Name |
Code |
Database Connection-establish a connection with MySQL
|
Connect database connections
< ? php $host="mysql153.secureserver.net"; $uname="abcd"; $pass="password"; $connection= mysql_connect ($host, $uname, $pass); if (! $connection) { die ("A connection to the Server could not be established!"); } else { echo "User root logged into to MySQL server ",$host," successfully."; } ?>
Close database connections
< ? php @mysql_connect("mysql153.secureserver.net","abcd","password") or die("Could not connect to MySQL server!"); @mysql_select_db("abcd") or die("Could not select database!"); echo "You're connected to a MySQL database!"; mysql_close(); ? >
|
Program For Date Sort
|
< ?
function date_sort($a, $b)
{
list($a_month, $a_day, $a_year) = explode('/', $a);
list($b_month, $b_day, $b_year) = explode('/', $b);
if ($a_year > $b_year ) return 1;
if ($a_year < $b_year ) return -1;
if ($a_month > $b_month) return 1;
if ($a_month < $b_month) return -1;
if ($a_day > $b_day ) return 1;
if ($a_day < $b_day ) return -1;
return 0;
}
$dates = array('12/14/2000', '08/10/2001', '08/07/1999');
usort($dates, 'date_sort');
?>
|
Delete Lines From a File
|
< ? php
// this function strips a specific line from a file
// if no linenumber is specified, last line is stripped
// if a line is stripped, functions returns True else false
//
// e.g.
// cutline('foo.txt'); // strip last line
// cutline('foo.txt',1); // strip first line
/* its probably a good idea to allow access to this file via a password. otherwise, anyone that knows its in your directory could delete lines of text from the file you specify below! */
function cutline($filename,$line_no=-1)
{
$strip_return=FALSE;
$data=file($filename);
$pipe=fopen($filename,'w');
$size=count($data);
if($line_no==-1) $skip=$size-1;
else $skip=$line_no-1;
for($line=0;$line<$size;$line++)
if($line!=$skip)
fputs($pipe,$data[$line]);
else
$strip_return=TRUE;
return $strip_return;
}
cutline('foo.txt',6); // deletes line 6 in foo.txt
? >
|
Display text on specified number of characters
|
< ?
function cuttext($text, $maxChars = 20, $tail = "")
{
$arrWords = explode(" ", $text);
$temp = "";
for ($i=0; $i< count($arrWords); $i++) {
$temp .= ($i == 0 ? $arrWords[$i] : " " . $arrWords[$i]);
if (strlen($temp) < $maxChars) {
$returnStr = $temp;
} else {
if (strlen($text) > $maxChars)
return $returnStr.$tail;
else
return $returnStr;
}
}
return $returnStr;
}
* EXAMPLE *
$string = "A quick brown fox jumps over the lazy dog.";
echo cuttext($string, 30, "...");
* OUT PUT *
?>
A quick brown fox jumps over...
|
Email validation with Regular Expressions
|
< ? php
if (isset($_POST['posted']))
{
$email = $_POST['email'];
$theresults = ereg("^[^@ ]+@[^@ ]+\.[^@ \.]+$", $email, $trashed);
if ($theresults)
{
$isamatch = "Valid";
}
else
{
$isamatch = "Invalid";
}
echo "Email address validation says $email is " . $isamatch;
}
? >
|
Multiple File Upload
|
< ? php
$numoffile = 5;
// Fix path of your file to be uploaded, don't forget to CHMOD 777 to this folder
$file_dir = "/home/webs/dmonster.com/subdomain/files/";
if ($_POST)
{
for ($i=0;$i<$numoffile;$i++)
{
if (trim($_FILES['myfiles']['name'][$i])!="")
{
$newfile = $file_dir.$_FILES['myfiles']['name'][$i];
move_uploaded_file($_FILES['myfiles']['tmp_name'][$i], $newfile);
$j++;
}
}
}
if (isset($j)&&$j>0) print "Your file(s) has been uploaded.
";
print "< form method='post' enctype='multipart/form-data'>";
for($i=0;$i<$numoffile;$i++)
{
print "< input type='file' name='myfiles[]' size='30'>
";
}
print "< input type='submit' name='action' value='Upload'>";
print "< / form>";
? >
|
Get a Random File from a Directory
|
< ?
function getRandomFile($start_dir)
{
/*
returns the name of one random file from within a directory
*/
chdir($start_dir);
$dir = opendir('.');
while (($myfile = readdir($dir)) !==false)
{
if ($myfile != '.' && $myfile != '..' && is_file($myfile) && $myfile ! = 'resource.frk')
{
$files[] = $myfile;
}
}
closedir($dir);
chdir('../');
srand ((float) microtime() * 10000000);
$file = array_rand($files);
return $files[$file];
}
?>
Example 1: random image:
< ?
$imagesDir = 'images/something';
$imageURL = getRandomFile($imagesDir);
$image
echo "< img src='{$imagesDir}/{$imageURL} ' alt='' />";
? >
Example 2: random include():
< ?
$ includeDir = 'randomquotes';
$quoteFile = getRandomFile($includeDir);
include("{$includeDir}/{$quoteFile}");
? >
|
Recursive copy, delete function |
Recursive Delete Function
function DELETE_RECURSIVE_DIRS($dirname) { // recursive function to delete // all subdirectories and contents: if(is_dir($dirname))$dir_handle=opendir($dirname); while($file=readdir($dir_handle)) { if($file!="." && $file!="..") { if(!is_dir($dirname."/".$file))unlink ($dirname."/".$file); else DELETE_RECURSIVE_DIRS($dirname."/".$file); } } closedir($dir_handle); rmdir($dirname); return true; }
Recursive Copy Function
function COPY_RECURSIVE_DIRS($dirsource, $dirdest) { // recursive function to copy // all subdirectories and contents: if(is_dir($dirsource))$dir_handle=opendir($dirsource); mkdir($dirdest."/".$dirsource, 0750); while($file=readdir($dir_handle)) { if($file!="." && $file!="..") { if(!is_dir($dirsource."/".$file)) copy ($dirsource."/".$file, $dirdest."/".$dirsource."/".$file); else COPY_RECURSIVE_DIRS($dirsource."/".$file, $dirdest); } } closedir($dir_handle); return true; }
|
Return an Array of Files within a Directory
|
< ?
function listFilesInDir($start_dir)
{
/*
returns an array of files in $start_dir (not recursive)
*/
$files = array();
$dir = opendir($start_dir);
while(($myfile = readdir($dir)) !== false)
{
if($myfile != '.' && $myfile != '..' && !is_file($myfile) && $myfile ! = 'resource.frk' && !eregi('^Icon',$myfile) )
{
$files[] = $myfile;
}
}
closedir($dir);
return $files;
}
?>
Example:
< ?
$ dir = 'downloads/wordDocs/public/topic_1';
$wordDocs = listFilesInDir($dir);
foreach($wordDocs as $key => $fileName)
{
echo "{$fileName}";
}
?>
|
Simple PHP File Find function
|
< ? php
// filefind accepts two parameters:
// $basedirectory : The root of the directory tree to search
// $needle : The file to find
//
// Return Value:
// The fully qualified file name of the target file if it is found,
// if the target file cannot be found then an empty string is returned.
//
// Sample Usage:
// $fullpath = filefind($DOCUMENT_ROOT, "scriptEngine.php");
// if ($fullpath != "")
// { Some processing (presumably involving scriptEngine.php) }
//
// NOTE: The search is case sensitive (because UNIX is)
// This construct is to prevent the same include file from being included more than once,
// lest it bloat the code.
if (!defined("__DLIB_FILEFIND_DEFINED"))
{
define('__DLIB_FILEFIND_DEFINED', TRUE);
function filefind ($basedirectory, $needle)
{
$handle=opendir($basedirectory);
while ($file = readdir($handle))
{
if (($file == ".") || ($file == ".."))
continue;
if (is_dir($basedirectory . '/' . $file))
{
$subDirResult = filefind($basedirectory . '/' . $file, $needle);
if ($subDirResult != "")
{
closedir($handle);
return $subDirResult;
}
} // if (is_dir($file))
if (strcmp($file, $needle) == 0)
{
closedir($handle);
return $basedirectory . '/' . $needle;
}
} // while ($file = readdir($handle))
closedir($handle);
return "";
} // function filefind
}
? >
|