10 Most Important PHP Code Snippets for Web Developers

0saves

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>
&nbsp;&nbsp;&nbsp;&nbsp;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

If you enjoyed this post, please consider leaving a comment or subscribing to the RSS feed to have future articles delivered to your feed reader.

Related posts:

  1. PHP : Array Functions Tutorial – Part 2
  2. PHP : Array Functions Tutorial – Part 1
  3. Function : Check if array index is set and whether it has a value.
  4. How to crop an image using jQuery and PHP
  5. How to get the URL of the Current Page using PHP Server Variables
  6. 21 Most Useful Firefox Add-ons For Web Designers And Developers
  7. 11 Most Important String Functions in PHP a programmer should know
  8. What are class, methods, objects and instance in PHP – Object Oriented Concepts
  9. CSV file upload and save it to MySQL database using PHP Code
  10. A code for the new Rupee Symbol for the Internet By Symbiosis (SICSR) Students

Related Posts

About the Author: Abhishek Sanghvi

Hi Friends, my name is Abhishek Sanghvi and I am the founder of this “open source script” site MYPHPSCRIPTZ. I have been learning and practising PHP from the last 3 years. You could always contact me if you wish to have some code for your need. I would surely try and solve them for you at abhishek(at)myphpscriptz(dot)com

6 Comments + Add Comment

  • [...] reading here: 10 Most Important PHP Code Snippets for Web Developers … No [...]

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

  • Valid Email address regex does not conform to RFC2821. It misses various valid email addresses, so call it that, “invalid email address verification”.

  • Hi mario,
    Thanks for your valuable comment. Its a basic tutorial for noobs, smart guys knows how to handle such issues properly. They dont need such basic tutorials!! What do you say?

  • protectionspecialties…

    [...]10 Most Important PHP Code Snippets for Web Developers | My PHP Scripts | A Hub for PHP Scripts, PHP tutorial, PHP codes and lots more[...]…

  • Access Control North East…

    [...]10 Most Important PHP Code Snippets for Web Developers | My PHP Scripts | A Hub for PHP Scripts, PHP tutorial, PHP codes and lots more[...]…

Leave a comment


two + = four

CommentLuv badge