Professional Documents
Culture Documents
46 useful PHP code Snippets that can help you with your PHP
projects
by Mohit Madan - Monday, July 06, 2015
http://blog.koonk.com/2015/07/46-useful-php-code-snippets-that-can-help-you-with-your-php-projects/
Its always good to have a magic hat while writing code. Below I have compiled 40+ PHP code snippets
that can help you with your PHP Projects.
These PHP code snippets can come handy even if you are just beginning to learn PHP. So, let's get
started.
1. Sending sms
While working on web or mobile applications, you often face a situation where you need to send an SMS
to your user either for login purposes or providing them with some information. The below PHP function
would help you with it.
For sending SMS using any language, you'd need an SMS gateway. Most of the SMS providers these
days provide with an API. For the below PHP snippet, I am using MSG91 as SMS gateway.
function send_sms($mobile,$msg)
{
$authKey = "XXXXXXXXXXX";
date_default_timezone_set("Asia/Kolkata");
$date = strftime("%Y-%m-%d %H:%M:%S");
//Multiple mobiles numbers separated by comma
$mobileNumber = $mobile;
//Sender ID,While using route4 sender id should be 6 characters long.
$senderId = "IKOONK";
//Your message to send, Add URL encoding here.
$message = urlencode($msg);
//Define route
$route = "template";
//Prepare you post parameters
$postData = array(
'authkey' => $authKey,
'mobiles' => $mobileNumber,
'message' => $message,
'sender' => $senderId,
1 / 39
46 useful PHP code Snippets that can help you with your PHP projects - 07-06-2015
by Mohit Madan - KOONK Technologies - http://blog.koonk.com
//get response
$output = curl_exec($ch);
//Print error if any
if(curl_errno($ch))
{
echo 'error:' . curl_error($ch);
}
curl_close($ch);
}
You'd see that I have highlighted two lines. On the first highlighted line you need to enter your passkey
and on the second you need to enter your senderID. While entering mobile number you need to specify
the country code (For example, USA's country code is 1. India's country code is 91).
Syntax:
<?php
$message = "Hello World";
$mobile = "918112998787";
2 / 39
46 useful PHP code Snippets that can help you with your PHP projects - 07-06-2015
by Mohit Madan - KOONK Technologies - http://blog.koonk.com
send_sms($mobile,$message);
?>
In the above code you would have to specify your own api key that you get from your Mandrill account.
Syntax
<?php
$to = "abc@example.com";
$subject = "This is a test email";
$message = "Hello World!";
send_email($to,$subject,$message);
?>
3 / 39
46 useful PHP code Snippets that can help you with your PHP projects - 07-06-2015
by Mohit Madan - KOONK Technologies - http://blog.koonk.com
For best deliveries, I would recommend you to configure DNS settings as guided by Mandrill.
4 / 39
46 useful PHP code Snippets that can help you with your PHP projects - 07-06-2015
by Mohit Madan - KOONK Technologies - http://blog.koonk.com
Syntax
<?php
$text = "<script>alert(1)</script>";
$text = clean($text);
echo $text;
?>
Had we not used the clean function above, the page would have popped up an alert box.
5 / 39
46 useful PHP code Snippets that can help you with your PHP projects - 07-06-2015
by Mohit Madan - KOONK Technologies - http://blog.koonk.com
CURLOPT_URL
CURLOPT_TIMEOUT
CURLOPT_REFERER
=> $url,
=> 1,
=> 'http://' . $_SERVER['HTTP_HOST
'],
);
curl_setopt_array($ch, $curl_opt);
$content = curl_exec($ch);
if (!is_null($curl_info)) {
$curl_info = curl_getinfo($ch);
}
curl_close($ch);
if ( preg_match('{<li>City : ([^<]*)</li>}i', $content, $regs)
)
{
$city = $regs[1];
}
if ( preg_match('{<li>State/Province : ([^<]*)</li>}i', $conte
nt, $regs) ) {
$state = $regs[1];
}
if( $city!='' && $state!='' ){
$location = $city . ', ' . $state;
return $location;
}else{
return $default;
}
}
Syntax
<?php
$ip = $_SERVER['REMOTE_ADDR'];
$city = detect_city($ip);
echo $city;
?>
6 / 39
46 useful PHP code Snippets that can help you with your PHP projects - 07-06-2015
by Mohit Madan - KOONK Technologies - http://blog.koonk.com
Syntax
<?php
$url = "http://blog.koonk.com";
$source = display_sourcecode($url);
echo $source;
?>
Syntax
<?php
$page = "koonktechnologies";
$count = fb_fan_count($page);
echo $count;
7 / 39
46 useful PHP code Snippets that can help you with your PHP projects - 07-06-2015
by Mohit Madan - KOONK Technologies - http://blog.koonk.com
?>
8. whois query
Using the below function you would be able to get complete details regarding the owner of any domain.
function whois_query($domain) {
// fix the domain name:
$domain = strtolower(trim($domain));
$domain = preg_replace('/^http:\/\//i', '', $domain);
$domain = preg_replace('/^www\./i', '', $domain);
$domain = explode('/', $domain);
$domain = trim($domain[0]);
// split the TLD from domain name
$_domain = explode('.', $domain);
8 / 39
46 useful PHP code Snippets that can help you with your PHP projects - 07-06-2015
by Mohit Madan - KOONK Technologies - http://blog.koonk.com
$lst = count($_domain)-1;
$ext = $_domain[$lst];
// You find resources and lists
// like these on wikipedia:
//
// http://de.wikipedia.org/wiki/Whois
//
$servers = array(
"biz" => "whois.neulevel.biz",
"com" => "whois.internic.net",
"us" => "whois.nic.us",
"coop" => "whois.nic.coop",
"info" => "whois.nic.info",
"name" => "whois.nic.name",
"net" => "whois.internic.net",
"gov" => "whois.nic.gov",
"edu" => "whois.internic.net",
"mil" => "rs.internic.net",
"int" => "whois.iana.org",
"ac" => "whois.nic.ac",
"ae" => "whois.uaenic.ae",
"at" => "whois.ripe.net",
"au" => "whois.aunic.net",
"be" => "whois.dns.be",
"bg" => "whois.ripe.net",
"br" => "whois.registro.br",
"bz" => "whois.belizenic.bz",
"ca" => "whois.cira.ca",
"cc" => "whois.nic.cc",
"ch" => "whois.nic.ch",
"cl" => "whois.nic.cl",
"cn" => "whois.cnnic.net.cn",
"cz" => "whois.nic.cz",
"de" => "whois.nic.de",
"fr" => "whois.nic.fr",
"hu" => "whois.nic.hu",
"ie" => "whois.domainregistry.ie",
"il" => "whois.isoc.org.il",
"in" => "whois.ncst.ernet.in",
"ir" => "whois.nic.ir",
"mc" => "whois.ripe.net",
"to" => "whois.tonic.to",
"tv" => "whois.tv",
"ru" => "whois.ripn.net",
"org" => "whois.pir.org",
9 / 39
46 useful PHP code Snippets that can help you with your PHP projects - 07-06-2015
by Mohit Madan - KOONK Technologies - http://blog.koonk.com
Syntax
<?php
$domain = "http://www.blog.koonk.com";
$result = whois_query($domain);
print_r($result);
?>
10 / 39
46 useful PHP code Snippets that can help you with your PHP projects - 07-06-2015
by Mohit Madan - KOONK Technologies - http://blog.koonk.com
{
$check = 1;
}
return $check;
}
Syntax
<?php
$email = "blog@koonk.com";
$check = is_validemail($email);
echo $check;
// If the output is 1, then email is valid.
?>
Syntax
<?php
$ip = getRealIpAddr();
echo $ip;
11 / 39
46 useful PHP code Snippets that can help you with your PHP projects - 07-06-2015
by Mohit Madan - KOONK Technologies - http://blog.koonk.com
?>
Syntax
<?php
$text = "This is my first post on http://blog.koonk.com";
$text = makeClickableLinks($text);
echo $text;
?>
12 / 39
46 useful PHP code Snippets that can help you with your PHP projects - 07-06-2015
by Mohit Madan - KOONK Technologies - http://blog.koonk.com
'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 array
if ( (array_search($ip, $deny_ips))!== FALSE ) {
// address is blocked:
echo 'Your IP adress ('.$ip.') was blocked!';
exit;
}
Syntax
13 / 39
46 useful PHP code Snippets that can help you with your PHP projects - 07-06-2015
by Mohit Madan - KOONK Technologies - http://blog.koonk.com
<php
force_download("image.jpg");
?>
14 / 39
46 useful PHP code Snippets that can help you with your PHP projects - 07-06-2015
by Mohit Madan - KOONK Technologies - http://blog.koonk.com
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);
?>
15 / 39
46 useful PHP code Snippets that can help you with your PHP projects - 07-06-2015
by Mohit Madan - KOONK Technologies - http://blog.koonk.com
return FALSE;
}
}
Syntax
<?php
unzip('test.zip','unziped/test'); //File would be unzipped in unziped/
test folder
?>
16 / 39
46 useful PHP code Snippets that can help you with your PHP projects - 07-06-2015
by Mohit Madan - KOONK Technologies - http://blog.koonk.com
Syntax
<?php
$to = "admin@koonk.com";
$subject = "This is a test mail";
$body = "Hello World!";
send_mail($to,$subject,$body);
?>
17 / 39
46 useful PHP code Snippets that can help you with your PHP projects - 07-06-2015
by Mohit Madan - KOONK Technologies - http://blog.koonk.com
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;
?>
In the highlighted lines above, you would have to specify your own server database details.
You can save the above file as config.php and you would have to include that file in all pages where you
need database connectivity.
18 / 39
46 useful PHP code Snippets that can help you with your PHP projects - 07-06-2015
by Mohit Madan - KOONK Technologies - http://blog.koonk.com
Syntax
<?php
list_files("images/"); //This will list all files of images folder
?>
19 / 39
46 useful PHP code Snippets that can help you with your PHP projects - 07-06-2015
by Mohit Madan - KOONK Technologies - http://blog.koonk.com
return $choice;
}
}
}
return $default;
}
Syntax
<?php
$csvFile = "test.csv";
$csv = readCSV($csvFile);
$a = csv[0][0]; // This will get value of Column 1 & Row 1
?>
20 / 39
46 useful PHP code Snippets that can help you with your PHP projects - 07-06-2015
by Mohit Madan - KOONK Technologies - http://blog.koonk.com
Syntax
<?php
$data[0] = "apple";
$data[1] = "oranges";
generateCsv($data, $delimiter = ',', $enclosure = '"');
?>
21 / 39
46 useful PHP code Snippets that can help you with your PHP projects - 07-06-2015
by Mohit Madan - KOONK Technologies - http://blog.koonk.com
le","oracle"]} ';
$obj=json_decode($json_string);
//print the parsed data
echo $obj->name; //displays rolf
echo $obj->office[0]; //displays google
Syntax
<?php
echo "Currently you are on: ".current_url();
?>
22 / 39
46 useful PHP code Snippets that can help you with your PHP projects - 07-06-2015
by Mohit Madan - KOONK Technologies - http://blog.koonk.com
}
}
}
}
Syntax
<?php
$handle = "koonktech";
my_twitter($handle);
?>
Syntax
<?php
$url = "http://blog.koonk.com";
$count = tweetCount($url);
return $count;
?>
23 / 39
46 useful PHP code Snippets that can help you with your PHP projects - 07-06-2015
by Mohit Madan - KOONK Technologies - http://blog.koonk.com
<?php
$date1 = date( 'Y-m-d' );
$date2 = "2015-12-04";
$diff = abs(strtotime($date2) - strtotime($date1));
$years = floor($diff / (365*60*60*24));
$months = floor(($diff - $years * 365*60*60*24) / (30*60*60*24));
$days = floor(($diff - $years * 365*60*60*24 - $months*30*60*60*24)/ (
60*60*24));
printf("%d years, %d months, %d days\n", $years, $months, $days);
-------------------------------------------------------- OR
-------------------------------------------------------- OR
/**
* Calculate differences between two dates with precise semantics. Bas
ed on PHPs DateTime::diff()
* implementation by Derick Rethans. Ported to PHP by Emil H, 2011-0502. No rights reserved.
*
* See here for original code:
* http://svn.php.net/viewvc/php/phpsrc/trunk/ext/date/lib/tm2unixtime.c?revision=302890&view=markup
* http://svn.php.net/viewvc/php/phpsrc/trunk/ext/date/lib/interval.c?revision=298973&view=markup
*/
function _date_range_limit($start, $end, $adj, $a, $b, $result)
{
24 / 39
46 useful PHP code Snippets that can help you with your PHP projects - 07-06-2015
by Mohit Madan - KOONK Technologies - http://blog.koonk.com
25 / 39
46 useful PHP code Snippets that can help you with your PHP projects - 07-06-2015
by Mohit Madan - KOONK Technologies - http://blog.koonk.com
"s",
"i",
"h",
"m",
"i",
"h",
"d",
"y",
$result);
$result);
$result);
$result);
26 / 39
46 useful PHP code Snippets that can help you with your PHP projects - 07-06-2015
by Mohit Madan - KOONK Technologies - http://blog.koonk.com
m d H i s", $two))));
$result = array();
$result["y"] = $b["y"] - $a["y"];
$result["m"] = $b["m"] - $a["m"];
$result["d"] = $b["d"] - $a["d"];
$result["h"] = $b["h"] - $a["h"];
$result["i"] = $b["i"] - $a["i"];
$result["s"] = $b["s"] - $a["s"];
$result["invert"] = $invert ? 1 : 0;
$result["days"] = intval(abs(($one - $two)/86400));
if ($invert) {
_date_normalize(&$a, &$result);
} else {
_date_normalize(&$b, &$result);
}
return $result;
}
$date = "2014-12-04 19:37:22";
echo '<pre>';
print_r( _date_diff( strtotime($date), time() ) );
echo '</pre>';
?>
27 / 39
46 useful PHP code Snippets that can help you with your PHP projects - 07-06-2015
by Mohit Madan - KOONK Technologies - http://blog.koonk.com
Syntax
<?php
$path = "images/";
Delete($path); // This will delete images folder along with its conten
ts.
?>
Syntax
<?php
$string = "I like chocolates and I like apples";
$words = "apple";
echo highlighter_text($string ,$words);
28 / 39
46 useful PHP code Snippets that can help you with your PHP projects - 07-06-2015
by Mohit Madan - KOONK Technologies - http://blog.koonk.com
?>
Syntax
<?php
$url = "http://koonk.com/images/logo.png";
$rename = "koonk.png";
imagefromURL($url,$rename);
29 / 39
46 useful PHP code Snippets that can help you with your PHP projects - 07-06-2015
by Mohit Madan - KOONK Technologies - http://blog.koonk.com
?>
Syntax
<?php
$url = "http://koonk.com";
$check = checkvalidURL($url);
echo $check; //if returns 1 then URL is valid.
?>
30 / 39
46 useful PHP code Snippets that can help you with your PHP projects - 07-06-2015
by Mohit Madan - KOONK Technologies - http://blog.koonk.com
Syntax
<?php
header("Content-type: image/png");
echo qr_code("http://koonk.com", "URL");
?>
Syntax
31 / 39
46 useful PHP code Snippets that can help you with your PHP projects - 07-06-2015
by Mohit Madan - KOONK Technologies - http://blog.koonk.com
<?php
$point1 = array('lat' => 40.770623, 'long' => -73.964367);
$point2 = array('lat' => 40.758224, 'long' => -73.917404);
$distance = getDistanceBetweenPointsNew($point1['lat'], $point1['long'
], $point2['lat'], $point2['long']);
foreach ($distance as $unit => $value) {
echo $unit.': '.number_format($value,4).'<br />';
}
?>
<
return true ;
}
32 / 39
46 useful PHP code Snippets that can help you with your PHP projects - 07-06-2015
by Mohit Madan - KOONK Technologies - http://blog.koonk.com
Syntax
<?php
$number = 10;
echo ordinal($number); //output is 10th
?>
33 / 39
46 useful PHP code Snippets that can help you with your PHP projects - 07-06-2015
by Mohit Madan - KOONK Technologies - http://blog.koonk.com
34 / 39
46 useful PHP code Snippets that can help you with your PHP projects - 07-06-2015
by Mohit Madan - KOONK Technologies - http://blog.koonk.com
Syntax
<?php
$file = "http://koonk.com/images/logo.png";
$size = remote_filesize($url);
echo $size;
?>
35 / 39
46 useful PHP code Snippets that can help you with your PHP projects - 07-06-2015
by Mohit Madan - KOONK Technologies - http://blog.koonk.com
if($return_var == 0) {
//if exec successfuly converted pd
f to jpg
print "Conversion OK";
}
else print "Conversion failed.<br />".$output;
?>
Syntax
<?php
$url = "http://blog.koonk.com/2015/07/Hello-World";
$tinyurl = get_tiny_url($url);
echo $tinyurl;
?>
36 / 39
46 useful PHP code Snippets that can help you with your PHP projects - 07-06-2015
by Mohit Madan - KOONK Technologies - http://blog.koonk.com
function get_youtube_download_link(){
$youtube_link = $_GET['youtube'];
$youtube_page = file_get_contents($youtube_link);
$v_id = str_between($youtube_page, "&video_id=", "&");
$t_id = str_between($youtube_page, "&t=", "&");
$flv_link = "http://www.youtube.com/get_video?video_id=$v_id&t=$t_id"
;
$hq_flv_link = "http://www.youtube.com/get_video?video_id=$v_id&t=$t_
id&fmt=6";
$mp4_link = "http://www.youtube.com/get_video?video_id=$v_id&t=$t_id&
fmt=18";
$threegp_link = "http://www.youtube.com/get_video?video_id=$v_id&t=$t
_id&fmt=17";
echo "\t\tDownload (right-click > save as):\n\t\t";
echo "<a href=\"$flv_link\">FLV</a>\n\t\t";
echo "<a href=\"$hq_flv_link\">HQ FLV (if available)</a>\n\t\t";
echo "<a href=\"$mp4_link\">MP4</a>\n\t\t";
echo "<a href=\"$threegp_link\">3GP</a><br><br>\n";
}
= time();
= strtotime($date);
37 / 39
46 useful PHP code Snippets that can help you with your PHP projects - 07-06-2015
by Mohit Madan - KOONK Technologies - http://blog.koonk.com
= $unix_date - $now;
= "from now";
Syntax
<?php
$date = "2015-07-05 03:45";
$result = nicetime($date); // 2 days ago
?>
This completes my first blog post. Most of the PHP snippets that I have mentioned above are not mine. I
have gathered them over years hence I am unable to add proper credits.
These snippets can help you save a lot of time while you get down to code something amazing.
This is my first blog post here. Took me a few hours to compile. Hope you guys would like it.
Do comment below and let me know if you liked(or disliked) my first post. Comments and suggestions
are welcome. Let me know how you feel about this post by tweeting to @TheMohitMadan
38 / 39
46 useful PHP code Snippets that can help you with your PHP projects - 07-06-2015
by Mohit Madan - KOONK Technologies - http://blog.koonk.com
Signing off.
Mohit Madan
_______________________________________________
PDF generated by Kalin's PDF Creation Station
39 / 39
Powered by TCPDF (www.tcpdf.org)