PHP Snippets
1 2 3 » ... 10globsort
Information
(PHP Version >= 4.3.0)Functions used in this snippet: glob, print_r, empty, count, array_key_exists, var_dump, method, sort, array_keys.
Description
array globsort( string pattern, mixed flags, string sortby)
Globsort returns an array of files that meet the pattern pattern sorted by the parameter sortby. This uses the normal glob function and just sorts the resulting files by either: last modified date, created date, last accessed date, file size and file type.
You can change the way the different parameters sort the results by changing the sorts array from arsort to asort or vice versa.
The different parameters to pass in are based on the keys in the sorts and the methods array. By default they are: modified, created, accessed, size, type
Snippet
<?php
function globsort($pattern, $flags=NULL, $sortby='modified') {
$files = glob($pattern, $flags);
if(empty($files))
return array();
if($flags == GLOB_NOCHECK && count($files) == 1 && $files[0] == $pattern)
return array($pattern);
$methods = array(
'modified' => 'filemtime',
'created' => 'filectime',
'size' => 'filesize',
'type' => 'filetype',
'accessed' => 'fileatime'
);
$sorts = array(
'modified' => 'arsort',
'created' => 'arsort',
'size' => 'arsort',
'type' => 'asort',
'accessed' => 'arsort'
);
$method = array_key_exists($sortby, $methods) ? $methods[$sortby] : 'filemtime';
$sort = array_key_exists($sortby, $sorts) ? $sorts[$sortby] : 'arsort';
$tmp = array();
foreach($files as $file)
{
$tmp[$file] = $method($file);
}
$sort($tmp);
return array_keys($tmp);
}
?>
Example
globsort Can be used in the following way:
<?php
// Pretend we have a directory like this
// Created, Modified, Accessed, Size, Type, Name
// 2008-04-01, 2008-04-22, 2008-04-22, 152, file, file.txt
// 2008-03-01, 2008-04-24, 2008-04-26, 250, file, people.csv
// 2008-03-15, 2008-03-21, 2008-03-22, 34540, file, sound.wav
// 2008-01-04, 2008-04-25, 2008-04-26, 409, dir, Music
// Now some examples
// Default returns modified time with the most recently modified first
$files = globsort('*');
// Results in: Music/, people.csv, file.txt, sound.wav
// Sorted by Filesize
$files = globsort('*', NULL, 'filesize');
// Results in: sound.wav, Music/ people.csv, file.txt
// Sorted by Type
$files = glob('*', NULL, 'type');
// Results in: Music/, file.txt, people.wav, sound.wav
// Sorted by Last Accessed
$files = glob('*.*', NULL, 'accessed'); // Only filenames with extensions
// Results in: people.csv, file.txt, sound.wav
// Using one of the GLOB_* Constants and orders them by created date
$files = glob('*', GLOB_ONLYDIR, 'created');
// Results in: Music/ (there is only one folder...)
?>
find_filename
Information
(PHP Version >= 3)Functions used in this snippet: pathinfo, str_replace, file_exists.
Description
string find_filename( string filename )
Creates a unique filename if one already exists (similar to an operating systems naming schema Ex: file.ext already exists so the new file becomes file-1.ext)
Snippet
<?php
function find_filename($filename)
{
$info = pathinfo($filename);
$info['filename'] = str_replace('.' . $info['extension'], '', $filename);
$i = 1;
while(file_exists($filename))
{
$filename = $info['dirname'] . DIRECTORY_SEPARATOR . $info['filename'] . "-$i." . $info['extension'];
$i++;
}
return $filename;
}
?>
Example
find_filename Can be used in the following way:
<?php
<?php
// A file that does not exist
$filename = find_filename('file.txt'); // returns ./file.txt
touch($filename); // create file.txt so it exists now
$filename = find_filename('file.txt'); // returns ./file-1.txt
touch($filename) // create file-1.txt so it exists now
$filename = find_filename('file.txt'); // returns ./file-2.txt
// etc etc
?>
csv2array
Information
(PHP Version >= 3)Functions used in this snippet: file_exists, is_readable, file_get_contents, preg_replace, explode, array_map, unset, range, count, substr_count, reset.
Description
array csv2array( string file, boolean titles )
Takes a csv file and turns it into a multidimensional array. If you leave titles set to true it returns the array with the first line as the associative indexes of the array, if you set titles to false the first line is included in the values and the indexes are integers.
array2csv returns false if the file is not found or not readable.
Snippet
<?php
function csv2array($file, $titles=true)
{
if(!file_exists($file) || !is_readable($file))
{
return false;
}
$file = file_get_contents($file);
$file = preg_replace("/(\r\n|\r|\n\n)/ms", "\n", $file);
$lines = explode("\n", $file);
if($titles)
{
$titles = array_map('trim', explode(',',$lines[0]));
unset($lines[0]);
}
else
{
$titles = range(0, count(explode(',', $lines[0]), 1));
}
$return = array();
foreach($lines as $key => $line)
{
$peices = array_map('trim', explode(',', $line));
for($i=0;$i<count($peices);$i++)
{
$k = $i;
while(substr_count($peices[$k], '"') % 2 === 1)
{
$peices[$k] = $peices[$k] . ',' . $peices[$i + 1];
$i++;
unset($peices[$i]);
}
}
reset($peices);
foreach($peices as $column => $peice)
{
$return[$titles[$column]][$key] = $peice;
}
}
return $return;
}
?>
Example
csv2array Can be used in the following way:
<?php
<?php
/* In the example the csv is as follows:
Name,Title
Scott Roach,"Web Developer, CCi"
Annie Roach,Production Designer
*/
$csv = csv2array('file.csv');
print_r($csv);
/*
Array(
[Name] => Array(
[0] => Scott Roach
[1] => Annie Roach
)
[Title] => Array(
[0] => Web Developer, CCi
[1] => Production Designer
)
)
*/
$csv = csv2array('file.csv', false);
print_r($csv);
/*
Array(
[0] => Array(
[0] => Name
[1] => Scott Roach
[2] => Annie Roach
)
[1] => Array(
[0] => Title
[1] => "Web Developer, CCi"
[2] => Production Designer
)
)
*/
$csv = csv2array('non-existant-file.csv');
print_r($csv);
// False
?>
sendmail
Information
(PHP Version >= 3)Functions used in this snippet: trim, preg_math, rand, strip_tags, preg_replace, chunk_split, base64_encode, is_array, file_exists, pathinfo, file_get_contents, mail, implode.
Description
boolean sendmail( string to, string subject, string body, mixed file, string from, string additional )
Simply put, this function sends mail. It checks to see if the body is in html format, if so it will send it with the correct headers to be received as html. It also sends a plain text alternative for older browsers.
If the optional file is supplied, the function will send this file (or files if file is of type array) as an attachment.
You can also specify who the email should be from as well as the reply-to address.
If you need additional settings, you can pass them as mail headers in the additional parameter.
Snippet
<?php
function sendmail($to, $subject, $body, $file=NULL, $from='noreply@yourdomain.com', $additional='')
{
$boundary = 'SPROUT-19_16_18_15_21_20';
$headers = array();
$headers[] = 'From: ' . $from;
$headers[] = 'Reply-To: ' . $from;
if(trim($additional) !== '')
{
$headers[] = $additional;
}
$headers[] = 'MIME-Version: 1.0';
$headers[] = 'Content-Type: multipart/mixed; boundary="' . $boundary . '"';
$headers[] = 'Content-Transfer-Encoding: 7bit' . "\r\n";
$headers[] = "> This is a multi-part message in MIME format.\r\n";
$headers[] = '--' . $boundary;
// if there is html in the message, send it with the right settings and an alternative for crappy browsers
if(preg_match('/\<(html|body)/ims', $body))
{
$htmlbound = 'SPROUT-' . rand(100,9999);
$headers[] = 'Content-Type: multipart/alternative; boundary="' . $htmlbound . '"' . "\r\n";
$headers[] = '--' . $htmlbound;
$headers[] = 'Content-Type: text/plain; charset="iso-8859-1"';
$headers[] = 'Content-Transfer-Encoding: 7bit' . "\r\n";
$headers[] = strip_tags(preg_replace('/\<head\>(.+?)\<\/head\>/ims', '', $body)) . "\r\n\r\n";
$headers[] = '--' . $htmlbound;
$headers[] = 'Content-Type: text/html; charset="iso-8859-1"';
$headers[] = 'Content-Transfer-Encoding: base64' . "\r\n";
$headers[] = chunk_split(base64_encode($body));
$headers[] = "\r\n\r\n--" . $htmlbound . "--\r\n\r\n--" . $boundary;
}
else
{
$headers[] = 'Content-Type: text/plain; charset="iso-8859-1"';
$headers[] = 'Content-Transfer-Encoding: 7bit' . "\r\n";
$headers[] = $body . "\r\n\r\n";
$headers[] = '--' . $boundary;
}
// attach files if they are there
if($file !== NULL)
{
$files = (!is_array($file)) ? array($file) : $file;
foreach($files as $attachment)
{
if(!file_exists($attachment))
continue;
$path = pathinfo($attachment);
$headers[] = 'Content-Type: application/octet-stream; name="' . $path['basename'] . '"';
$headers[] = 'Content-Disposition: attachment; filename="' . $path['basename'] . '"';
$headers[] = "Content-Transfer-Encoding: base64\r\n";
$attach = chunk_split(base64_encode(file_get_contents($attachment)));
$headers[] = $attach;
$headers[] = '--' . $boundary;
}
}
return mail($to, $subject, '', implode("\r\n", $headers) . '--');
}
?>
Example
sendmail Can be used in the following way:
<?php
// Send an html file
sendmail('someone@domain.ext', 'Title', 'HTML CONTENT HERE');
// Send an email with an attachment
sendmail('someone@domain.ext', 'Title', 'Check out this picture', 'image.jpg');
// Send an html style email with multiple attachments
sendmail('someone@domain.ext', 'Title', 'HTML GOES HERE', array('product.jpg', 'productdetails.pdf'));
// Send a plaintext email from joeschmoe@domain.ext
sendmail('someone@domain.ext', 'Title', 'PLAIN TEXT GOES HERE', NULL, 'joeschmoe@domain.ext');
?>
excerpt
Information
(PHP Version >= 3)Functions used in this snippet: preg_match_all, preg_replace, substr, strrpos, strpos.
Description
str excerpt( str excerpt, int length )
Returns an excerpt of the string excerpt with a maximum length of length. This function is useful if you have HTML in the excerpt because it will keep the HTML structure intact. It does this by keeping the HTML tags in the excerpt, and appending the empty HTML tags at the end of the excerpt.
Snippet
<?php
function excerpt($excerpt, $length)
{
preg_match_all('/<[^>]+>/', $excerpt, $matches);
$excerpt = preg_replace('/<[^>]+>/', '|!|', $excerpt);
$excerpt = substr($excerpt, 0, strrpos(substr($excerpt, 0, $length), ' '));
$exhausted = false;
foreach($matches[0] as $match)
{
if(strpos($excerpt, '|!|') !== false)
{
$excerpt = preg_replace('/\|\!\|/', $match, $excerpt, 1);
}
else
{
if(!$exhausted)
{
$excerpt .= '...';
$exhausted = true;
}
$excerpt .= $match;
}
}
return $excerpt;
}
?>
Example
excerpt Can be used in the following way:
<?php
$str = '<p>Hello <a href="http://www.bigtoach.com">Test</a> This is just a test to see if <strong>Nested</strong> <em>Tags</em> <em>Will work</em></p>';
echo excerpt($str, 80);
// Produces The Following
// <p>Hello <a href="http://www.bigtoach.com">Test</a> This is just a test to see if <strong>Nested</strong> <em>Tags</em>...<em></em></p>
?>
1 2 3 » ... 10