Following are list of 15 most useful PHP code snippets that a PHP developer will need at any point in his career. Few of the snippets are shared from my projects and few are taken from useful php websites from internet. You may also want to comment on any of the code or also you can share your code snippet through comment section if you think it may be useful for others.
1. Send Mail using mail function in PHP
$to = "[email protected]";
$subject = "VIRALPATEL.net";
$body = "Body of your message here you can use HTML too. e.g. <br> <b> Bold </b>";
$headers = "From: Peter\r\n";
$headers .= "Reply-To: [email protected]\r\n";
$headers .= "Return-Path: [email protected]\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);
?>
Code language: PHP (php)
2. Base64 Encode and Decode String in PHP
function base64url_encode($plainText) {
$base64 = base64_encode($plainText);
$base64url = strtr($base64, '+/=', '-_,');
return $base64url;
}
function base64url_decode($plainText) {
$base64url = strtr($plainText, '-_,', '+/=');
$base64 = base64_decode($base64url);
return $base64;
}
Code language: PHP (php)
3. Get Remote IP Address in PHP
function getRemoteIPAddress() {
$ip = $_SERVER['REMOTE_ADDR'];
return $ip;
}
Code language: PHP (php)
The above code will not work in case your client is behind proxy server. In that case use below function to get real IP address of client.function getRealIPAddr()
{
if (!empty($_SERVER['HTTP_CLIENT_IP'])) //check ip from share internet
{
$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'];
}
return $ip;
}
Code language: PHP (php)
4. Seconds to String
This function will return the duration of the given time period in days, hours, minutes and seconds. e.g. secsToStr(1234567) would return “14 days, 6 hours, 56 minutes, 7 seconds”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;
}
Code language: PHP (php)
5. Email validation snippet in PHP
$email = $_POST['email'];
if(preg_match("~([a-zA-Z0-9!#$%&'*+-/=?^_`{|}~])@([a-zA-Z0-9-]).([a-zA-Z0-9]{2,4})~",$email)) {
echo 'This is a valid email.';
} else{
echo 'This is an invalid email.';
}
Code language: PHP (php)
6. Parsing XML in easy way using PHP
Required Extension: SimpleXML//this is a sample xml string
$xml_string="<?xml version='1.0'?>
<moleculedb>
<molecule name='Benzine'>
<symbol>ben</symbol>
<code>A</code>
</molecule>
<molecule name='Water'>
<symbol>h2o</symbol>
<code>K</code>
</molecule>
</moleculedb>";
//load the xml string using simplexml function
$xml = simplexml_load_string($xml_string);
//loop through the each node of molecule
foreach ($xml->molecule as $record)
{
//attribute are accessted by
echo $record['name'], ' ';
//node are accessted by -> operator
echo $record->symbol, ' ';
echo $record->code, '<br />';
}
Code language: PHP (php)
7. Database Connection in PHP
<?php
if(basename(__FILE__) == basename($_SERVER['PHP_SELF'])) send_404();
$dbHost = "localhost"; //Location Of Database usually its localhost
$dbUser = "xxxx"; //Database User Name
$dbPass = "xxxx"; //Database Password
$dbDatabase = "xxxx"; //Database Name
$db = mysql_connect("$dbHost", "$dbUser", "$dbPass") or die ("Error connecting to database.");
mysql_select_db("$dbDatabase", $db) or die ("Couldn't select the database.");
# This function will send an imitation 404 page if the user
# types in this files filename into the address bar.
# only files connecting with in the same directory as this
# file will be able to use it as well.
function send_404()
{
header('HTTP/1.x 404 Not Found');
print '<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">'."n".
'<html><head>'."n".
'<title>404 Not Found</title>'."n".
'</head><body>'."n".
'<h1>Not Found</h1>'."n".
'<p>The requested URL '.
str_replace(strstr($_SERVER['REQUEST_URI'], '?'), '', $_SERVER['REQUEST_URI']).
' was not found on this server.</p>'."n".
'</body></html>'."n";
exit;
}
# In any file you want to connect to the database,
# and in this case we will name this file db.php
# just add this line of php code (without the pound sign):
# include"db.php";
?>
Code language: PHP (php)
8. Creating and Parsing JSON data in PHP
Following is the PHP code to create the JSON data format of above example using array of PHP.$json_data = array ('id'=>1,'name'=>"rolf",'country'=>'russia',"office"=>array("google","oracle"));
echo json_encode($json_data);
Code language: PHP (php)
Following code will parse the JSON data into PHP arrays.$json_string='{"id":1,"name":"rolf","country":"russia","office":["google","oracle"]} ';
$obj=json_decode($json_string);
//print the parsed data
echo $obj->name; //displays rolf
echo $obj->office[0]; //displays google
Code language: PHP (php)
9. Process MySQL Timestamp in PHP
$query = "select UNIX_TIMESTAMP(date_field) as mydate from mytable where 1=1";
$records = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($records))
{
echo $row;
}
Code language: PHP (php)
10. Generate An Authentication Code in PHP
This basic snippet will create a random authentication code, or just a random string.<?php
# This particular code will generate a random string
# that is 25 charicters long 25 comes from the number
# that is in the for loop
$string = "abcdefghijklmnopqrstuvwxyz0123456789";
for($i=0;$i<25;$i++){
$pos = rand(0,36);
$str .= $string{$pos};
}
echo $str;
# If you have a database you can save the string in
# there, and send the user an email with the code in
# it they then can click a link or copy the code
# and you can then verify that that is the correct email
# or verify what ever you want to verify
?>
Code language: PHP (php)
11. Date format validation in PHP
Validate a date in “YYYY-MM-DD” format.function checkDateFormat($date)
{
//match the format of the date
if (preg_match ("/^([0-9]{4})-([0-9]{2})-([0-9]{2})$/", $date, $parts))
{
//check weather the date is valid of not
if(checkdate($parts[2],$parts[3],$parts[1]))
return true;
else
return false;
}
else
return false;
}
Code language: PHP (php)
12. HTTP Redirection in PHP
<?php
header('Location: http://you_stuff/url.php'); // stick your url here
?>
Code language: PHP (php)
13. Directory Listing in PHP
<?php
function list_files($dir)
{
if(is_dir($dir))
{
if($handle = opendir($dir))
{
while(($file = readdir($handle)) !== false)
{
if($file != "." && $file != ".." && $file != "Thumbs.db"/*pesky windows, images..*/)
{
echo '<a target="_blank" href="'.$dir.$file.'">'.$file.'</a><br>'."\n";
}
}
closedir($handle);
}
}
}
/*
To use:
<?php
list_files("images/");
?>
*/
?>
Code language: PHP (php)
14. Browser Detection script in PHP
<?php
$useragent = $_SERVER ['HTTP_USER_AGENT'];
echo "<b>Your User Agent is</b>: " . $useragent;
?>
Code language: PHP (php)
15. Unzip a Zip File
<?php
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;
}
}
?>
//Use the code as following:
<?php
include 'functions.php';
if(unzip('zipedfiles/test.zip','unziped/myNewZip'))
echo 'Success!';
else
echo 'Error';
?>
Code language: PHP (php)
How you like this small collection of PHP code snippets. You may want to paste your code snippet in the comment section below and share it with others. :)
I haven’t done PHP for a long time but these are Very nice! should be really useful for people doing PHP thnx :-)
@pourya: thanks for the comment. Please feel free to share some more php code snippets.
nice to your website code of php and learn to easy ……………thanx……for……….
Some of your code snippets could be solved in a much better way:
# 4:
list($d, $h, $m, $s) = explode(\" \",gmdate(\’j H i s\’,12345678));
return ($d-1).\" days $h hour $m minutes $s seconds\"; // -1 @ days because date starts with jan 1st ;-)
# 11:
Use php build in function checkdate()
http://php.net/manual/en/function.checkdate.php
# 15:
Use php build in function ziparchive::extractto()
http://php.net/manual/en/function.ziparchive-extractto.php
i just skimmed this blogpost really quick, but for #13 u should use the SPL DirectoryIterator:
http://de.php.net/directoryiterator
and for the other snippets i recommend to use an already existing library/framework (pear, zf, symfony, …) ;)
@wolfgang: thanks a lot for the updates. I will sure look at the code and try to add more in this list.
@lo: thanks to you too for the tip. i know these snippets and the updates by people who have commented will of great help to php newbies.
The email filter is poor and ignores a PHP standard function:
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
// it’s valid
}
For MySQL Connection in PHP we have one more function mysql_pconnect() which we can use when we don\’t need connect to DB server each time. Having the same reference to connect again. For more details http://in.php.net/function.mysql-pconnect
@kumar: thanks for the useful comment. mysql_pconnect() indeed is a better option to connect to mysql in php.
thanks for the good post! imho is using glob (http://at2.php.net/glob) better for the directory listing.
Tip 11:
foreach(glob(“*”) as $f)
if (is_dir($f))
echo $f;
Is much simpler :).
Tip 13, sorry.
Don\’t want to sound too cynical, but I\’m not really impressed with this list. Some of the snippets do not add anything to the information available in the PHP (or MySQL) manual (#1, #6, #7, #8, #9, #14), for others you do not specify what is interesting about this snippet.
#2: Explain what you\’re doing (encode a string using base64 for the use in an URL) and why base64_encode / _decode doesn\’t cut it.
#3: Creating a function to return an existing variable obscures code and makes your code run slower. Why not just use $_SERVER[\’REMOTE_ADDR\’] directly in your code? (or at least return the value directly without re-assigning it to another variable). The getRealIPAddr() function _is_ useful, but why would you want to use the getRemoteIPAddress() if you have the getRealIPAddr() function?
#4: If you post code snippets to help people write code, make sure they can read and understand your code (personally I think you\’re code should always be readable and understandable but that\’s your choice ;)).
#5: See the other comment about filter_var()
#7: Never ever put database connection details inside your webroot! (imagine you update your server with an error in your PHP config and all PHP files are served as plain text).
#9: Not really a PHP code snippet is it?
#12: Eh what? What\’s up with the $uri variable you don\’t use?
#13: I agree with the other comments to use the SPL directory iterator or scandir or glob. When you use glob use the GLOB_ONLYDIR flag instead of checking if the path is a directory inside the loop. Another thing to be aware of when using glob is that it will return the complete path you specify (e.g. glob(\’./*\’) will return ./file1 and ./file2. glob(\’/path/*\’) will return /path/file1 and /path/file2.
#15: Have a look at PHP\’s zip functions (http://php.net/manual/en/ref.zip.php)
Don\’t get me wrong: I encourage you to post snippets that may be useful to others, just think a minute longer about what you\’ll be posting and make sure the examples solve a problem (i.e. aren\’t copy+paste from the manual) and are clear and understandable.
Overall, I think the snippets were educational, whether they were exemplary or not (in some cases). They served a purpose in making us think of how we would solve the problems better or, in cases where newer programmers hadn’t been faced with the problem, in making us realize that we might have to solve them in a similar way to what was presented here.
My only complaint was #10, which could’ve been solved more simply using the uniqid() function with an md5() of microtime(). Instant random string of a length you choose. :-)
For those that were complaining about the email validation: For those of us that cannot chose the dev environment of our clients, we must often resort to a solution that supports both PHP4 and PHP5. As the filter functions were introduced in 5, this solution actually helps.
The fact still remains, though… that these snippets were somewhat sloppy code. There’s a beauty in serving a purpose, and there’s a beauty in serving a purpose optimally. Hopefully, there will be a part 2 with a rewrite.
I think the list is generally ok. The primary focus was not to show perfect code, but just an entry into the language PHP at all. There will always be a way to optimize the code.
So go on with these intoducing tutorials!
If you want to try one of the scripts/functions above you can test some of them here: http://www.functions-online.com
Don’t just mindlessly copy-paste provided code. Some of provided snippets may create a serious vulnabilities on your site. For example snippet #14 may create XSS ( http://en.wikipedia.org/wiki/Cross-site_scripting ).
Never trust the input you get from user.
Thanks for the list, very useful.
#12 HTTP Redirection in PHP
What is this ??? Doesn’t maen anything
These are really great. I’m just greating into PHP, so every little bit helps. I really like this code. There almost like litte time savers. Thank You.
nice :)
Great snippets!
@Ronald, @Hossein, @Jef… Thanks for the comment.. :)
Thanks man this is a great sample.. this will be very use-full for all developers.
#14: Lose the single quote right before the “http”.
@Mr. Foo: I think you are pointing to Tip #12. I have corrected the typo error. Thanks
hai this is really superb.
regards
babu.p
Hey Viral,
I wanna know is der a function thru which i can get client’s computer name and I.P address,
Computer Name Must…
whenever a client my web site his computer name shud be stored in my db…
Thanx in Advance.
@Hardik: Well I am not aware of such function in PHP. I think there is no HTTP header element which holds such data.
Let me know in case you find a way to achieve this.
OK! i must say these are really good examples of useful handy php snippets. i have collected some snippets, it might be handy for others too. here is the link : http://www.alittlegeek.com/18-php-snippets-to-boost-your-development-speed/. i am thinking of using some of your snippets as a new post in my blog.
In regard to mysql_pconnect() vs mysql_connect(), be careful when taking advice. mysql_pconnect() is viewed by many as unneccessary and, in some cases, even a bad choice for typical database programmers. Persistant connections can be costly in terms of resources. For more info go here… http://efreedom.com/Question/1-247807/Mysql-Connect-VS-Mysql-Pconnect
Hi Viral.
Excellent Post.
How can we create Thumbnail form uploaded image (JPG, GIF, PNG) on a fly?
Please Help.
$h_old) {
$rat=$w_old/$w;
}
else {
$rat=$h_old/$h;
}
$w_new=round($w_old/$rat);
$h_new=round($h_old/$rat);
$new = imageCreateTrueColor($w_new, $h_new);
imageCopyResized($new, $old, 0, 0, 0, 0, $w_new, $h_new, $w_old, $h_old);
imageJpeg($new,””,”100″);
}
}
?>
save the file as resize.php
Use it in a way like this
http://yoursite.com/resize.php?pic=/uploads/image.jpg
Nice post, i work on some php project and i’m using some of this snippets. Works very well. Thank you.
Useful tools indeed. thanks!
Really useful snippets, very helpful. Thank you.
I want code how to send sms after user successfully registered in a website.
Please Help me out of this.
Thanks & Regards,
Moulika.
Hi,Can you guide me how to use IP address snippet.I don’t how to use it.Waiting for help…
Hi,
Guide me how to stream audio, video in the web page using php any code snippet i will wait …..
Helpful snippets,
thnx
keep posting
Very helpful snippets thank’s, and this is a good website where you can find more php snippets on all categories :
http://www.codesphp.com
Some good coding
very useful scripts. I used some of this in my site.
This blog very helpful,
it’s work… thank you so much..
this is support for html and add image for header mail ??
thank..
thanks a lot for these scripts
These helped with a site I am working on. Thanks!
i like Unzip a Zip File
nice article…
Hi !
I have just started with php, I have installed WAMP but dont wht to start with ?
any suggestions for the basic programs to starts with ……
targeting to learn WAMP and PHP!
i want to creat a inbox (messaging system) like facebook for my website in PHP. plz help with advice & php codeā¦.
can you add this login system made by me if you whish
sir,
Guide me how to create exam.php progam and also send php related codes
I want code how to send sms after user successfully registered in a website.
Please Help me and send demo my alternet Id in there
tryed all kinds couldnt get this working why?
IP Page
<?php
// . Get Remote IP Address in PHP
function getRemoteIPAddress() {
$ip = $_SERVER['REMOTE_ADDR'];
return $ip;
}
$a = getRemoteIPAddress();
echo "$a";
echo "”
// The above code will not work in case your client is behind proxy server. In that case use below function to get real IP address of client.
function getRealIPAddr()
{
if (!empty($_SERVER[‘HTTP_CLIENT_IP’])) //check ip from share internet
{
$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’];
}
return $ip;
}
$b = getRealIPAddr();
echo “$b”;
echo “”
?>
kindly send a code for pdf generation in php.
I have personally used and tested some of this. For sure very useful in daily practice.
good one!
Dear Avinash
try this for generate pdf using html & php
http://www.fpdf.org/
i need some help in mssql 2008 database connection in php i have tried some code bt cant connect n cant retive data from d table
how can we stop the form resubmission on click of ctrl+f5 for avoiding the insertion of duplicate record in database table using php and mysql–Thanks in advance
Dear sir I made php application for invoice generation wuth the wamp server. I can generate invoice by adding manually product name and generate invoice but now I want to use barcode scanner for reading product so I need code for barcode scanner and how barcode scanner work .
Hey Siddu,
Just look at my code for stop resubmit form value again and again.
“1”, “message”=>”Invalid Submission”);
}
elseif($_POST[‘form_token’] != $_SESSION[‘form_token’])
{
$notification = array(“error”=>”1”, “message”=>”Access denied”);
}
else
{
//Write Your Code Here
}
}
$form_token = uniqid();
$_SESSION[‘form_token’] = $form_token;
$categoryNameData = allCategoryName($conn)
?>
//ADD THIS INPUT TYPE ANY WHERE INSIDE FORM
<input type="hidden" name="form_token" value="” />
Please like my page on facebook. http://www.facebook.com/whcommerce
Thanks
Waseem Asgar
http://www.whcommerce.com
Useful functions collection, thanks. But getRemoteIPAddress is not really accurate.
Well established articles in PHP, I must agree…Keep sharing!