PHP Snippets
<?php
/**
* CALCULATE DISTANCE BETWEEN TWO MAP COORDINATES
*
*/
function getDistanceBetweenPointsNew($latitude1, $longitude1, $latitude2, $longitude2) {
$theta = $longitude1 - $longitude2;
$miles = (sin(deg2rad($latitude1)) * sin(deg2rad($latitude2))) + (cos(deg2rad($latitude1)) * cos(deg2rad($latitude2)) * cos(deg2rad($theta)));
$miles = acos($miles);
$miles = rad2deg($miles);
$miles = $miles * 60 * 1.1515;
$feet = $miles * 5280;
$yards = $feet / 3;
$kilometers = $miles * 1.609344;
$meters = $kilometers * 1000;
return compact('miles','feet','yards','kilometers','meters');
}
/* use */
$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 />';
}
<?php
/**
* limit number of chars
*
*/
$char_limit = 50;
$ivm_content = "SOME CONTENT TO LIMIT HERE";
$ivm_content = (strlen($ivm_content) > $char_limit) ? substr($ivm_content,0,$char_limit).'...' : $ivm_content;
/**
* SEARCH AND HIGHLIGHT KEYWORDS IN A STRING
*
*/
function highlighter_text($text, $words) {
$split_words = explode( " " , $words );
foreach($split_words as $word)
{
$color = "#4285F4";
$text = preg_replace("|($word)|Ui" ,
"<span style=\"color:".$color.";\"><b>$1</b></span>" , $text );
}
return $text;
}
/* use */
$string = "I like chocolates and I like apples";
$words = "apple";
echo highlighter_text($string ,$words);
<?php
/**
* GET CURRENT PAGE URL
*
*/
function current_url() {
$url = "http://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
$validURL = str_replace("&", "&", $url);
return validURL;
}
/* use */
echo "Currently you are on: ".current_url();
/**
* sum values in a loop
*
*/
$sum = '';
foreach($item as $item) {
echo $item->title;
$sum += $item->price // sum items prices
}
echo "Total Price: $sum";
/**
* Even / Odd loop
*
*/
for ($i = 0; $i < 10; $i++){
if ($i % 2 == 0) {
echo "even";
}else {
echo "odd";
}
}
/**
* IF START/END WITH
*
*/
// if first char is "#"
if (substr($string, 0, 1) === '#') {
// code here
}
// if 7 first chars are "http://"
if (substr($string, 0, 7) === "http://") {
// code here
}
// if last char is "#"
if (substr($string, -1) === '#') {
// code here
}
/**
* HTTP redirect
*
*/
header('Location: http://you_stuff/url.php'); // stick your url here
<?php
/**
* Parse JSON Data
*
*/
$json_string='{"id":1,"name":"foo","email":"foo@foobar.com","interest":["wordpress","php"]} ';
$obj=json_decode($json_string);
echo $obj->name; //prints foo
echo $obj->interest[1]; //prints php
/**
* Detect AJAX Reques
*
*/
if(!emptyempty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest'){
//If AJAX Request Then
}else{
//something else
}
<?php
/**
* Force file download
* @file - path to file
*
*/
function force_download($file) {
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";
}
}
/**
* DELETE DIR
* @dir - Directory to destroy
* @virtual[optional]- whether a virtual directory
*
*/
function deleteDir($dir, $virtual = false) {
$ds = DIRECTORY_SEPARATOR;
$dir = $virtual ? realpath($dir) : $dir;
$dir = substr($dir, -1) == $ds ? substr($dir, 0, -1) : $dir;
if (is_dir($dir) && $handle = opendir($dir)) {
while ($file = readdir($handle)) {
if ($file == '.' || $file == '..') {
continue;
} elseif (is_dir($dir.$ds.$file)) {
destroyDir($dir.$ds.$file);
} else {
unlink($dir.$ds.$file);
}
}
closedir($handle);
rmdir($dir);
return true;
} else {
return false;
}
}
/**
* READING A CSV FILE
* @csvFile - csv file to read
*
*/
function readCSV($csvFile){
$file_handle = fopen($csvFile, 'r');
while (!feof($file_handle) ) {
$line_of_text[] = fgetcsv($file_handle, 1024);
}
fclose($file_handle);
return $line_of_text;
}
/* use */
$csvFile = "test.csv";
$csv = readCSV($csvFile);
$a = csv[0][0]; // This will get value of Column 1 & Row 1
/**
* CREATING A CSV FILE FROM PHP ARRAY
*
*/
function generateCsv($data, $delimiter = ',', $enclosure = '"') {
$handle = fopen('php://temp', 'r+');
foreach ($data as $line) {
fputcsv($handle, $line, $delimiter, $enclosure);
}
rewind($handle);
while (!feof($handle)) {
$contents .= fread($handle, 8192);
}
fclose($handle);
return $contents;
}
/* use */
$data[0] = "apple";
$data[1] = "oranges";
generateCsv($data, $delimiter = ',', $enclosure = '"');
<?php
/**
* DETECT LOCATION OF THE USER
*
* @ip - ip address of the user
*
*/
function detectCity($ip) {
$default = 'UNKNOWN';
$curlopt_useragent = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.2) Gecko/20100115 Firefox/3.6 (.NET CLR 3.5.30729)';
$url = 'http://ipinfodb.com/ip_locator.php?ip=' . urlencode($ip);
$ch = curl_init();
$curl_opt = array(
CURLOPT_FOLLOWLOCATION => 1,
CURLOPT_HEADER => 0,
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_USERAGENT => $curlopt_useragent,
CURLOPT_URL => $url,
CURLOPT_TIMEOUT => 1,
CURLOPT_REFERER => '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', $content, $regs) ) {
$state = $regs[1];
}
if( $city!='' && $state!='' ){
$location = $city . ', ' . $state;
return $location;
}else{
return $default;
}
}
/* usage */
$ip = $_SERVER['REMOTE_ADDR'];
$city = detectCity($ip);
echo $city;
/**
* GET REAL IP
* This function will fetch the real IP address of the user even if he is behind a proxy server.
*
*/
function getRealIpAddr(){
if (!emptyempty($_SERVER['HTTP_CLIENT_IP'])) {
$ip=$_SERVER['HTTP_CLIENT_IP'];
}
elseif (!emptyempty($_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;
}
/**
* Detect browser language
* @availableLanguages - languages that are available on your website
*
*/
function get_client_language($availableLanguages, $default='en'){
if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
$langs=explode(',',$_SERVER['HTTP_ACCEPT_LANGUAGE']);
foreach ($langs as $value){
$choice=substr($value,0,2);
if(in_array($choice, $availableLanguages)){
return $choice;
}
}
}
return $default;
}
<?php
// date
$date = '423523463463'; // time stamp
$date = date("F j, Y, g:i a", $date);
// satring to date
$str = strtotime('10/16/2016');
$date = date('M d Y',$str);
echo $date;
// Count date diference
$now = time(); // or your date as well
$datediff = ($now) - ($item->created);
$days = floor($datediff / (60 * 60 * 24));
echo $days;
/**
* Time Ago Function
*/
function time_ago($datetime, $full = false) {
$now = new DateTime;
$ago = new DateTime($datetime);
$diff = $now->diff($ago);
$diff->w = floor($diff->d / 7);
$diff->d -= $diff->w * 7;
$string = array(
'y' => 'year',
'm' => 'month',
'w' => 'week',
'd' => 'day',
'h' => 'hour',
'i' => 'minute',
's' => 'second',
);
foreach ($string as $k => &$v) {
if ($diff->$k) {
$v = $diff->$k . ' ' . $v . ($diff->$k > 1 ? 's' : '');
} else {
unset($string[$k]);
}
}
if (!$full) $string = array_slice($string, 0, 1);
return $string ? implode(', ', $string) . ' ago' : 'just now';
}
echo time_ago($some_date);
/**
* CONVERT SECONDS TO DAYS, HOURS AND MINUTES
*
*/
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;
}
/* usage */
$seconds = "56789";
$output = secsToStr($seconds);
echo $output;
<?php
/**
* VAlidate Email
* E-mail validation is perhaps the most used validation in web forms,
* this code will validate email address and also optionally check the MX records of the domain provided
* in email address to make email validation more robust.
*
*/
function is_valid_email($email, $test_mx = false) {
if(eregi("^([_a-z0-9-]+)(\.[_a-z0-9-]+)*@([a-z0-9-]+)(\.[a-z0-9-]+)*(\.[a-z]{2,4})$", $email))
if($test_mx) {
list($username, $domain) = split("@", $email);
return getmxrr($domain, $mxrecords);
} else
return true;
else
return false;
}
/**
* Send Mail using mail function in PHP
*
*/
$to = "example@gmail.com";
$subject = "Test Eamil";
$body = "Body of your message here you can use HTML too. e.g. <br> <b> Bold </b>";
$headers = "From: Ivan\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);
<?php
/**
* @l - length of random string
*/
function generate_rand($l){
$c= "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
srand((double)microtime()*1000000);
for($i=0; $i<$l; $i++) {
$rand.= $c[rand()%strlen($c)];
}
return $rand;
}
<?php
/**
* Youtube link embed conversion
*
* https://img.youtube.com/vi/<insert-youtube-video-id-here>/0.jpg
* https://img.youtube.com/vi/<insert-youtube-video-id-here>/1.jpg
* https://img.youtube.com/vi/<insert-youtube-video-id-here>/2.jpg
* https://img.youtube.com/vi/<insert-youtube-video-id-here>/3.jpg
*
* https://img.youtube.com/vi/<insert-youtube-video-id-here>/default.jpg
* https://img.youtube.com/vi/<insert-youtube-video-id-here>/hqdefault.jpg
* https://img.youtube.com/vi/<insert-youtube-video-id-here>/mqdefault.jpg
* https://img.youtube.com/vi/<insert-youtube-video-id-here>/sddefault.jpg
* https://img.youtube.com/vi/<insert-youtube-video-id-here>/maxresdefault.jpg
*
*/
$video = preg_replace("/\s*[a-zA-Z\/\/:\.]*youtube.com\/watch\?v=([a-zA-Z0-9\-_]+)([a-zA-Z0-9\/\*\-\_\?\&\;\%\=\.]*)/i","//www.youtube.com/embed/$1", $youtube_link);
$thumb = preg_replace("/\s*[a-zA-Z\/\/:\.]*youtube.com\/watch\?v=([a-zA-Z0-9\-_]+)([a-zA-Z0-9\/\*\-\_\?\&\;\%\=\.]*)/i","//img.youtube.com/vi/$1/maxresdefault.jpg", $youtube_link);
// no controls
$youtube_embed = preg_replace("/\s*[a-zA-Z\/\/:\.]*youtube.com\/watch\?v=([a-zA-Z0-9\-_]+)([a-zA-Z0-9\/\*\-\_\?\&\;\%\=\.]*)/i","//www.youtube.com/embed/$1?rel=0&controls=0&showinfo=0", $youtube_link);
?>
<iframe width="100%" height="400" src="<?=$video?>" frameborder="0" allowfullscreen></iframe>
<img src="<?=$thumb?>" alt="" />
<?php
// if cookie not set set it and run code
if ($_COOKIE['iwashere'] != "yes") {
setcookie("iwashere", "yes", time()+2628000); // <-- 1 month in seconds
// code to run
}
// if cookie not set set it and run code
if ($_COOKIE['iwashere'] != "yes") {
setcookie("iwashere", "yes", strtotime( '+1 week' )); // <-- 1 week in seconds
// do something
}
<?php
/**
* Backlink Check
*
*/
// BACKLINK CHECK
$web_location = "https://www.gopogle.rs";
$phrase_to_check = "https://mail.google.com";
// Test if link/phraze exist on page
$ch = curl_init("$web_location");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$web_test_location = curl_exec($ch);
$backlink_test = strpos($web_test_location, "$phrase_to_check");
if($backlink_test == true) {
$notification = "Yes";
}else {
$notification = "No";
}