Common PHP Functions and Code Snippets
This article presents a curated collection of useful PHP functions covering string generation, email encoding, validation, file handling, JSON/XML parsing, slug creation, IP detection, forced downloads, tag clouds, similarity checks, Gravatar integration, text truncation, ZIP compression, URL handling, clickable link conversion, image resizing, and AJAX request detection, each accompanied by ready‑to‑use code examples.
1. Readable random string – Generates a pronounceable random string by alternating consonants and vowels.
function readable_random_string($length = 6){
$conso=array("b","c","d","f","g","h","j","k","l","m","n","p","r","s","t","v","w","x","y","z");
$vocal=array("a","e","i","o","u");
$password="";
srand((double)microtime()*1000000);
$max = $length/2;
for($i=1;$i<=$max;$i++){
$password .= $conso[rand(0,19)];
$password .= $vocal[rand(0,4)];
}
return $password;
}2. Simple random string – Creates a generic random string useful for passwords.
function generate_rand($l){
$c="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
srand((double)microtime()*1000000);
for($i=0;$i<$l;$i++){
$rand .= $c[rand()%strlen($c)];
}
return $rand;
}3. Email address encoder – Obfuscates an email address using HTML character entities to deter spam bots.
function encode_email($email='[email protected]', $linkText='Contact Us', $attrs='class="emailencoder"'){
$email = str_replace('@','@',$email);
$email = str_replace('.','.', $email);
$email = str_split($email,5);
$linkText = str_replace('@','@',$linkText);
$linkText = str_replace('.','.', $linkText);
$linkText = str_split($linkText,5);
$part1 = '<a href="mailto:';
$part2 = '';
$part3 = '" '.$attrs.'>';
$part4 = '</a>';
$encoded = '<script type="text/javascript">';
$encoded .= "document.write('$part1');";
foreach($email as $e){ $encoded .= "document.write('$e');"; }
$encoded .= "document.write('$part3');";
foreach($linkText as $l){ $encoded .= "document.write('$l');"; }
$encoded .= "document.write('$part4');";
$encoded .= '</script>';
return $encoded;
}4. Email validator – Checks email format and optionally verifies MX records.
function is_valid_email($email, $test_mx = false){
if(eregi("^([_a-z0-9-]+)(\.[_a-z0-9-]+)*@([a-z0-9-]+)(\.[a-z0-9-]+)*(\.[a-z]{2,4})$", $email)){
if($test_mx){
list($username,$domain) = split("@", $email);
return getmxrr($domain, $mxrecords);
}
return true;
}
return false;
}5. List directory contents – Outputs links for each file in a directory, skipping '.' and '..'.
function list_files($dir){
if(is_dir($dir) && ($handle = opendir($dir))){
while(($file = readdir($handle)) !== false){
if($file != "." && $file != ".." && $file != "Thumbs.db"){
echo '<a target="_blank" href="'.$dir.$file.'">'.$file.'</a><br>\n';
}
}
closedir($handle);
}
}6. Destroy directory – Recursively deletes a directory and all its contents.
function destroyDir($dir, $virtual = false){
$ds = DIRECTORY_SEPARATOR;
$dir = $virtual ? realpath($dir) : $dir;
$dir = substr($dir,-1) == $ds ? substr($dir,0,-1) : $dir;
if(is_dir($dir) && $handle = opendir($dir)){
while($file = readdir($handle)){
if($file == '.' || $file == '..') continue;
if(is_dir($dir.$ds.$file)) destroyDir($dir.$ds.$file);
else unlink($dir.$ds.$file);
}
closedir($handle);
rmdir($dir);
return true;
}
return false;
}7. JSON parsing – Decodes a JSON string into an object and accesses its properties.
$json_string='{"id":1,"name":"foo","email":"[email protected]","interest":["wordpress","php"]}';
$obj = json_decode($json_string);
echo $obj->name; // prints foo
echo $obj->interest[1]; // prints php8. XML parsing – Loads an XML string with SimpleXML and iterates over user nodes.
$xml_string = "<?xml version='1.0'?><users><user id='398'><name>Foo</name><email>[email protected]</email></user><user id='867'><name>Foobar</name><email>[email protected]</email></user></users>";
$xml = simplexml_load_string($xml_string);
foreach($xml->user as $user){
echo $user['id'], ' ';
echo $user->name, ' ';
echo $user->email, "<br>";
}9. Slug creator – Generates a URL‑friendly slug from a string.
function create_slug($string){
$slug = preg_replace('/[^A-Za-z0-9-]+/', '-', $string);
return $slug;
}10. Real IP address – Retrieves the client’s true IP even behind proxies.
function getRealIpAddr(){
if(!empty($_SERVER['HTTP_CLIENT_IP'])) $ip = $_SERVER['HTTP_CLIENT_IP'];
elseif(!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
else $ip = $_SERVER['REMOTE_ADDR'];
return $ip;
}11. Forced file download – Sends appropriate headers to force a file download.
function force_download($file){
if(isset($file) && file_exists($file)){
header('Content-length: '.filesize($file));
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="'.$file.'"');
readfile($file);
} else {
echo 'No file selected';
}
}12. Tag cloud generator – Builds an HTML tag cloud with font sizes scaled to tag frequency.
function getCloud($data=array(), $minFontSize=12, $maxFontSize=30){
$minimumCount = min(array_values($data));
$maximumCount = max(array_values($data));
$spread = $maximumCount - $minimumCount;
$spread == 0 && $spread = 1;
$cloudTags = array();
foreach($data as $tag=>$count){
$size = $minFontSize + ($count-$minimumCount) * ($maxFontSize-$minFontSize) / $spread;
$cloudTags[] = '<a style="font-size:'.floor($size).'px" href="#" title="'.$tag.' returned a count of '.$count.'">'.htmlspecialchars(stripslashes($tag)).'</a>';
}
return implode("\n", $cloudTags)."\n";
}13. String similarity – Uses similar_text to compute percentage similarity between two strings.
similar_text($string1, $string2, $percent); // $percent holds similarity percentage14. Gravatar display – Generates an <img> tag for a Gravatar based on an email address.
function show_gravatar($email, $size, $default, $rating){
echo '<img src="http://www.gravatar.com/avatar.php?gravatar_id='.md5($email).'&default='.$default.'&size='.$size.'&rating='.$rating.'" width="'.$size.'px" height="'.$size.'px" />';
}15. Word‑break truncation – Truncates a string at a specified breakpoint and appends an ellipsis.
function myTruncate($string, $limit, $break=".", $pad="..."){
if(strlen($string) <= $limit) return $string;
if(($breakpoint = strpos($string, $break, $limit)) !== false && $breakpoint < strlen($string)-1){
$string = substr($string, 0, $breakpoint) . $pad;
}
return $string;
}16. ZIP archive creation – Compresses an array of files into a ZIP archive.
function create_zip($files=array(), $destination='', $overwrite=false){
if(file_exists($destination) && !$overwrite) return false;
$valid_files = array();
foreach($files as $file){ if(file_exists($file)) $valid_files[] = $file; }
if(count($valid_files)){
$zip = new ZipArchive();
if($zip->open($destination, $overwrite ? ZipArchive::OVERWRITE : ZipArchive::CREATE) !== true) return false;
foreach($valid_files as $file) $zip->addFile($file, $file);
$zip->close();
return file_exists($destination);
}
return false;
}17. ZIP extraction – Extracts a ZIP file to a specified directory.
function unzip_file($file, $destination){
$zip = new ZipArchive();
if($zip->open($file) !== TRUE) die('Could not open archive');
$zip->extractTo($destination);
$zip->close();
echo 'Archive extracted to directory';
}18. Prepend http to URLs – Ensures a URL starts with http:// or ftp:// .
if(!preg_match('/^(http|ftp):/', $_POST['url'])){
$_POST['url'] = 'http://'.$_POST['url'];
}19. Clickable link conversion – Converts plain URLs and email addresses in text into HTML links.
function makeClickableLinks($text){
$text = eregi_replace('(((f|ht){1}tp://)[-a-zA-Z0-9@:%_+.~#?&//=]+)', '<a href="\1">\1</a>', $text);
$text = eregi_replace('([[:space:]()[{}])(www.[-a-zA-Z0-9@:%_+.~#?&//=]+)', '\1<a href="http://\2">\2</a>', $text);
$text = eregi_replace('([_.0-9a-z-]+@([0-9a-z][0-9a-z-]+.)+[a-z]{2,3})', '<a href="mailto:\1">\1</a>', $text);
return $text;
}20. Image resizing – Resizes an image while preserving aspect ratio.
function resize_image($filename, $tmpname, $xmax, $ymax){
$ext = pathinfo($filename, PATHINFO_EXTENSION);
if($ext == 'jpg' || $ext == 'jpeg') $im = imagecreatefromjpeg($tmpname);
elseif($ext == 'png') $im = imagecreatefrompng($tmpname);
elseif($ext == 'gif') $im = imagecreatefromgif($tmpname);
$x = imagesx($im);
$y = imagesy($im);
if($x <= $xmax && $y <= $ymax) return $im;
if($x >= $y){ $newx = $xmax; $newy = $newx * $y / $x; }
else { $newy = $ymax; $newx = $x * $ymax / $y; }
$im2 = imagecreatetruecolor($newx, $newy);
imagecopyresized($im2, $im, 0,0,0,0, floor($newx), floor($newy), $x, $y);
return $im2;
}21. AJAX request detection – Determines whether the current request was made via AJAX.
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest'){
// AJAX request handling
} else {
// regular request handling
}php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.