PHP practical code snippet (2 ),
1. Convert URL: from string to hyperlink
If you are developing a forum, blog, or submitting a regular form, you often need to access a website. With this function, the URL string can be automatically converted to a hyperlink.
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; }
Syntax:
<?php$text = "This is my first post on http://blog.koonk.com";$text = makeClickableLinks($text);echo $text;?>
2. prevent multiple IP addresses from accessing your website
This code snippet allows you to prohibit certain IP addresses from accessing your website.
if ( !file_exists('blocked_ips.txt') ) { $deny_ips = array( '127.0.0.1', '192.168.1.1', '83.76.27.9', '192.168.1.163' );} else { $deny_ips = file('blocked_ips.txt');}// read user ip adress:$ip = isset($_SERVER['REMOTE_ADDR']) ? trim($_SERVER['REMOTE_ADDR']) : ''; // search current IP in $deny_ips arrayif ( (array_search($ip, $deny_ips))!== FALSE ) { // address is blocked: echo 'Your IP adress ('.$ip.') was blocked!'; exit;}3. Mandatory File Download
If you need to download a specific file without opening a new window, the following code snippets can help you.
function force_download($file) { $dir = "../log/exports/"; if ((isset($file))&&(file_exists($dir.$file))) { header("Content-type: application/force-download"); header('Content-Disposition: inline; filename="' . $dir.$file . '"'); header("Content-Transfer-Encoding: Binary"); header("Content-length: ".filesize($dir.$file)); header('Content-Type: application/octet-stream'); header('Content-Disposition: attachment; filename="' . $file . '"'); readfile("$dir$file"); } else { echo "No file selected"; } }
Syntax:
<phpforce_download("image.jpg");?>4. Create JSON data
You can use the following PHP snippets to create JSON data so that you can easily create mobile app Web Services.
$json_data = array ('id'=>1,'name'=>"Mohit");echo json_encode($json_data);5. zip file Compression
The following PHP snippets can be used to instantly compress zip files.
function create_zip($files = array(),$destination = '',$overwrite = false) { //if the zip file already exists and overwrite is false, return false if(file_exists($destination) && !$overwrite) { return false; } //vars $valid_files = array(); //if files were passed in... if(is_array($files)) { //cycle through each file foreach($files as $file) { //make sure the file exists if(file_exists($file)) { $valid_files[] = $file; } } } //if we have good files... if(count($valid_files)) { //create the archive $zip = new ZipArchive(); if($zip->open($destination,$overwrite ? ZIPARCHIVE::OVERWRITE : ZIPARCHIVE::CREATE) !== true) { return false; } //add the files foreach($valid_files as $file) { $zip->addFile($file,$file); } //debug //echo 'The zip archive contains ',$zip->numFiles,' files with a status of ',$zip->status; //close the zip -- done! $zip->close(); //check to make sure the file exists return file_exists($destination); } else { return false; } }
Syntax:
<?php$files=array('file1.jpg', 'file2.jpg', 'file3.gif'); create_zip($files, 'myzipfile.zip', true); ?>6. decompress the file
function unzip($location,$newLocation){ if(exec("unzip $location",$arr)){ mkdir($newLocation); for($i = 1;$i< count($arr);$i++){ $file = trim(preg_replace("~inflating: ~","",$arr[$i])); copy($location.'/'.$file,$newLocation.'/'.$file); unlink($location.'/'.$file); } return TRUE; }else{ return FALSE; }}
Syntax:
<?phpunzip('test.zip','unziped/test'); //File would be unzipped in unziped/test folder?>7. resize the image
function resize_image($filename, $tmpname, $xmax, $ymax) { $ext = explode(".", $filename); $ext = $ext[count($ext)-1]; 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 / $y * $newy; } $im2 = imagecreatetruecolor($newx, $newy); imagecopyresized($im2, $im, 0, 0, 0, 0, floor($newx), floor($newy), $x, $y); return $im2; }8. Use mail () to send an email
function send_mail($to,$subject,$body){$headers = "From: KOONK\r\n";$headers .= "Reply-To: blog@koonk.com\r\n";$headers .= "Return-Path: blog@koonk.com\r\n";$headers .= "X-Mailer: PHP5\n";$headers .= 'MIME-Version: 1.0' . "\n";$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";mail($to,$subject,$body,$headers);}
Syntax:
<?php$to = "admin@koonk.com";$subject = "This is a test mail";$body = "Hello World!";send_mail($to,$subject,$body);?>
9. Convert seconds to days, hours, and minutes
function secsToStr($secs) { if($secs>=86400){$days=floor($secs/86400);$secs=$secs%86400;$r=$days.' day';if($days<>1){$r.='s';}if($secs>0){$r.=', ';}} if($secs>=3600){$hours=floor($secs/3600);$secs=$secs%3600;$r.=$hours.' hour';if($hours<>1){$r.='s';}if($secs>0){$r.=', ';}} if($secs>=60){$minutes=floor($secs/60);$secs=$secs%60;$r.=$minutes.' minute';if($minutes<>1){$r.='s';}if($secs>0){$r.=', ';}} $r.=$secs.' second';if($secs<>1){$r.='s';} return $r;}
Syntax:
<?php$seconds = "56789";$output = secsToStr($seconds);echo $output;?>
10. Database Connection
Connect to the MySQL database
<?php$DBNAME = 'koonk';$HOST = 'localhost';$DBUSER = 'root';$DBPASS = 'koonk';$CONNECT = mysql_connect($HOST,$DBUSER,$DBPASS);if(!$CONNECT){ echo 'MySQL Error: '.mysql_error();}$SELECT = mysql_select_db($DBNAME);if(!$SELECT){ echo 'MySQL Error: '.mysql_error();}?>