$to = "viralpatel.net@gmail.com";
$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: info@yoursite.com\r\n";
$headers .= "Return-Path: info@yoursite.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);
?>
Code language: PHP (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)
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)
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)
$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)
//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)
<?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)
$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)
$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)
<?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)
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)
<?php
header('Location: http://you_stuff/url.php'); // stick your url here
?>
Code language: PHP (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)
<?php
$useragent = $_SERVER ['HTTP_USER_AGENT'];
echo "<b>Your User Agent is</b>: " . $useragent;
?>
Code language: PHP (php)
<?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. :) Java URL Encoder/Decoder Example - In this tutorial we will see how to URL encode/decode…
Show Multiple Examples in OpenAPI - OpenAPI (aka Swagger) Specifications has become a defecto standard…
Local WordPress using Docker - Running a local WordPress development environment is crucial for testing…
1. JWT Token Overview JSON Web Token (JWT) is an open standard defines a compact…
GraphQL Subscription provides a great way of building real-time API. In this tutorial we will…
1. Overview Spring Boot Webflux DynamoDB Integration tests - In this tutorial we will see…
View Comments
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 :).