PHP Snippets
1 2 3 »globsort
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
?>
link_track
Information
(PHP Version >= 4.3.0)Functions used in this snippet: file_exists, is_readable, is_writable, unserialize, file_get_contents, is_array, array_key_exists, isset, fopen, fwrite, serialize, fclose.
Description
mixed link_track( [ int id]] )
Keeps track of the number of times that clients have clicked a link. To find the number of clicks that a link has, leave id blank. To update a certain link, set id to the id of the link that you want to update.
Snippet
<?php
function link_track($id=NULL){
$file = 'somefile.txt'; // this is the file stuff is stored in
// make sure php can read and write to this file
if(!file_exists($file) || !is_readable($file) || !is_writable($file)){
return;
}
$links = array(0=>'http://www.bigtoach.com', 1=>'http://www.neverside.com', 2=>'http://www.google.com'); // change these to your links
$array = unserialize(file_get_contents($file));
$array = is_array($array) ? $array : array();
if($id !== NULL){
if(!array_key_exists($id, $links)){
return 'sorry there is no link to the id ' . $id;
}
$array[$id] = isset($array[$id]) ? $array[$id] + 1 : 1;
$fp = fopen($file, 'w');
fwrite($fp, serialize($array));
fclose($fp);
return $links[$id];
}
$ret = array();
foreach($links as $key=>$value){
$ret[$key]['site'] = $value;
$ret[$key]['clicks'] = isset($array[$key]) ? $array[$key] : 0;
$ret[$key]['id'] = $key;
}
return $ret;
}
?>
Example
link_track Can be used in the following way:
<?php
// this snippet is to find # of clicks
$array = link_track(); // gets the array
foreach($array as $key=>$value){
echo '<a href="pass.php?id=' . $value['id'] . '">' . $value['site'] . ' (' . $value['clicks'] . ' Clicks)</a><br />';
}
// you can also get click counts like this
echo '<a href="pass.php?id=0">http://www.bigtoach.com (' . $array[0]['clicks'] . ' Clicks)</a>';
// pass.php would look as the following
$_GET['id'] = isset($_GET['id']) ? intval($_GET['id']) : NULL;
$redirect = link_track($_GET['id']);
if(strstr($redirect, 'http')){
header('Location: ' . $redirect);
}else{
echo 'Sorry that link does not exist';
}
?>
dir_recurse
Information
(PHP Version >= 3)Functions used in this snippet: opendir, readdir, is_dir, dir_recurse, filesize, closedir, isset.
Description
array dir_recurse( str dir, bool filesize )
Recursively find all files and folders underneath the folder dir.
If the optional filesize is set to true the array will have the indexes be the filenames, and the values be the filsize of the filenames.
Snippet
<?php
function dir_recurse($dir, $filesize=false){
if ($fh = opendir($dir)) {
while(false !== ($file = readdir($fh))){
if($file != "." && $file != "..") {
if(is_dir($dir . '/' . $file)){
$data[$file] = dir_recurse($dir . '/' . $file, $filesize);
}else{
if($filesize){
$data[$file] = filesize($dir . '/' . $file);
}else{
$data[] = $file;
}
}
}
}
closedir($fh);
}
return (isset($data) ? $data : array());
}
?>
Example
dir_recurse Can be used in the following way:
<?php
print_r(dir_recurse('.'));
// returns the directory structure of the directory that the script is in
print_r(dir_recurse('some/path/to/dir'));
// returns dir structure of some/path/to/dir
print_r(dir_recurse('.', true));
// returns filesizes of all files above the current working directory.
// if you have PHP 5 and you want to easily show the dir folder size you can do the following
function dummy_func($value){
global $_dummy_var;
$_dummy_var += $value;
}
array_walk_recursive(dir_recurse('.'), 'dummy_func');
echo 'That directory is ' . $_dummy_var . ' Bytes big';
?>
1 2 3 »