10 Most Important PHP Code Snippets for Web Developers
Here in this Post I am sharing some most important PHP code snippets which are used in day to day life of web developer.
HTML Mail
This code will send the mail in HTML format.
sendmail.php
{code type=codetype}
<?php
//change this to your email.
$to = “test@test.com”;
$from = “test2@test2.com”;
$subject = “Call for verification”;
//begin of HTML message
$message = ”
<html>
<body>
Test Mail<br>
test mail<br>
testmail<br><br>
Final test mail
</body>
</html>”; //end of message
$headers = “From: $from\r\n”;
$headers .= “Content-type: text/html\r\n”;
//options to send to cc+bcc
//$headers .= “Cc: [email]test3@test3.com[/email]“;
//$headers .= “Bcc: [email]test4@test4.com[/email]“;
// now lets send the email.
mail($to, $subject, $message, $headers);
echo “Message has been sent….!”;
?>
{/code}
Text to Image Convertor
This code will convert the given text to image format. It is generally used for captcha purpose and also to save email addresses from BOTs
form.php
{code type=codetype}
<form action=”check.php” method=”post”>
<img src=”code.php”>
<input type=”text” name=”num” maxlength=”4″><br>
<input type=”submit” name=”submit” value=”Check”>
</form>
{/code}
code.php
{code type=codetype}
<?php
// Usage <img src=”textToImage.php?text=emailAddress@emailProvider.com”>
header (“Content-type: image/png”);
$textToConvert = rand(1111,9999);
$font = 4;
$width = ImageFontWidth($font) * strlen($textToConvert);
$height = ImageFontHeight($font);
$im = @imagecreate ($width,$height);
$background_color = imagecolorallocate ($im, 255, 255, 255); //this means it’s white bg
$text_color = imagecolorallocate ($im, 0, 0,0);//and of course black text
imagestring ($im, $font, 0, 0, $textToConvert, $text_color);
imagepng ($im);
session_start();
$_SESSION['img'] = $textToConvert;
?>
{/code}
check.php
{code type=codetype}
<?php
session_start();
if($_SESSION['img'] != $_POST['num']){
echo “The number you entered doesnot match the image.<br>
<a href=\”form.php\”>Try Again</a><br>”;
}else{
echo “The numbers Match!<br>
<a href=\”form.php\”>Try Again</a><br>”;
}
?>
{/code}
Valid Email Address
This code will check if the email address format is valid or not
check.php
{code type=codetype}
<?php
$email=”a@a.c.com”;
if(eregi(“^([_a-z0-9-]+)(\.[_a-z0-9-]+)*@([a-z0-9-]+)(\.[a-z0-9-]+)*(\.[a-z]{2,4})$”, $email))
{
echo “Valid Email Address”;
}
else
{
echo “Invalid email address”;
}
?>
{/code}
List Directory Content
This code will list directory contents.
code.php
{code type=codetype}
<?php
$dir=’c:\test’;
if(is_dir($dir))
{
if($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);
}
}
?>
{/code}
Get Real IP Address of the Client
This code will help you get the real IP address of the client. It checks if any proxy is used.
getip.php
{code type=codetype}
<?php
if (!empty($_SERVER['HTTP_CLIENT_IP']))
{
$ip=$_SERVER['HTTP_CLIENT_IP'];
}
elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR']))
//to check ip is pass from proxy
{
$ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
}
else
{
$ip=$_SERVER['REMOTE_ADDR'];
}
echo $ip;
?>
{/code}
Download File Forcefully
This code will enable the client to download the file forcefully.
forcedownload.php
{code type=codetype}
<?php
$file = “C:\test.jpg”;
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”;
}
?>
{/code}
Add Http to URL
This codes adds and “http://” to the url specified to it
addhttp.php
{code type=codetype}
<?php
$url = “myphpscriptz.com”;
if (!preg_match(“/^(http|ftp):/”, $url))
{
$url = ‘http://’.$url;
echo $url;
}
?>
{/code}
Convert URL to Link
This code converts the given URL to a Link
urltolink.php
{code type=codetype}
<?php
$text = “http://myphpscriptz.com”;
$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);
echo $text;
?>
{/code}
Display Gravatar Image
This code displays gravatar image
gravatar.php
{code type=codetype}
<?php
/******************
*@email – Email address to show gravatar for
*@size – size of gravatar
*@default – URL of default gravatar to use
*@rating – rating of Gravatar(G, PG, R, X)
*/
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” />’;
}
$email=”abhi.sanghvi@yahoo.co.in”;
$size=100;
$default = “http://myphpscriptz.com”;
$rating = “G”;
show_gravatar($email, $size, $default, $rating);
?>
{/code}
Unzip File using PHP
This code unzip the zip file on server
unzip.php
{code type=codetype}
<?php
/**********************
*@file – path to zip file
*@destination – destination directory for unzipped files
***********************/
$file=”test.zip”;
$destination=”unzip”;
// create object
$zip = new ZipArchive() ;
// open archive
if ($zip->open($file) !== TRUE) {
die (‘Could not open archive’);
}
// extract contents to destination directory
$zip->extractTo($destination);
// close archive
$zip->close();
echo ‘Archive extracted to directory’;
?>
{/code}
You can download all the above mentioned code here
Related posts:
- PHP : Array Functions Tutorial – Part 2
- PHP : Array Functions Tutorial – Part 1
- Function : Check if array index is set and whether it has a value.
- How to crop an image using jQuery and PHP
- How to get the URL of the Current Page using PHP Server Variables
- 21 Most Useful Firefox Add-ons For Web Designers And Developers
- 11 Most Important String Functions in PHP a programmer should know
- What are class, methods, objects and instance in PHP – Object Oriented Concepts
- CSV file upload and save it to MySQL database using PHP Code
- A code for the new Rupee Symbol for the Internet By Symbiosis (SICSR) Students

I believe you mean most awkward and retarded. Not best.