Created
October 29, 2013 02:43
-
-
Save INDIAN2020/7208402 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/*valid email checking*/ | |
<?php | |
if(isset($_POST['email'])){ | |
$email = $_POST['email']; | |
if(filter_var($email, FILTER_VALIDATE_EMAIL)){ | |
echo '<p>This is a valid email.<p>'; | |
}else{ | |
echo '<p>This is an invalid email.</p>'; | |
} | |
} | |
?> | |
<form action="" method="post"> | |
Email: <input type="text" name="email" value=" <?php echo $_POST['email']; ?> "> | |
<input type="submit" value="Check Email"> | |
</form> | |
/*hex to rgb :: rgb to hex*/ | |
<?php | |
function toHex($N) { | |
if ($N==NULL) return "00"; | |
if ($N==0) return "00"; | |
$N=max(0,$N); | |
$N=min($N,255); | |
$N=round($N); | |
$string = "0123456789ABCDEF"; | |
$val = (($N-$N%16)/16); | |
$s1 = $string{$val}; | |
$val = ($N%16); | |
$s2 = $string{$val}; | |
return $s1.$s2; | |
} | |
function rgb2hex($r,$g,$b){ | |
return toHex($r).toHex($g).toHex($b); | |
} | |
function hex2rgb($N){ | |
$dou = str_split($N,2); | |
return array( | |
"R" => hexdec($dou[0]), | |
"G" => hexdec($dou[1]), | |
"B" => hexdec($dou[2]) | |
); | |
} | |
echo rgb2hex(106,48,48); | |
echo '<p> </p>'; | |
print_r(hex2rgb("6A3030")); | |
?> | |
/*css minifier*/ | |
<?php | |
/* | |
DS STYLE MINIFIER & COMPILER: | |
It gathers all css files from requested directories and then minify the code. | |
USAGE: set the constants below and then make links in the html like this | |
<link href="http://mydomain.org/min/css.php?t=default&g=vendor" rel="stylesheet" type="text/css"> | |
*/ | |
// Output mode - min | dev. min = minify the output, dev = no minify. | |
define('MODE','min'); | |
// Base url to the css files. Relatively to the minifier. | |
define('STYLES_BASEDIR','../style/'); | |
// Content type header. Feel free to extend. | |
header ('Content-type: text/css; charset=UTF-8'); | |
function minify($source){ // Minify function the gathered sourcecodes | |
$source = trim($source); | |
$source = str_replace("\r\n", "\n", $source); | |
$search = array("/\/\*[^!][\d\D]*?\*\/|\t+/","/\s+/", "/\}\s+/"); | |
$replace = array(null," ", "}\n"); | |
$source = preg_replace($search, $replace, $source); | |
$search = array("/;[\s+]/","/[\s+];/","/\s+\{\\s+/", "/\\:\s+\\#/", "/,\s+/i", "/\\:\s+\\\'/i","/\\:\s+([0-9]+|[A-F]+)/i","/\{\\s+/","/;}/"); | |
$replace = array(";",";","{", ":#", ",", ":\'", ":$1","{","}"); | |
$source = preg_replace($search, $replace, $source); | |
$source = str_replace("\n", null, $source); | |
return $source; | |
} | |
if(isset($_GET['g'])&&isset($_GET['t'])){ | |
$group = $_GET['g']; | |
$theme = $_GET['t']; | |
$source_data =''; | |
$files = glob(STYLES_BASEDIR.$theme.'/'.$group.'/*.css'); // Get each .css files in the requested directory | |
$files_count = count($files); // Count them | |
for($i=0; $i<$files_count;$i++){ | |
$source_data .= file_get_contents($files[$i]); // Read each file's content and append to the source data | |
} | |
switch (MODE){ // Depending on what mode we using this, minify or just print the source data. | |
case'dev': | |
echo $source_data; | |
break; | |
case'min': | |
echo minify($source_data); | |
break; | |
} | |
} | |
/*dropdown menu from array*/ | |
<?php | |
//Array contents array 1 :: value | |
$myArray1 = array('Cat','Mat','Fat','Hat'); | |
//Array contents array 2 :: key => value | |
$myArray2 = array('c'=>'Cat','m'=>'Mat','f'=>'Fat','h'=>'Hat'); | |
//Values from array 1 | |
echo'<select name="Words">'; | |
//for each value of the array assign a variable name word | |
foreach($myArray1 as $word){ | |
echo'<option value="'.$word.'">'.$word.'</option>'; | |
} | |
echo'</select>'; | |
//Values from array 2 | |
echo'<select name="Words">'; | |
//for each key of the array assign a variable name let | |
//for each value of the array assign a variable name word | |
foreach($myArray2 as $let=>$word){ | |
echo'<option value="'.$let.'">'.$word.'</option>'; | |
} | |
echo'</select>'; | |
?> | |
/*alexa/google page rank */ | |
<?php | |
function page_rank($page, $type = 'alexa'){ | |
switch($type){ | |
case 'alexa': | |
$url = 'http://alexa.com/siteinfo/'; | |
$handle = fopen($url.$page, 'r'); | |
break; | |
case 'google': | |
$url = 'http://google.com/search?client=navclient-auto&ch=6-1484155081&features=Rank&q=info:'; | |
$handle = fopen($url.'http://'.$page, 'r'); | |
break; | |
} | |
$content = stream_get_contents($handle); | |
fclose($handle); | |
$content = preg_replace("~(\n|\t|\s\s+)~",'', $content); | |
switch($type){ | |
case 'alexa': | |
if(preg_match('~\<div class=\"data (down|up)\"\>\<img.+?\>(.+?)\<\/div\>~im',$content,$matches)){ | |
return $matches[2]; | |
}else{ | |
return FALSE; | |
} | |
break; | |
case 'google': | |
$rank = explode(':',$content); | |
if($rank[2] != '') | |
return $rank[2]; | |
else | |
return FALSE; | |
break; | |
default: | |
return FALSE; | |
break; | |
} | |
} | |
// Alexa Page Rank: | |
echo 'Alexa Rank: '.page_rank('phpsnips.com'); | |
echo '<br>'; | |
// Google Page Rank | |
echo 'Google Rank: '.page_rank('phpsnips.com', 'google'); | |
?> | |
/*get a unique random list of array items*/ | |
<?php | |
/* | |
* $array = the array to be filtered | |
* $total = the maximum number of items to return | |
* $unique = whether or not to remove duplicates before getting a random list | |
*/ | |
function unique_array($array, $total, $unique = true){ | |
$newArray = array(); | |
if((bool)$unique){ | |
$array = array_unique($array); | |
} | |
shuffle($array); | |
$length = count($array); | |
for($i = 0; $i < $total; $i++){ | |
if($i < $length){ | |
$newArray[] = $array[$i]; | |
} | |
} | |
return $newArray; | |
} | |
$phrases = array('Hello Sailor','Acid Test','Bear Garden','Botch A Job','Dark Horse', | |
'In The Red','Man Up','Pan Out','Quid Pro Quo','Rub It In','Turncoat', | |
'Yes Man','All Wet','Bag Lady','Bean Feast','Big Wig', 'Big Wig','Bear Garden' | |
,'All Wet','Quid Pro Quo','Rub It In'); | |
print_r(unique_array($phrases, 1)); // Returns 1 result | |
print_r(unique_array($phrases, 5)); // Returns 5 unique results | |
print_r(unique_array($phrases, 5, false)); // Returns 5 results, but may have duplicates if | |
// there are duplicates in original array | |
print_r(unique_array($phrases, 100)); // Returns 100 unique results | |
print_r(unique_array($phrases, 100, false)); // Returns 100 results, but may have duplicates if | |
// there are duplicates in original array | |
/*twitter feed reader */ | |
<?php | |
class Twitter{ | |
protected $twitURL = 'http://api.twitter.com/1/'; | |
protected $xml; | |
protected $tweets = array(), $twitterArr = array(); | |
protected $pversion = "1.0.0"; | |
public function pversion(){ | |
return $this->pversion; | |
} | |
public function loadTimeline($user, $max = 20){ | |
$this->twitURL .= 'statuses/user_timeline.xml?screen_name='.$user.'&count='.$max; | |
$ch = curl_init(); | |
curl_setopt($ch, CURLOPT_URL, $this->twitURL); | |
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); | |
$this->xml = curl_exec($ch); | |
return $this; | |
} | |
public function getTweets(){ | |
$this->twitterArr = $this->getTimelineArray(); | |
$tweets = array(); | |
foreach($this->twitterArr->status as $status){ | |
$tweets[$status->created_at->__toString()] = $status->text->__toString(); | |
} | |
return $tweets; | |
} | |
public function getTimelineArray(){ | |
return simplexml_load_string($this->xml); | |
} | |
public function formatTweet($tweet){ | |
$tweet = preg_replace("/(http(.+?))( |$)/","<a href=\"$0\">$1</a>$3", $tweet); | |
$tweet = preg_replace("/#(.+?)(\h|\W|$)/", "<a href=\"https://twitter.com/i/#!/search/?q=%23$1&src=hash\">#$1</a>$2", $tweet); | |
$tweet = preg_replace("/@(.+?)(\h|\W|$)/", "<a href=\"http://twitter.com/#!/$1\">@$1</a>$2", $tweet); | |
return $tweet; | |
} | |
} | |
/*url shortening for long urls*/ | |
This snippet requires a 3rd party service to work. | |
It will take your url, such as: http://phpsnips.com | |
and convert it to a shorter URL such as: | |
http://m8.to/BA | |
<?php | |
$long_url = "http://www.google.com/?q=oh+hai"; | |
$short_url = implode('',file("http://to.m8.to/api/shortenLink?url=$long_url")); | |
?> | |
/*ip blacklist check script*/ | |
<html> | |
<head> | |
<title>DNSBL Lookup Tool - IP Blacklist Check Script</title> | |
</head> | |
<body> | |
<form action="" method="get"> | |
<input type="text" value="" name="ip" /> | |
<input type="submit" value="LOOKUP" /> | |
</form> | |
<?php | |
/*************************************************************************************** | |
This is a simple PHP script to lookup for blacklisted IP against multiple DNSBLs at once. | |
You are free to use the script, modify it, and/or redistribute the files as you wish. | |
Homepage: http://dnsbllookup.com | |
****************************************************************************************/ | |
function dnsbllookup($ip){ | |
$dnsbl_lookup=array("dnsbl-1.uceprotect.net","dnsbl-2.uceprotect.net","dnsbl-3.uceprotect.net","dnsbl.dronebl.org","dnsbl.sorbs.net","zen.spamhaus.org"); // Add your preferred list of DNSBL's | |
if($ip){ | |
$reverse_ip = implode(".", array_reverse(explode(".", $ip))); | |
foreach($dnsbl_lookup as $host){ | |
if(checkdnsrr($reverse_ip.".".$host.".", "A")){ | |
$listed .= $reverse_ip.'.'.$host.' <font color="red">Listed</font><br />'; | |
} | |
} | |
} | |
if($listed){ | |
return $listed; | |
}else{ | |
return '"A" record was not found'; | |
} | |
} | |
$ip=$_GET['ip']; | |
if(isset($_GET['ip']) && $_GET['ip']!=null){ | |
if(filter_var($ip,FILTER_VALIDATE_IP)){ | |
echo dnsbllookup($ip); | |
}else{ | |
echo "Please enter a valid IP"; | |
} | |
} | |
?> | |
</body> | |
</html> | |
/*tag builder*/ | |
This simple function can build XHTML tags for you really quickly | |
<?php | |
function buildTag($tag, $att = array(), $selfColse = FALSE, $inner = ''){ | |
$t = '<'.$tag.' '; | |
foreach($att as $k => $v){ | |
$t .= $k.'="'.$v.'"'; | |
} | |
if(!$selfColse) | |
$t .= '>'; | |
else | |
$t .= ' />'; | |
if(!$selfColse) | |
$t .= $inner.'</'.$tag.'>'; | |
return $t; | |
} | |
// Example 1: | |
echo buildTag('input', array('type'=>'button', 'value'=>'WOOT!'), TRUE); | |
// Example 2: | |
echo buildTag('div', array('style'=>'border:solid 1px #000'), FALSE, buildTag('a', array('href'=>'http://google.com'), FALSE, 'Google')); | |
?> | |
/*download files from website*/ | |
<?php | |
set_time_limit(0); | |
// Supports all file types | |
// URL Here: | |
$url = 'http://somsite.com/some_video.flv'; | |
$pi = pathinfo($url); | |
$ext = $pi['extension']; | |
$name = $pi['filename']; | |
// create a new cURL resource | |
$ch = curl_init(); | |
// set URL and other appropriate options | |
curl_setopt($ch, CURLOPT_URL, $url); | |
curl_setopt($ch, CURLOPT_HEADER, false); | |
curl_setopt($ch, CURLOPT_BINARYTRANSFER, true); | |
curl_setopt($ch, CURLOPT_AUTOREFERER, true); | |
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); | |
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); | |
// grab URL and pass it to the browser | |
$opt = curl_exec($ch); | |
// close cURL resource, and free up system resources | |
curl_close($ch); | |
$saveFile = $name.'.'.$ext; | |
if(preg_match("/[^0-9a-z\.\_\-]/i", $saveFile)) | |
$saveFile = md5(microtime(true)).'.'.$ext; | |
$handle = fopen($saveFile, 'wb'); | |
fwrite($handle, $opt); | |
fclose($handle); | |
?> | |
/*number to $*/ | |
<?php | |
function toCurrency($var){ | |
return "$".number_format($var,2); | |
} | |
/*cache php generated images*/ | |
<?php | |
header("Cache-Control: private, max-age=10800, pre-check=10800"); | |
header("Pragma: private"); | |
// Set to expire in 2 days | |
header("Expires: " . date(DATE_RFC822,strtotime(" 2 day"))); | |
if(isset($_SERVER['HTTP_IF_MODIFIED_SINCE'])){ | |
// if the browser has a cached version of this image, send 304 | |
header('Last-Modified: '.$_SERVER['HTTP_IF_MODIFIED_SINCE'],true,304); | |
exit; | |
} | |
// Generate an image below either using GD or a file reader such as: | |
// readfile(), fread(), file_get_contents(), etc. | |
$path = "/path/to/my/image.jpg"; | |
$info = pathinfo($path); | |
switch($info["extension"]){ | |
case "jpg": | |
$mime = "image/jpeg"; | |
break; | |
case "gif": | |
$mime = "image/gif"; | |
break; | |
case "png": | |
$mime = "image/png"; | |
break; | |
} | |
header("content-type: $mime"); | |
readfile($path); | |
?> | |
/*advanced image captcha*/ | |
image.php | |
<?php | |
// Font directory + font name | |
$font = 'fonts/Disney.ttf'; | |
// Total number of lines | |
$lineCount = 40; | |
// Size of the font | |
$fontSize = 40; | |
// Height of the image | |
$height = 50; | |
// Width of the image | |
$width = 150; | |
$img_handle = imagecreate ($width, $height) or die ("Cannot Create image"); | |
// Set the Background Color RGB | |
$backColor = imagecolorallocate($img_handle, 255, 255, 255); | |
// Set the Line Color RGB | |
$lineColor = imagecolorallocate($img_handle, 175, 238, 238); | |
// Set the Text Color RGB | |
$txtColor = imagecolorallocate($img_handle, 135, 206, 235); | |
// Do not edit below this point | |
$string = "abcdefghijklmnopqrstuvwxyz0123456789"; | |
$str = ""; | |
for($i=0;$i<6;$i++){ | |
$pos = rand(0,36); | |
$str .= $string{$pos}; | |
} | |
$textbox = imagettfbbox($fontSize, 0, $font, $str) or die('Error in imagettfbbox function'); | |
$x = ($width - $textbox[4])/2; | |
$y = ($height - $textbox[5])/2; | |
imagettftext($img_handle, $fontSize, 0, $x, $y, $txtColor, $font , $str) or die('Error in imagettftext function'); | |
for($i=0;$i<$lineCount;$i++){ | |
$x1 = rand(0,$width);$x2 = rand(0,$width); | |
$y1 = rand(0,$width);$y2 = rand(0,$width); | |
imageline($img_handle,$x1,$y1,$x2,$y2,$lineColor); | |
} | |
header('Content-Type: image/jpeg'); | |
imagejpeg($img_handle,NULL,100); | |
imagedestroy($img_handle); | |
session_start(); | |
$_SESSION['img_number'] = $str; | |
?> | |
form.php | |
<form action="result.php" method="post"> | |
<img alt="Random Number" src="image.php"> | |
<input type="text" name="num"><br> | |
<input type="submit" name="submit" value="Check"> | |
</form> | |
result.php | |
<?php | |
session_start(); | |
if($_SESSION['img_number'] != $_POST['num']){ | |
echo'The number you entered doesn\'t 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>'; | |
} | |
?> | |
/*water marking image*/ | |
Take an image, and put a water mark on top of it. | |
<?php | |
function watermark($file, $watermark, $pos = null, $x = 0, $y = 0){ | |
$details = getimagesize($file); | |
$wDetails = getimagesize($watermark); | |
if(!is_null($pos)){ | |
switch($pos){ | |
case TOP_LEFT: | |
$x = 0; | |
$y = 0; | |
break; | |
case TOP_RIGHT: | |
$x = $details[0] - $wDetails[0]; | |
$y = 0; | |
break; | |
case BOTTOM_LEFT: | |
$x = 0; | |
$y = $details[1] - $wDetails[1]; | |
break; | |
case BOTTOM_RIGHT: | |
$x = $details[0] - $wDetails[0]; | |
$y = $details[1] - $wDetails[1]; | |
break; | |
case CENTER: | |
$x = round(($details[0] - $wDetails[0])/2); | |
$y = round(($details[1] - $wDetails[1])/2); | |
break; | |
} | |
} | |
switch($details['mime']){ | |
case 'image/jpeg':$im = imagecreatefromjpeg($file);break; | |
case 'image/gif':$im = imagecreatefromgif($file);break; | |
case 'image/png':$im = imagecreatefrompng($file);break; | |
} | |
switch($wDetails['mime']){ | |
case 'image/jpeg':$newWater = imagecreatefromjpeg($watermark);break; | |
case 'image/gif':$newWater = imagecreatefromgif($watermark);$colorTransparent = imagecolortransparent($newWater);imagefill($newWater, 0, 0, $colorTransparent);imagecolortransparent($newWater, $colorTransparent);break; | |
case 'image/png':$newWater = imagecreatefrompng($watermark);imagealphablending($newWater, false);imagesavealpha($newWater,true);break; | |
} | |
imagecopyresampled($im, $newWater, $x, $y, 0, 0, $wDetails[0], $wDetails[1], $wDetails[0], $wDetails[1]); | |
// Output the image | |
switch($details['mime']){ | |
case 'image/jpeg':header('Content-type: image/jpeg');imagejpeg($im);break; | |
case 'image/gif':header('Content-type: image/gif');imagegif($im);break; | |
case 'image/png':header('Content-type: image/png');imagepng($im);break; | |
} | |
// Free up memory | |
imagedestroy($im); | |
} | |
// Watermark using only the defaults | |
watermark('girl.jpg','watermark.png'); | |
// Watermark using a pre-defined position | |
// Valid values: TOP_LEFT, TOP_RIGHT, BOTTOM_LEFT, BOTTOM_RIGHT, CENTER | |
watermark('girl.jpg','watermark.png', BOTTOM_RIGHT); | |
// Watermark using an exact position | |
watermark('girl.jpg','watermark.png', null, 150, 150); | |
// Note that you can only use this function once per page. | |
// If it is used more than one time, the image that will be displayed | |
// will be the first function called. | |
?> | |
/*get image from url and display it*/ | |
<?php | |
//$url = "http://share.meebo.com/content/katy_perry/wallpapers/3.jpg"; | |
$url = $_GET['url']; | |
$url = str_replace("http:/","http://",$url); | |
$allowed = array('jpg','gif','png'); | |
$pos = strrpos($_GET['url'], "."); | |
$str = substr($_GET['url'],($pos + 1)); | |
$ch = curl_init(); | |
$timeout = 0; | |
curl_setopt ($ch, CURLOPT_URL, $url); | |
curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout); | |
// Getting binary data | |
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); | |
curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1); | |
$image = curl_exec($ch); | |
curl_close($ch); | |
// output to browser | |
$im = @imagecreatefromstring($image); | |
$tw = @imagesx($im); | |
if(!$tw){ | |
// Font directory + font name | |
$font = '../../fonts/Austrise.ttf'; | |
// Size of the font | |
$fontSize = 18; | |
// Height of the image | |
$height = 32; | |
// Width of the image | |
$width = 250; | |
// Text | |
$str = 'Couldn\'t get image.'; | |
$img_handle = imagecreate ($width, $height) or die ("Cannot Create image"); | |
// Set the Background Color RGB | |
$backColor = imagecolorallocate($img_handle, 255, 255, 255); | |
// Set the Text Color RGB | |
$txtColor = imagecolorallocate($img_handle, 20, 92, 137); | |
$textbox = imagettfbbox($fontSize, 0, $font, $str) or die('Error in imagettfbbox function'); | |
$x = ($width - $textbox[4])/2; | |
$y = ($height - $textbox[5])/2; | |
imagettftext($img_handle, $fontSize, 0, $x, $y, $txtColor, $font , $str) or die('Error in imagettftext function'); | |
header('Content-Type: image/jpeg'); | |
imagejpeg($img_handle,NULL,100); | |
imagedestroy($img_handle); | |
}else{ | |
if($str == 'jpg' || $str == 'jpeg') | |
header("Content-type: image/jpeg"); | |
if($str == 'gif') | |
header("Content-type: image/gif"); | |
if($str == 'png') | |
header("Content-type: image/png"); | |
$th = imagesy($im); | |
$thumbWidth = 200; | |
if($tw <= $thumbWidth){ | |
$thumbWidth = $tw; | |
} | |
$thumbHeight = $th * ($thumbWidth / $tw); | |
$thumbImg = imagecreatetruecolor($thumbWidth, $thumbHeight); | |
if($str == 'gif'){ | |
$colorTransparent = imagecolortransparent($im); | |
imagefill($thumbImg, 0, 0, $colorTransparent); | |
imagecolortransparent($thumbImg, $colorTransparent); | |
} | |
if($str == 'png'){ | |
imagealphablending($thumbImg, false); | |
imagesavealpha($thumbImg,true); | |
$transparent = imagecolorallocatealpha($thumbImg, 255, 255, 255, 127); | |
imagefilledrectangle($thumbImg, 0, 0, $thumbWidth, $thumbHeight, $transparent); | |
} | |
imagecopyresampled($thumbImg, $im, 0, 0, 0, 0, $thumbWidth, $thumbHeight, $tw, $th); | |
if($str == 'jpg' || $str == 'jpeg'){ | |
imagejpeg($thumbImg, NULL, 100); | |
} | |
if($str == 'gif'){ | |
imagegif($thumbImg); | |
} | |
if($str == 'png'){ | |
imagealphablending($thumbImg,TRUE); | |
imagepng($thumbImg, NULL, 9, PNG_ALL_FILTERS); | |
} | |
imagedestroy($thumbImg); | |
} | |
?> | |
get image dir | |
displayImg.php?url=http://phpsnips.com/images/phpsnippets.jpg | |
get image using tag | |
<img src="displayImg.php?url=http://phpsnips.com/images/phpsnippets.jpg" /> | |
/*php tag cloud*/ | |
Ever see those sections on websites where some links are bigger than others? This is that! Simply passs an associative array of strings, and "weight", then echo the result. | |
cloud.php | |
<?php function getCloud( $data = array(), $minFontSize = 12, $maxFontSize = 30 ) | |
{ | |
$minimumCount = min($data); | |
$maximumCount = max($data); | |
$spread = $maximumCount - $minimumCount; | |
$cloudHTML = ''; | |
$cloudTags = array(); | |
$spread == 0 && $spread = 1; | |
foreach( $data as $tag => $count ) | |
{ | |
$size = $minFontSize + ( $count - $minimumCount ) | |
* ( $maxFontSize - $minFontSize ) / $spread; | |
$cloudTags[] = '<a style="font-size: ' . floor( $size ) . 'px' | |
. '" class="tag_cloud" href="#" title="\'' . $tag . | |
'\' returned a count of ' . $count . '">' | |
. htmlspecialchars( stripslashes( $tag ) ) . '</a>'; | |
} | |
return join( "\n", $cloudTags ) . "\n"; | |
} | |
<?php | |
$arr = Array('Actionscript' => 35, 'Adobe' => 22, 'Array' => 44, 'Background' => 43, | |
'Blur' => 18, 'Canvas' => 33, 'Class' => 15, 'Color Palette' => 11, 'Crop' => 42, | |
'Delimiter' => 13, 'Depth' => 34, 'Design' => 8, 'Encode' => 12, 'Encryption' => 30, | |
'Extract' => 28, 'Filters' => 42); | |
echo getCloud($arr, 12, 36); | |
/*daily event using php — by GenoPluto*/ | |
Allows you to change something on a daily basis using just php. | |
// ========================================================================== | |
// Creates a file on the server with the day of the month. | |
// If the day in the file doesn't match today's date, then do 'event' and update the file. | |
// | |
// I use this to change the daily featured photos from a sql database. | |
// ========================================================================== | |
<?PHP | |
$dates = (idate("d")); | |
$mydate = "getdates.txt"; | |
$fh = fopen($mydate, "r"); | |
$theDate = fread($fh, 5); | |
fclose($fh); | |
if ($dates <> $theDate){ | |
// Doesn't match what's in the file, so must be a new day. Update file. | |
$fp = fopen('getdates.txt', w); | |
fwrite($fp, $dates); | |
fclose($fp); | |
// Do something. | |
} | |
// Else ignore. | |
?> | |
EXAMPLE USE: | |
$query = "SELECT * FROM `photo_user` WHERE `idno` >'0'"; | |
$result = mysql_query($query) or die(mysql_error()); | |
while($noticia = mysql_fetch_array($result)) | |
{ | |
// Get total records | |
$total = $total +1; | |
} | |
// Get current selected user from file. | |
$myFile = "getuser.txt"; | |
$fh = fopen($myFile, "r"); | |
$theData = fread($fh, 5); | |
fclose($fh); | |
$userNo = $theData; | |
// Get today's date. | |
$dates = (idate("d")); | |
// See what date is in the file. | |
$mydate = "getdates.txt"; | |
$fh = fopen($mydate, "r"); | |
$theDate = fread($fh, 5); | |
fclose($fh); | |
// Check to see if the dates match. | |
if ($dates <> $theDate){ | |
$userNo = $userNo + 1; | |
if ($userNo > $total){ | |
$userNo = 1; | |
} | |
// Write today's date to file. | |
$fp = fopen('getdates.txt', w); | |
fwrite($fp, $dates); | |
fclose($fp); | |
// Write new user id number to file. | |
$fp = fopen('getuser.txt', w); | |
fwrite($fp, $userNo); | |
fclose($fp); | |
} | |
?> | |
<?php | |
// Each day a new user is selected. | |
$query = "SELECT * FROM `photo_user` WHERE `idno` =' ". $userNo."'"; | |
$result = mysql_query($query) or die(mysql_error()); | |
?> | |
/*replace tags with... — by admin*/ | |
This will replace all html tags with a particular string. | |
<?php | |
/* | |
$content = text you want to parse | |
$replacement = what you want to replace the tags with (Defaults to a space). | |
*/ | |
function tagStripReplace($content, $replacement = " "){ | |
return preg_replace("~<(w*[^>])*>~", $replacement, $content); | |
} | |
echo tagStripReplace("<p>I like pizza</p>",";"); | |
echo tagStripReplace("<p>I like pizza</p><p>Do you?</p>"); | |
?> | |
/*random color generator — by nogre*/ | |
<?php | |
function randomColor() { | |
$str = '#'; | |
for($i = 0 ; $i < 6 ; $i++) { | |
$randNum = rand(0 , 15); | |
switch ($randNum) { | |
case 10: $randNum = 'A'; break; | |
case 11: $randNum = 'B'; break; | |
case 12: $randNum = 'C'; break; | |
case 13: $randNum = 'D'; break; | |
case 14: $randNum = 'E'; break; | |
case 15: $randNum = 'F'; break; | |
} | |
$str .= $randNum; | |
} | |
return $str; | |
} | |
$color = randomColor(); | |
echo '<span style="color:'.$color.'">Random color: '.$color.'</span>'; | |
?> | |
/*password strength — by admin*/ | |
This function calculates how strong a password choice is. A strong password has a value that is as close to possible to 100. | |
<?php | |
/** | |
* | |
* @param String $string | |
* @return float | |
* | |
* Returns a float between 0 and 100. The closer the number is to 100 the | |
* the stronger password is; further from 100 the weaker the password is. | |
*/ | |
function password_strength($string){ | |
$h = 0; | |
$size = strlen($string); | |
foreach(count_chars($string, 1) as $v){ | |
$p = $v / $size; | |
$h -= $p * log($p) / log(2); | |
} | |
$strength = ($h / 4) * 100; | |
if($strength > 100){ | |
$strength = 100; | |
} | |
return $strength; | |
} | |
var_dump(password_strength("Correct Horse Battery Staple")); | |
echo "<br>"; | |
var_dump(password_strength("Super Monkey Ball")); | |
echo "<br>"; | |
var_dump(password_strength("Tr0ub4dor&3")); | |
echo "<br>"; | |
var_dump(password_strength("abc123")); | |
echo "<br>"; | |
var_dump(password_strength("sweet")); | |
/*display time in your time zone — by admin*/ | |
Is your server in some other timezone, and date functions display the date in another time? use this code to change that, to any timezone you would like. | |
<?php | |
// This is for Central Standard Time | |
ini_set('date.timezone','America/Chicago'); | |
echo '<p>'.date("g:i A").'</p>'; | |
?> | |
[url=http://us3.php.net/manual/en/timezones.php]More Time Zone Locations[/url] | |
/*country list generator — by bystwn22*/ | |
<?php | |
function countrylist($action = 'dropdown', $selectedid = null) { | |
$country_list = array( | |
"Afghanistan", | |
"Albania", | |
"Algeria", | |
"Andorra", | |
"Angola", | |
"Antigua and Barbuda", | |
"Argentina", | |
"Armenia", | |
"Australia", | |
"Austria", | |
"Azerbaijan", | |
"Bahamas", | |
"Bahrain", | |
"Bangladesh", | |
"Barbados", | |
"Belarus", | |
"Belgium", | |
"Belize", | |
"Benin", | |
"Bhutan", | |
"Bolivia", | |
"Bosnia and Herzegovina", | |
"Botswana", | |
"Brazil", | |
"Brunei", | |
"Bulgaria", | |
"Burkina Faso", | |
"Burundi", | |
"Cambodia", | |
"Cameroon", | |
"Canada", | |
"Cape Verde", | |
"Central African Republic", | |
"Chad", | |
"Chile", | |
"China", | |
"Colombi", | |
"Comoros", | |
"Congo (Brazzaville)", | |
"Congo", | |
"Costa Rica", | |
"Cote d'Ivoire", | |
"Croatia", | |
"Cuba", | |
"Cyprus", | |
"Czech Republic", | |
"Denmark", | |
"Djibouti", | |
"Dominica", | |
"Dominican Republic", | |
"East Timor (Timor Timur)", | |
"Ecuador", | |
"Egypt", | |
"El Salvador", | |
"Equatorial Guinea", | |
"Eritrea", | |
"Estonia", | |
"Ethiopia", | |
"Fiji", | |
"Finland", | |
"France", | |
"Gabon", | |
"Gambia, The", | |
"Georgia", | |
"Germany", | |
"Ghana", | |
"Greece", | |
"Grenada", | |
"Guatemala", | |
"Guinea", | |
"Guinea-Bissau", | |
"Guyana", | |
"Haiti", | |
"Honduras", | |
"Hungary", | |
"Iceland", | |
"India", | |
"Indonesia", | |
"Iran", | |
"Iraq", | |
"Ireland", | |
"Israel", | |
"Italy", | |
"Jamaica", | |
"Japan", | |
"Jordan", | |
"Kazakhstan", | |
"Kenya", | |
"Kiribati", | |
"Korea, North", | |
"Korea, South", | |
"Kuwait", | |
"Kyrgyzstan", | |
"Laos", | |
"Latvia", | |
"Lebanon", | |
"Lesotho", | |
"Liberia", | |
"Libya", | |
"Liechtenstein", | |
"Lithuania", | |
"Luxembourg", | |
"Macedonia", | |
"Madagascar", | |
"Malawi", | |
"Malaysia", | |
"Maldives", | |
"Mali", | |
"Malta", | |
"Marshall Islands", | |
"Mauritania", | |
"Mauritius", | |
"Mexico", | |
"Micronesia", | |
"Moldova", | |
"Monaco", | |
"Mongolia", | |
"Morocco", | |
"Mozambique", | |
"Myanmar", | |
"Namibia", | |
"Nauru", | |
"Nepa", | |
"Netherlands", | |
"New Zealand", | |
"Nicaragua", | |
"Niger", | |
"Nigeria", | |
"Norway", | |
"Oman", | |
"Pakistan", | |
"Palau", | |
"Panama", | |
"Papua New Guinea", | |
"Paraguay", | |
"Peru", | |
"Philippines", | |
"Poland", | |
"Portugal", | |
"Qatar", | |
"Romania", | |
"Russia", | |
"Rwanda", | |
"Saint Kitts and Nevis", | |
"Saint Lucia", | |
"Saint Vincent", | |
"Samoa", | |
"San Marino", | |
"Sao Tome and Principe", | |
"Saudi Arabia", | |
"Senegal", | |
"Serbia and Montenegro", | |
"Seychelles", | |
"Sierra Leone", | |
"Singapore", | |
"Slovakia", | |
"Slovenia", | |
"Solomon Islands", | |
"Somalia", | |
"South Africa", | |
"Spain", | |
"Sri Lanka", | |
"Sudan", | |
"Suriname", | |
"Swaziland", | |
"Sweden", | |
"Switzerland", | |
"Syria", | |
"Taiwan", | |
"Tajikistan", | |
"Tanzania", | |
"Thailand", | |
"Togo", | |
"Tonga", | |
"Trinidad and Tobago", | |
"Tunisia", | |
"Turkey", | |
"Turkmenistan", | |
"Tuvalu", | |
"Uganda", | |
"Ukraine", | |
"United Arab Emirates", | |
"United Kingdom", | |
"United States", | |
"Uruguay", | |
"Uzbekistan", | |
"Vanuatu", | |
"Vatican City", | |
"Venezuela", | |
"Vietnam", | |
"Yemen", | |
"Zambia", | |
"Zimbabwe" | |
); | |
if ($action == 'dropdown') { | |
foreach ($country_list as $country) { | |
echo "<option value=\"".$country."\""; | |
if (!empty($selectedid)) { | |
if ($selectedid == $country) { | |
echo " selected=\"selected\""; | |
} | |
} | |
echo ">".$country."</option>\n"; | |
} | |
} | |
elseif ($action == 'list') { | |
foreach ($country_list as $country) { | |
echo "<li>".$country."</li>\n"; | |
} | |
} | |
} | |
?> | |
Instruction: | |
$action = Type of Output (dropdown or list) | |
$selectedid = Selected option value (not needed) | |
Example 1: | |
<select name="country"> | |
<?php countrylist('dropdown','Albania') ?> | |
</select> | |
Output: | |
<select> | |
<option value="Afghanistan">Afghanistan</option> | |
<option value="Albania" selected="selected">Albania</option> | |
<option value="Algeria">Algeria</option> | |
<option................. | |
</select> | |
Example 2: | |
<ul> | |
<?php countrylist('list') ?> | |
</ul> | |
Output: | |
<ul> | |
<li>Afghanistan</li> | |
<li>Albania</li> | |
<li>Algeria</li> | |
<li................. | |
</ul> | |
/*get class hierarchy — by Oliver A*/ | |
Returns the complete class hierarchy of an object or a class name. Can be used as method or function. If you have any trouble with the LGPL licence send me a mail. | |
<?php | |
/** | |
* @author oliver anan <[email protected]> | |
* @version 1.0 | |
* @copyright oliver anan | |
* @license LGPL 3 http://www.gnu.org/licenses/lgpl.html | |
* Returns the class hierarchy of an object / a class name | |
* as an string array. | |
* The objects class/the classname is the first element. | |
* @param object|string $obj an objet or a class name | |
* @return string[] | |
*/ | |
public function getClassHierarchy($obj){ | |
if(is_object($obj)){ | |
$class = get_class($obj); | |
} | |
elseif(!class_exists($obj)){ | |
throw new InvalidArgumentException("class $obj is not defined" ); | |
} | |
$hierarchy = array(); | |
while($class){ | |
$hierarchy[] = $class; | |
$class = get_parent_class($class); | |
} | |
return $hierarchy; | |
} | |
/*user agent - mobile, tablet or not? (works with android, iphone, window phone and more) — by LukasFT | |
*/ | |
To to download code and example, [url=http://j.gs/447947/uacheckphp]Click here[/url] To remove the credits, please contact me at [email protected]. | |
<?php | |
function userAgent($ua){ | |
## This credit must stay intact (Unless you have a deal with @lukasmig or [email protected] | |
## Made by Lukas Frimer Tholander from Made In Osted Webdesign. | |
## Price will be $2 | |
$iphone = strstr(strtolower($ua), 'mobile'); //Search for 'mobile' in user-agent (iPhone have that) | |
$android = strstr(strtolower($ua), 'android'); //Search for 'android' in user-agent | |
$windowsPhone = strstr(strtolower($ua), 'phone'); //Search for 'phone' in user-agent (Windows Phone uses that) | |
function androidTablet($ua){ //Find out if it is a tablet | |
if(strstr(strtolower($ua), 'android') ){//Search for android in user-agent | |
if(!strstr(strtolower($ua), 'mobile')){ //If there is no ''mobile' in user-agent (Android have that on their phones, but not tablets) | |
return true; | |
} | |
} | |
} | |
$androidTablet = androidTablet($ua); //Do androidTablet function | |
$ipad = strstr(strtolower($ua), 'ipad'); //Search for iPad in user-agent | |
if($androidTablet || $ipad){ //If it's a tablet (iPad / Android) | |
return 'tablet'; | |
} | |
elseif($iphone && !$ipad || $android && !$androidTablet || $windowsPhone){ //If it's a phone and NOT a tablet | |
return 'mobile'; | |
} | |
else{ //If it's not a mobile device | |
return 'desktop'; | |
} | |
} | |
?> | |
/*visit counter — by maque*/ | |
if one visits for the first time, it says welcome. otherwise it gives the visit number and says when the user was on the site last time. | |
<?php | |
// set the variable to 0, it'll matter only if the cookie for the variable is not set | |
$visitCounter = 0; | |
// if cookie is set for the variable, it'll go to $visitCounter and get added by 1; otherwise it'll show 0 for tha variable | |
if(isset($_COOKIE['visitCounter'])){ | |
$visitCounter = $_COOKIE['visitCounter']; | |
$visitCounter ++; | |
} | |
// if the last visist cookie is set, it'll pass the value to $lastVisit, and it'll be displayed below; | |
if(isset($_COOKIE['lastVisit'])){ | |
$lastVisit = $_COOKIE['lastVisit']; | |
} | |
// set cookie for visitCounter | |
setcookie('visitCounter', $visitCounter+1, time()+3600); | |
// set cookie for last visit | |
setcookie('lastVisit', date("d-m-Y H:i:s"), time()+3600); | |
// show the respected values | |
// is the variable is not set, say 'welcome', otherwise show the info about visit number and last visit date | |
if($visitCounter == 0){ | |
echo "Welcome"; | |
} else { | |
echo "This is your visit number ".$visitCounter; | |
echo '<br>'; | |
echo "Last time, you were here ".$lastVisit; | |
} | |
?> | |
/*test if a value is in a list — by admin*/ | |
Test to see if a value is in a list. This can replace large OR statements. | |
<?php | |
function in(){ | |
$args = func_get_args(); | |
$value = array_shift($args); | |
foreach($args as $arg){ | |
if($value == $arg){ | |
return true; | |
} | |
} | |
return false; | |
} | |
$number = mt_rand(1, 10); | |
if(in($number, 2, 4, 6, 8, 10)){ | |
echo "I was found in the list!"; | |
} | |
/*cache using htaccess*/ | |
ExpiresActive on | |
ExpiresActive on | |
ExpiresByType image/gif "access plus 1 month" | |
ExpiresByType image/png "access plus 1 month" | |
ExpiresByType image/jpg "access plus 1 month" | |
ExpiresByType image/jpeg "access plus 1 month" | |
ExpiresByType video/ogg "access plus 1 month" | |
ExpiresByType audio/ogg "access plus 1 month" | |
ExpiresByType video/mp4 "access plus 1 month" | |
ExpiresByType video/webm "access plus 1 month" | |
/*compression using htaccess*/ | |
FilterDeclare COMPRESS | |
FilterProvider COMPRESS DEFLATE resp=Content-Type $text/html | |
FilterProvider COMPRESS DEFLATE resp=Content-Type $text/css | |
FilterProvider COMPRESS DEFLATE resp=Content-Type $text/javascript | |
FilterChain COMPRESS | |
FilterProtocol COMPRESS DEFLATE change=yes;byteranges=no | |
#older apache | |
SetOutputFilter DEFLATE | |
AddOutputFilterByType DEFLATE text/html text/css text/javascript | |
/*string links made clickable*/ | |
function makeClickableLinks($text) { | |
$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); | |
return $text; | |
} | |
/*21. Detect AJAX Request*/ | |
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest'){ | |
//If AJAX Request Then | |
}else{ | |
//something else | |
} | |
/*13. Find Similarity Between Two Strings*/ | |
similar_text($string1, $string2, $percent); | |
/*10. Get Real IP Address of Client*/ | |
function getRealIpAddr() | |
{ | |
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']; | |
} | |
return $ip; | |
} | |
/*8. Parse XML Data*/ | |
//xml string | |
$xml_string="<?xml version='1.0'?> | |
<users> | |
<user id='398'> | |
<name>Foo</name> | |
<email>[email protected]</name> | |
</user> | |
<user id='867'> | |
<name>Foobar</name> | |
<email>[email protected]</name> | |
</user> | |
</users>"; | |
//load the xml string using simplexml | |
$xml = simplexml_load_string($xml_string); | |
//loop through the each node of user | |
foreach ($xml->user as $user) | |
{ | |
//access attribute | |
echo $user['id'], ' '; | |
//subnodes are accessed by -> operator | |
echo $user->name, ' '; | |
echo $user->email, '<br />'; | |
} | |
7. Parse JSON Data | |
$json_string='{"id":1,"name":"foo","email":"[email protected]","interest":["wordpress","php"]} '; | |
$obj=json_decode($json_string); | |
echo $obj->name; //prints foo | |
echo $obj->interest[1]; //prints php | |
6. Destroy Directory | |
/***** | |
*@dir - Directory to destroy | |
*@virtual[optional]- whether a virtual directory | |
*/ | |
function destroyDir($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; | |
} | |
} | |
5. List Directory Contents | |
function list_files($dir) | |
{ | |
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); | |
} | |
} | |
} | |
1. Human Readable Random String | |
/************** | |
*@length - length of random string (must be a multiple of 2) | |
**************/ | |
function readable_random_string($length = 6){ | |
$conso=array("b","c","d","f","g","h","j","k","l", | |
"m","n","p","r","s","t","v","w","x","y","z"); | |
$vocal=array("a","e","i","o","u"); | |
$password=""; | |
srand ((double)microtime()*1000000); | |
$max = $length/2; | |
for($i=1; $i<=$max; $i++) | |
{ | |
$password.=$conso[rand(0,19)]; | |
$password.=$vocal[rand(0,4)]; | |
} | |
return $password; | |
} | |
/*Calculate full database size*/ | |
function CalcFullDatabaseSize($database, $db) { | |
$tables = mysql_list_tables($database, $db); | |
if (!$tables) { return -1; } | |
$table_count = mysql_num_rows($tables); | |
$size = 0; | |
for ($i=0; $i < $table_count; $i++) { | |
$tname = mysql_tablename($tables, $i); | |
$r = mysql_query("SHOW TABLE STATUS FROM ".$database." LIKE '".$tname."'"); | |
$data = mysql_fetch_array($r); | |
$size += ($data['Index_length'] + $data['Data_length']); | |
}; | |
$units = array(' B', ' KB', ' MB', ' GB', ' TB'); | |
for ($i = 0; $size > 1024; $i++) { $size /= 1024; } | |
return round($size, 2).$units[$i]; | |
} | |
usage: | |
/* | |
** Example: | |
*/ | |
// open mysql connection: | |
$handle = mysql_connect('localhost', 'user', 'password'); | |
if (!$handle) { die('Connection failed!'); } | |
// get the size of all tables in this database: | |
print CalcFullDatabaseSize('customer1234', $handle); | |
// --> returns something like: 484.2 KB | |
// close connection: | |
mysql_close($handle); | |
/*get country by ip*/ | |
<?php | |
function getLocationInfoByIp(){ | |
$client = @$_SERVER['HTTP_CLIENT_IP']; | |
$forward = @$_SERVER['HTTP_X_FORWARDED_FOR']; | |
$remote = @$_SERVER['REMOTE_ADDR']; | |
$result = array('country'=>'', 'city'=>''); | |
if(filter_var($client, FILTER_VALIDATE_IP)){ | |
$ip = $client; | |
}elseif(filter_var($forward, FILTER_VALIDATE_IP)){ | |
$ip = $forward; | |
}else{ | |
$ip = $remote; | |
} | |
$ip_data = @json_decode | |
(file_get_contents("http://www.geoplugin.net/json.gp?ip=".$ip)); | |
if($ip_data && $ip_data->geoplugin_countryName != null){ | |
$result['country'] = $ip_data->geoplugin_countryCode; | |
$result['city'] = $ip_data->geoplugin_city; | |
} | |
return $result; | |
} | |
?> | |
/*extract numbers from a string*/ | |
PHP - Extract numbers from a string | |
$str = 'In My Cart : 11 12 items'; | |
preg_match_all('!\d+!', $str, $matches); | |
print_r($matches); | |
List only certain files in a folder with PHP | |
Lists only certain files extensions as links on a page from a defined folder | |
<?php | |
//Define directory for files listing | |
//original example | |
//$files = glob('/path/to/dir/*.xml'); | |
$files = glob('*.php'); | |
//to limit what is displayed you can use a diff listing: | |
//$files = array_diff($files, array('index.php','opendb.php')); | |
foreach ($files as $value) { | |
echo "<a href=http://changetoyoursite/$value>".$value."</a><br>"; | |
} | |
?> | |
Sanitize database inputs | |
function cleanInput($input) { | |
$search = array( | |
'@<script[^>]*?>.*?</script>@si', // Strip out javascript | |
'@<[\/\!]*?[^<>]*?>@si', // Strip out HTML tags | |
'@<style[^>]*?>.*?</style>@siU', // Strip style tags properly | |
'@<![\s\S]*?--[ \t\n\r]*>@' // Strip multi-line comments | |
); | |
$output = preg_replace($search, '', $input); | |
return $output; | |
} | |
?> | |
<?php | |
function sanitize($input) { | |
if (is_array($input)) { | |
foreach($input as $var=>$val) { | |
$output[$var] = sanitize($val); | |
} | |
} | |
else { | |
if (get_magic_quotes_gpc()) { | |
$input = stripslashes($input); | |
} | |
$input = cleanInput($input); | |
$output = mysql_real_escape_string($input); | |
} | |
return $output; | |
} | |
Debug Function | |
function debug($var) { | |
echo '<pre>'; | |
echo "File:".__FILE__."<br>"; | |
echo "Line:" .__LINE__."<br>"; | |
print_r($var); | |
echo '</pre>'; | |
} | |
Star out password for reminder | |
Nice little function will star out a password for simple reminder - Original Password: password41! New: ******d41! Enter number of letters to show at end with $number_show | |
function star_out_password($password,$number_show){ | |
$star = ''; | |
if(is_numeric($number_show) && $number_show < strlen($password){ | |
$star = str_repeat('*',(strlen($password) -$number_show)) . substr($password,-$number_show,$number_show); | |
} | |
return $star; | |
} | |
/* TRY IT OUT */ | |
$reminder = star_out_password('m$ypaSs423',4); // returns *******s423 | |
Get current page | |
function curPageURL() { | |
$pageURL = 'http'; | |
//if ($_SERVER["HTTPS"] == "on") {$pageURL .= "s";} | |
$pageURL .= "://"; | |
if ($_SERVER["SERVER_PORT"] != "80") { | |
$pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"]; | |
} else { | |
$pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"]; | |
} | |
return $pageURL; | |
} | |
Find All Links on a Page | |
$html = file_get_contents('http://www.example.com'); | |
$dom = new DOMDocument(); | |
@$dom->loadHTML($html); | |
// grab all the on the page | |
$xpath = new DOMXPath($dom); | |
$hrefs = $xpath->evaluate("/html/body//a"); | |
for ($i = 0; $i < $hrefs->length; $i++) { | |
$href = $hrefs->item($i); | |
$url = $href->getAttribute('href'); | |
echo $url.'<br />'; | |
} | |
kill url injection when using 'PHP_SELF' | |
kill url injection when using 'PHP_SELF' in forms | |
$_SERVER['PHP_SELF'] = htmlspecialchars($_SERVER['PHP_SELF']); | |
[PHP] Is URL online? | |
function is_online( $url ){ | |
$url = @parse_url($url); | |
if (!$url) return false; | |
$url = array_map('trim', $url); | |
$url['port'] = (!isset($url['port'])) ? 80 : (int)$url['port']; | |
$path = (isset($url['path'])) ? $url['path'] : '/'; | |
$path .= (isset($url['query'])) ? "?$url[query]" : ''; | |
if (isset($url['host']) && $url['host'] != gethostbyname($url['host'])) { | |
$fp = fsockopen($url['host'], $url['port'], $errno, $errstr, 30); | |
if (!$fp) return false; //socket not opened | |
fputs($fp, "HEAD $path HTTP/1.1\r\nHost: $url[host]\r\n\r\n"); //socket opened | |
$headers = fread($fp, 4096); | |
fclose($fp); | |
if(preg_match('#^HTTP/.*\s+[(200|301|302)]+\s#i', $headers)){ | |
//matching header | |
return true; | |
} | |
else return false; | |
} // if parse url | |
else return false; | |
} | |
Verify if PDO extension is installed | |
<?php | |
if (!defined('PDO::ATTR_DRIVER_NAME')) | |
{ | |
echo 'PDO unavailable'; | |
} | |
elseif (defined('PDO::ATTR_DRIVER_NAME')) | |
{ | |
echo 'PDO available'; | |
} | |
?> | |
timeSince() PHP function | |
function timeBetween($start,$end) { | |
if (empty($start) || empty($end)) { return; } | |
else return timeSince(strtotime($start),strtotime($end),2,'short'); | |
} | |
/** | |
* Get time difference in human readable format | |
* $start is start time (unix time), $end is end time (unix time), $units is numeric and defines how many time units to display | |
*/ | |
function timeSince($start,$end='',$units=2,$words='long') { // $start and $end should be Unix time() format | |
switch($words) { | |
case 'long': | |
$unitName = array( // Change this array to reflect what should be displayed as unit names and pluralization append | |
'year' => 'year', | |
'month' => 'month', | |
'week' => 'week', | |
'day' => 'day', | |
'hour' => 'hour', | |
'minute' => 'minute', | |
'second' => 'second', | |
'plural' => 's' | |
); | |
break; | |
case 'short': | |
$unitName = array( // Change this array to reflect what should be displayed as unit names and pluralization append | |
'year' => 'yr', | |
'month' => 'mo', | |
'week' => 'wk', | |
'day' => 'day', | |
'hour' => 'hr', | |
'minute' => 'min', | |
'second' => 'sec', | |
'plural' => 's' | |
); | |
break; | |
} | |
// Common time periods as an array of arrays | |
$periods = array( | |
array(60 * 60 * 24 * 365 , $unitName['year']), | |
array(60 * 60 * 24 * 30 , $unitName['month']), | |
array(60 * 60 * 24 * 7, $unitName['week']), | |
array(60 * 60 * 24 , $unitName['day']), | |
array(60 * 60 , $unitName['hour']), | |
array(60 , $unitName['minute']), | |
array(1 , $unitName['second']), | |
); | |
$end = (!empty($end))?$end:time(); // if no end timestamp given use the current one for end date | |
$since = $end - $start; // Find the difference of time between now and the past | |
// Loop around the periods, starting with the biggest | |
for ($i = 0, $j = count($periods); $i < $j; $i++){ | |
$seconds = $periods[$i][0]; | |
$name = $periods[$i][1]; | |
// Find the biggest whole period | |
if (($count = floor($since / $seconds)) != 0){ | |
break; | |
} | |
} | |
$output = ($count == 1) ? '1 '.$name : "$count {$name}s"; | |
$deducted = ($seconds * $count); | |
for($z = 1, $j = count($periods); $z < $j; $z++) { | |
if ($units > $z && $i + $z < $j){ | |
// Retrieving the next requested relevant period | |
$seconds = $periods[$i + $z][0]; | |
$name = $periods[$i + $z][1]; | |
// Only show it if it's greater than 0 | |
if (($count = floor(($since - $deducted) / $seconds)) != 0){ | |
$deducted = $deducted+($seconds * $count); | |
$output .= ($count == 1) ? ', 1 '.$name : ", {$count} {$name}{$unitName['plural']}"; | |
} | |
} | |
} | |
return $output; | |
} | |
/** | |
* Identical to timeSince except your end time should be greater than your start time | |
*/ | |
function timeUntil($end,$start='',$units=2) { | |
$start = (!empty($start))?$start:time(); | |
return timeSince($start,$end,$units); | |
} | |
HTTP Header Status Codes With PHP. | |
// HTTP HEADER STATUS CODES | |
// Use this header instruction to fix 404 headers | |
// produced by url rewriting... | |
header('HTTP/1.1 200 OK'); | |
// Page was not found: | |
header('HTTP/1.1 404 Not Found'); | |
// Access forbidden: | |
header('HTTP/1.1 403 Forbidden'); | |
// The page moved permanently should be used for | |
// all redrictions, because search engines know | |
// what's going on and can easily update their urls. | |
header('HTTP/1.1 301 Moved Permanently'); | |
// Server error | |
header('HTTP/1.1 500 Internal Server Error'); | |
// Redirect to a new location: | |
header('Location: http://www.example.org/'); | |
// Redriect with a delay: | |
header('Refresh: 10; url=http://www.example.org/'); | |
print 'You will be redirected in 10 seconds'; | |
// you can also use the HTML syntax: | |
// <meta http-equiv="refresh" content="10;http://www.example.org/ /> | |
// override X-Powered-By value | |
header('X-Powered-By: PHP/4.4.0'); | |
header('X-Powered-By: Brain/0.6b'); | |
// content language (en = English) | |
header('Content-language: en'); | |
// last modified (good for caching) | |
$time = time() - 60; // or filemtime($fn), etc | |
header('Last-Modified: '.gmdate('D, d M Y H:i:s', $time).' GMT'); | |
// header for telling the browser that the content | |
// did not get changed | |
header('HTTP/1.1 304 Not Modified'); | |
// set content length (good for caching): | |
header('Content-Length: 1234'); | |
// Headers for an download: | |
header('Content-Type: application/octet-stream'); | |
header('Content-Disposition: attachment; filename="example.zip"'); | |
header('Content-Transfer-Encoding: binary'); | |
// load the file to send: | |
readfile('example.zip'); | |
// Disable caching of the current document: | |
header('Cache-Control: no-cache, no-store, max-age=0, must-revalidate'); | |
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past | |
header('Pragma: no-cache'); | |
// set content type: | |
header('Content-Type: text/html; charset=iso-8859-1'); | |
header('Content-Type: text/html; charset=utf-8'); | |
header('Content-Type: text/plain'); // plain text file | |
header('Content-Type: image/jpeg'); // JPG picture | |
header('Content-Type: application/zip'); // ZIP file | |
header('Content-Type: application/pdf'); // PDF file | |
header('Content-Type: audio/mpeg'); // Audio MPEG (MP3,...) file | |
header('Content-Type: application/x-shockwave-flash'); // Flash animation | |
// show sign in box | |
header('HTTP/1.1 401 Unauthorized'); | |
header('WWW-Authenticate: Basic realm="Top Secret"'); | |
print 'Text that will be displayed if the user hits cancel or '; | |
print 'enters wrong login data'; | |
PHP API Header For Function Libraray (Call Any PHP Functions Via Ajax) | |
Place your functions below the header and then call them by posting to the script with any kind of ajax : $('#test').load('base/ajax/ajaxapi.php',{method:'sha256',params:"'batman','gargamelhatessmurfs'"}); for example. | |
/** | |
* AJAX API FOR PHP FUNCTION LIBRARY | |
*/ | |
if(function_exists(stripslashes(trim($_POST['method'])))){ //IF THE FUNCTION EXISTS (IN THIS SCRIPT) | |
$method = stripslashes(trim($_POST['method'])); | |
$params = str_replace("'", '',stripslashes(trim($_POST['params']))); //strip single quotes if used | |
$opts= explode(',',$params); //turn the parameters string into an array | |
$function = new ReflectionFunction($method); //instantiate the function as an object | |
$function->invokeArgs($opts); //invoke the function with an array of arguments (if given) | |
}else{ //ELSE THE FUNCTION DOES NOT EXIST | |
echo "error the function you called : ".$_POST['method']."(".$_POST['params'].")"." does not exist"; | |
exit; | |
} | |
exit; | |
///////////////////////////////////////////////////////////////////////////////////////////////// | |
///////////////////////////////////////////////////////////////////////////////////////////////// | |
// PLACE YOUR FUNCTIONS BELOW HERE. // | |
///////////////////////////////////////////////////////////////////////////////////////////////// | |
///////////////////////////////////////////////////////////////////////////////////////////////// | |
Display the source code of a webpage. | |
URL: http://perishablepress.com/code-snippets/#code-snippets_php | |
Want to be able to display the source code of any webpage, with line numbering? Here is a simple code snippet to do it. Just modify the url on line 2 at your convenience. Or even better, make a pretty function according to your needs. | |
Expand | Embed | Plain Text | |
// display source code | |
$lines = file('http://google.com/'); | |
foreach ($lines as $line_num => $line) { | |
// loop thru each line and prepend line numbers | |
echo "Line #<b>{$line_num}</b> : " . htmlspecialchars($line) . "<br>\n"; | |
} | |
Get Whois Information. | |
URL: http://www.jonasjohn.de/snippets/php/whois-query.htm | |
If you need to get the whois information for a specific domain, why not using PHP to do it? The following function take a domain name as a parameter, and then display the whois info related to the 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); | |
$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", | |
"aero" => "whois.information.aero", | |
"nl" => "whois.domain-registry.nl" | |
); | |
if (!isset($servers[$ext])){ | |
die('Error: No matching nic server found!'); | |
} | |
$nic_server = $servers[$ext]; | |
$output = ''; | |
// connect to whois server: | |
if ($conn = fsockopen ($nic_server, 43)) { | |
fputs($conn, $domain." | |
"); | |
while(!feof($conn)) { | |
$output .= fgets($conn,128); | |
} | |
fclose($conn); | |
} | |
else { die('Error: Could not connect to ' . $nic_server . '!'); } | |
return $output; | |
} | |
PHP - Generating Emoticons | |
URL: http://www.flashstar.nl/article-37.html | |
If you are a PHP developer, you are probably aware that you can pass an array of strings as the search strings and an array as the replacements to the str_replace function. In this example you can see how to automatically replace smiley shortcuts by an image. | |
<?php | |
function emoticons($text) { | |
$emoticons = array( | |
'<img src="images/smiley-happy.png" alt="emoticon" />' => array('1' => ':-)', '2' => ':)'), | |
'<img src="images/smiley-wink.png" alt="emoticon" />' => array('1' => ';-)', '2' => ';)'), | |
'<img src="images/smiley-cool.png" alt="emoticon" />' => array('1' => '8)', '2' => '8|') | |
); | |
foreach ($emoticons as $key => $emoticon) { | |
$text = str_replace($emoticon, $key, $text); | |
} | |
return $text; | |
} | |
echo emoticons('This is :) a text ;-) with :-) emoticons 8)'); | |
?> | |
Get the absolute webroot URL. | |
if (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) { define("PROTOCOL", "https://");} // DEFINE PROTOCOL | |
else { define("PROTOCOL", "http://"); } | |
define("WEBROOT_URL", PROTOCOL.$_SERVER['HTTP_HOST'].dirname($_SERVER['PHP_SELF'])); // DEFINE WEBROOT PATH | |
A function to get a files contents with curl. | |
A handy function to get the contents of a file with curl. Accepts $_path as a parameter. | |
function file_content($_path) { | |
$ch = curl_init(); | |
curl_setopt($ch, CURLOPT_HEADER, 0); | |
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //Set curl to return the data instead of printing it to the browser. | |
curl_setopt($ch, CURLOPT_URL, $_path); | |
$data = curl_exec($ch); | |
curl_close($ch); | |
return $data; | |
} | |
A function to see if a file exists with curl. | |
This function will use curl to see if a file exists at the location it's provided. It accepts $_path as a parameter. | |
function file_alive($_path) { | |
$handle = curl_init($_path); | |
if (false === $handle) {return false;} | |
curl_setopt($handle, CURLOPT_HEADER, false); | |
curl_setopt($handle, CURLOPT_FAILONERROR, true); | |
curl_setopt($handle, CURLOPT_HTTPHEADER, Array("User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.15) Gecko/20080623 Firefox/2.0.0.15") ); // request as if Firefox because some sites request a valid header from you | |
curl_setopt($handle, CURLOPT_NOBODY, true); | |
curl_setopt($handle, CURLOPT_RETURNTRANSFER, false); | |
$alive = curl_exec($handle); | |
curl_close($handle); | |
return $alive; | |
} | |
A function to get file sizes in multiple formats with curl. | |
A function to get a files size via curl. Accepts $path, $unit, $float, $username & $_password; In the listed order. | |
function file_size($_path, $_unit, $_float = null, $_username = null, $_password = null) { | |
$_unit = trim(strtoupper($_unit)); //Making the unit compatible | |
function unit_size($data, $_unit, $_float) { | |
if (!isset($_float)) {$_float = 3;} // float 3 decimal places by default | |
$sizes = array("B"=>0, "KB"=>1, "MB"=>2, "GB"=>3, "TB"=>4, "PB"=>5, "EB"=>6, "ZB"=>7, "YB"=>8); //Associated with each unit is the exponent that will be used to do the conversion from bytes | |
if (array_key_exists($_unit, $sizes) && $sizes[$_unit] != 0) { // If the unit is not bytes we get down to business | |
$number = $sizes[$_unit]; | |
$total = $data / (pow(1024, $number)); | |
return round($total, $_float)." ".$_unit; | |
} | |
else {return $data." B";} // If you want bytes then we just skip to this part | |
} | |
$ch = curl_init($_path); | |
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); | |
curl_setopt($ch, CURLOPT_HEADER, TRUE); | |
if(isset($userame) && isset($password)) { $headers = array('Authorization: Basic '.base64_encode("$user:$pw")); curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); } | |
curl_setopt($ch, CURLOPT_NOBODY, TRUE); | |
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); | |
curl_setopt($ch, CURLOPT_URL, $_path); //specify the ur | |
$data = curl_exec($ch); | |
$size = curl_getinfo($ch, CURLINFO_CONTENT_LENGTH_DOWNLOAD); | |
curl_close($ch); | |
return unit_size($size, $_unit, $_float); | |
} | |
A function to get file mime-types with curl. | |
This is a function to retrieve the mime-type of a file by checking the header response with curl. It accepts the file-path as a parameter & it also has a fallback for empty returns. | |
function file_mime($_path) { | |
$ch = curl_init($_path); | |
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); | |
curl_exec($ch); | |
$content_info = curl_getinfo($ch, CURLINFO_CONTENT_TYPE); | |
curl_close($ch); | |
$content_parts = explode(";", $content_info); | |
$mime = $content_parts[0]; | |
if(isset($mime) && !empty($mime)){return $mime;} | |
else if (function_exists('finfo_open')) { | |
$get_info = new finfo; | |
$mime = $finfo->file($_path, FILEINFO_MIME); | |
return $mime; | |
} | |
else { $mime = 'application/octet-stream'; return $mime;} | |
} | |
PHP SSH API class | |
This SSH API is used to execute remote commands, send and receive files. | |
class SshApi extends BaseObject{ | |
public $session = null; | |
public $authenticated = false; | |
public function __construct(){ | |
} | |
public function connect($host){ | |
$this->session = ssh2_connect($host); | |
return $this->session; | |
} | |
public function pubkeyFile($sshUser, $sshPub, $sshPriv, $sshPass){ | |
if ( ! $this->session ) return false; | |
if ( empty($sshPass) ){ | |
$b = ssh2_auth_pubkey_file( $this->session, $sshUser, $sshPub, $sshPriv); | |
} | |
else | |
$b = ssh2_auth_pubkey_file( $this->session, $sshUser, $sshPub, $sshPriv, $sshPass); | |
if ( $b ) $this->authenticated = true; | |
return $b; | |
} | |
public function send($localfile, $remotefile, $perms=0660){ | |
$this->debug(__METHOD__); | |
if ( ! $this->session ) return false; | |
$this->debug('Sending '. $localfile . ' to ' . $remotefile); | |
$b = ssh2_scp_send($this->session, $localfile, $remotefile, $perms); | |
return $b; | |
} | |
public function recv($remotefile , $localfile){ | |
if ( ! $this->session ) return false; | |
$b = ssh2_scp_recv($this->session , $remotefile , $localfile ); | |
return $b; | |
} | |
public function exec($command){ | |
if ( ! $this->session ) return false; | |
$stream = ssh2_exec($this->session, $command); | |
return $stream; | |
} | |
} | |
Detect City by IP function | |
URL: http://www.catswhocode.com/blog/useful-php-code-snippets-and-functions | |
This will take an IP and try to find the city. | |
function detect_city($ip) { | |
$default = 'UNKNOWN'; | |
if (!is_string($ip) || strlen($ip) < 1 || $ip == '127.0.0.1' || $ip == 'localhost') | |
$ip = '8.8.8.8'; | |
$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; | |
} | |
} | |
PHP Function to Convert 12 Hour Time to 24 Hour Format | |
Convert 12-hour time format with hour, minutes, seconds, and meridiem into 24-hour format. Performs data correction to make sure hours, minutes and seconds have leading zeros if needed. | |
The trick here is to use strtotime() where we pass the time string in this format: "hh:mm:ss meridiem" Example: "02:30:00 pm" | |
<?php | |
function to_24_hour($hours,$minutes,$seconds,$meridiem){ | |
$hours = sprintf('%02d',(int) $hours); | |
$minutes = sprintf('%02d',(int) $minutes); | |
$seconds = sprintf('%02d',(int) $seconds); | |
$meridiem = (strtolower($meridiem)=='am') ? 'am' : 'pm'; | |
return date('H:i:s', strtotime("{$hours}:{$minutes}:{$seconds} {$meridiem}")); | |
} | |
echo to_24_hour( 1, 2, 3, 'pm' ); // Returns 13:02:03 | |
echo to_24_hour( '02', '30', '00', 'pm' ); // Returns 14:30:00 | |
?> | |
Paginate WordPress Posts | |
URL: http://www.design-ninja.net | |
Place the function in your functions.php file of your theme... | |
Then, simply call like this: wp_paginate('', 3); The first param is optional, the second dictates how many pages before and after the current page link will show... | |
<?php | |
function wp_paginate($pgs = '', $rng = 2) { | |
$itm = ($rng * 2) + 1; | |
global $pgd; | |
if (empty($pgd)) | |
$pgd = 1; | |
if ($pgs == '') { | |
global $wp_query; | |
$pgs = $wp_query->max_num_pgs; | |
if (!$pgs) { | |
$pgs = 1; | |
} | |
} | |
if (1 != $pgs) { | |
// echo the HTML output | |
echo "<div class='wp_paginate'>"; | |
if ($pgd > 2 && $pgd > $rng + 1 && $itm < $pgs) | |
echo "<a href='" . get_pagenum_link(1) . "'>«</a>"; | |
if ($pgd > 1 && $itm < $pgs) | |
echo "<a href='" . get_pagenum_link($pgd - 1) . "'>‹</a>"; | |
for ($i = 1; $i <= $pgs; $i++) { | |
if (1 != $pgs && (!($i >= $pgd + $rng + 1 || $i <= $pgd - $rng - 1) || $pgs <= $itm)) { | |
echo ($pgd == $i) ? "<span class='current'>" . $i . "</span>" : "<a href='" . get_pagenum_link($i) . "' class='inactive' >" . $i . "</a>"; | |
} | |
} | |
if ($pgd < $pgs && $itm < $pgs) | |
echo "<a href='" . get_pagenum_link($pgd + 1) . "'>›</a>"; | |
if ($pgd < $pgs - 1 && $pgd + $rng - 1 < $pgs && $itm < $pgs) | |
echo "<a href='" . get_pagenum_link($pgs) . "'>»</a>"; | |
echo "</div>\n"; | |
} | |
} | |
?> | |
Find a file (including subdirectory search) | |
URL: http://www.visionhive.com | |
This function searches the current working directory (or any other directory path that you specify with parameter $p) for a file, named $f, and returns the full path and filename of the first occurrence, or false if it is either not found or the maximum number of comparisons is reached. The return value is relative to the executing script, so you can safely pass this function to other file-handling functions, e.g. fopen(FFIND("my.file")); or file(FFIND("my.file")); | |
function FFIND($f,$p=null,$l=1000) | |
{ // Recursively find a file $f in directory $p (compare up to $l files) | |
// Returns the full path of the first occurrence (relative to current directory) | |
// (c) Peter Mugane Kionga-Kamau http://www.visionhive.com | |
// Free for unrestricted use with this notice and description unaltered. | |
$cd=$p==null?getcwd():$p; | |
if(substr($cd,-1,1)!="/")$cd.="/"; | |
if(is_dir($cd)) | |
{ | |
$dh=opendir($cd); | |
while($fn=readdir($dh)) | |
{ // traverse directories and compare files: | |
if(is_file($cd.$fn)&&$fn==$f){closedir($dh);return $cd.$fn;} | |
if($fn!="."&&$fn!=".."&&is_dir($cd.$fn)){$m=ffind($f,$cd.$fn,$l);if($m){closedir($dh);return $m;}} | |
} | |
closedir($dh); | |
} | |
return false; | |
} | |
Copyright Display | |
URL: http://www.evinw.com | |
Display Copyright | |
<?php | |
/* | |
|--------------------------- | |
| Author: Evin Weissenberg | |
|--------------------------- | |
*/ | |
class Copyright_Display { | |
private $company_name; | |
private $utf8; | |
function __constructor() { | |
$this->utf8 = ini_set('default_charset', 'UTF-8'); | |
} | |
function setCompanyName($company_name) { | |
$this->company_name = (string)$company_name; | |
return $this; | |
} | |
function __get($property) { | |
return $this->$property; | |
} | |
function render() { | |
$copyright = "Copyright © " . date('Y') . " " . $this->company_name; | |
return $copyright; | |
} | |
function __destructor() { | |
unset($this->utf8); | |
} | |
} | |
$c = new Copyright_Display(); | |
$c->setCompanyName('ACME LLC')->render(); | |
Crop Image and Display it using PHP | |
Displays a selected area of the image. In this example provided, it picks up from the upper left 100px x 100px | |
$filename= "my_picture.jpg"; | |
list($w, $h, $type, $attr) = getimagesize($filename); | |
$src_im = imagecreatefromjpeg($filename); | |
$src_x = '0'; // begin x | |
$src_y = '0'; // begin y | |
$src_w = '100'; // width | |
$src_h = '100'; // height | |
$dst_x = '0'; // destination x | |
$dst_y = '0'; // destination y | |
$dst_im = imagecreatetruecolor($src_w, $src_h); | |
$white = imagecolorallocate($dst_im, 255, 255, 255); | |
imagefill($dst_im, 0, 0, $white); | |
imagecopy($dst_im, $src_im, $dst_x, $dst_y, $src_x, $src_y, $src_w, $src_h); | |
header("Content-type: image/png"); | |
imagepng($dst_im); | |
imagedestroy($dst_im); | |
JSON Responder | |
URL: http://www.evinw.com | |
This response in JSON format with an ability to indicate type,code, message and if there is data, with data. | |
<?php | |
/* | |
|--------------------------- | |
| Author: Evin Weissenberg | |
|--------------------------- | |
*/ | |
class JSON_Responder { | |
private $code; | |
private $type = 1; //1 Error, 2 Success, 3 Informative. | |
private $message; | |
private $data; | |
const MESSAGE_TYPE_ERROR = 'Error'; | |
const MESSAGE_TYPE_SUCCESS = 'Success'; | |
const MESSAGE_TYPE_INFO = 'Informative'; | |
function setCode($code) { | |
$this->code = (string)$code; | |
return $this; | |
} | |
function setMessage($message) { | |
$this->message = (string)$message; | |
return $this; | |
} | |
function setData($date) { | |
$this->data = (array)$date; | |
return $this; | |
} | |
function setType($type) { | |
$this->type = (int)$type; | |
try { | |
if ($this->type == 1) { | |
$this->type = self::MESSAGE_TYPE_ERROR; | |
} elseif ($this->type == 2) { | |
$this->type = self::MESSAGE_TYPE_SUCCESS; | |
} elseif ($this->type == 3) { | |
$this->type = self::MESSAGE_TYPE_INFO; | |
} else { | |
throw new Exception('Type must be options 1,2 or 3'); | |
} | |
} catch (Exception $e) { | |
echo $e->getMessage(); | |
} | |
return $this; | |
} | |
function __get($property) { | |
return $this->$property; | |
} | |
function respond() { | |
try { | |
if ($this->type == null) { | |
throw new Exception('Property type is null.'); | |
} elseif ($this->code == null) { | |
throw new Exception('Property code is null.'); | |
} | |
elseif ($this->message) { | |
throw new Exception('Property message is null.'); | |
} else { | |
if ($this->data != NULL) { | |
// If there is data in the response this pattern will be used. | |
$response = array( | |
"Type" => $this->type, | |
"Code" => $this->code, | |
"Message" => $this->message, | |
"Data" => $this->data); | |
$response_json = json_encode($response); | |
return $response_json; | |
} else { | |
// If there is no data in the response this pattern will be used. | |
$response = array( | |
"Type" => $this->type, | |
"Code" => $this->code, | |
"Message" => $this->message); | |
$response_json = json_encode($response); | |
return $response_json; | |
} | |
} | |
} catch (Exception $e) { | |
echo $e->getMessage(); | |
echo $e->getTrace(); | |
} | |
} | |
} | |
//Usage | |
$j = new JSON_Responder(); | |
$j->setType(1)->setCode('304')->setMessage('Failed')->respond(); | |
Database Connection | |
URL: http://www.evinw.com | |
Allows you to connect to different datasources. Very common to use something like this for development,staging and production deployments. | |
<?php | |
/* | |
|--------------------------- | |
| Author: Evin Weissenberg | |
|--------------------------- | |
*/ | |
class Connection { | |
public static $db = '1'; // 1=production, 2=staging, 3=development. | |
//PRODUCTION | |
public static $host_1 = ''; | |
public static $username_1 = ''; | |
public static $password_1 = ''; | |
public static $db_name_1 = ''; | |
public static $port_1 = ''; | |
//STAGING | |
public static $host_2 = ''; | |
public static $username_2 = ''; | |
public static $password_2 = ''; | |
public static $db_name_2 = ''; | |
public static $port_2 = ''; | |
//DEVELOPMENT | |
public static $host_3 = 'localhost'; | |
public static $username_3 = 'root'; | |
public static $password_3 = 'password'; | |
public static $db_name_3 = 'my_database'; | |
public static $port_3 = '3306'; | |
public static function dbConnection() { | |
if (self::$db == 1) { | |
mysql_connect(self::$host_1, self::$username_1, self::$password_1) or die(mysql_error()); | |
mysql_select_db(self::$db_name_1) or die(mysql_error()); | |
return true; | |
} elseif (self::$db == 2) { | |
mysql_connect(self::$host_2, self::$username_2, self::$password_2) or die(mysql_error()); | |
mysql_select_db(self::$db_name_2) or die(mysql_error()); | |
return true; | |
} elseif (self::$db == 3) { | |
mysql_connect(self::$host_3, self::$username_3, self::$password_3) or die(mysql_error()); | |
mysql_select_db(self::$db_name_3) or die(mysql_error()); | |
return true; | |
} else { | |
return false; | |
} | |
} | |
} | |
//Usage | |
Connection::$db=3; | |
Connection::dbConnection(); | |
Debugging $_REQUEST | |
<div style="position:fixed; top:0; left: 0; width: 400px; background: rgb(0,0,0,0); background: rgba(0,0,0,0.8); color: green; margin:0px; padding:5px; max-height: 90%; overflow-y:auto;"> | |
<h2 style="margin:0px;color:white;">$ HEADERS:</h2> | |
<h3 style="margin:5px;color:white;">GET</h3> | |
<?php | |
//var_dump($_GET); | |
foreach($_GET as $name=>$value) { | |
echo $name." => "; | |
echo $value."<br />"; | |
} | |
?> | |
<h3 style="margin:5px;color:white;">POST</h3> | |
<?php | |
//var_dump($_POST); | |
foreach($_POST as $name=>$value) { | |
echo $name." => "; | |
echo $value."<br />"; | |
} | |
?></div> | |
Detect Location by IP | |
Returns "City, State" if found otherwise the default set at the top. | |
function detect_city($ip) { | |
$default = 'UNKNOWN'; | |
if (!is_string($ip) || strlen($ip) < 1 || $ip == '127.0.0.1' || $ip == 'localhost') | |
$ip = '8.8.8.8'; | |
$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; | |
} | |
} | |
Get Geo-IP Information | |
Requests a geo-IP-server to check, returns where an IP is located (host, state, country, town). | |
<?php | |
$ip='94.219.40.96'; | |
print_r(geoCheckIP($ip)); | |
//Array ( [domain] => dslb-094-219-040-096.pools.arcor-ip.net [country] => DE - Germany [state] => Hessen [town] => Erzhausen ) | |
//Get an array with geoip-infodata | |
function geoCheckIP($ip) | |
{ | |
//check, if the provided ip is valid | |
if(!filter_var($ip, FILTER_VALIDATE_IP)) | |
{ | |
throw new InvalidArgumentException("IP is not valid"); | |
} | |
//contact ip-server | |
$response=@file_get_contents('http://www.netip.de/search?query='.$ip); | |
if (empty($response)) | |
{ | |
throw new InvalidArgumentException("Error contacting Geo-IP-Server"); | |
} | |
//Array containing all regex-patterns necessary to extract ip-geoinfo from page | |
$patterns=array(); | |
$patterns["domain"] = '#Domain: (.*?) #i'; | |
$patterns["country"] = '#Country: (.*?) #i'; | |
$patterns["state"] = '#State/Region: (.*?)<br#i'; | |
$patterns["town"] = '#City: (.*?)<br#i'; | |
//Array where results will be stored | |
$ipInfo=array(); | |
//check response from ipserver for above patterns | |
foreach ($patterns as $key => $pattern) | |
{ | |
//store the result in array | |
$ipInfo[$key] = preg_match($pattern,$response,$value) && !empty($value[1]) ? $value[1] : 'not found'; | |
} | |
return $ipInfo; | |
} | |
?> | |
http://css-tricks.com/snippets/php/error-page-to-handle-all-errors/ | |
Get Current File Name | |
<?php | |
$pageName = basename($_SERVER['PHP_SELF']); | |
?> | |
Get Current Page URL | |
function getUrl() { | |
$url = @( $_SERVER["HTTPS"] != 'on' ) ? 'http://'.$_SERVER["SERVER_NAME"] : 'https://'.$_SERVER["SERVER_NAME"]; | |
$url .= ( $_SERVER["SERVER_PORT"] !== 80 ) ? ":".$_SERVER["SERVER_PORT"] : ""; | |
$url .= $_SERVER["REQUEST_URI"]; | |
return $url; | |
} | |
Get File Last Updated Date | |
/* | |
* @param string $file Filepath | |
* @param string $format dateformat | |
* @link http://www.php.net/manual/de/function.date.php | |
* @link http://www.php.net/manual/de/function.filemtime.php | |
* @return string|bool Date or Boolean | |
*/ | |
function getFiledate($file, $format) { | |
if (is_file($file)) { | |
$filePath = $file; | |
if (!realpath($filePath)) { | |
$filePath = $_SERVER["DOCUMENT_ROOT"].$filePath; | |
} | |
$fileDate = filemtime($filePath); | |
if ($fileDate) { | |
$fileDate = date("$format",$fileDate); | |
return $fileDate; | |
} | |
return false; | |
} | |
return false; | |
} | |
HTML Tidy | |
function html_tidy( $input_html, $indent = "true", $no_body_tags = "true", $fix = "true" ) { | |
ob_start( ); | |
$tidy = new tidy; | |
$config = array( 'indent' => $indent, 'output-xhtml' => true, 'wrap' => 200, 'clean' => $fix, 'show-body-only' => $no_body_tags ); | |
$tidy->parseString( $input_html, $config, 'utf8' ); | |
$tidy->cleanRepair( ); | |
$input = $tidy; | |
return $input; | |
} | |
Add Facebook Login to Your Website | |
Launch Facebook oAuth Box | |
<?php | |
$stoken = Util::getMD5GUID(); | |
$gWeb->store("fb_state",$stoken); | |
$fbAppId = Config::getInstance()->get_value("facebook.app.id"); | |
$host = "http://".$_SERVER["HTTP_HOST"]; | |
$fbCallback = $host."/callback/fb2.php" ; | |
$fbDialogUrl = "https://www.facebook.com/dialog/oauth?client_id=".$fbAppId ; | |
$fbDialogUrl .= "&redirect_uri=".urlencode($fbCallback)."&scope=email&state=".$stoken ; | |
?> | |
<a href="<?php echo $fbDialogUrl; ?>"> Login with Facebook</a> | |
Example of error handler | |
function login_error_handler($errorno,$errorstr,$file,$line) { | |
if(error_reporting() == 0 ) { | |
// do nothing for silenced errors | |
return true ; | |
} | |
switch($errorno) { | |
case E_STRICT : | |
return true; | |
case E_NOTICE : | |
case E_USER_NOTICE : | |
Logger->error(" $file :: $line :: $errorstr"); | |
break ; | |
case E_USER_ERROR: | |
Logger->trace($file,$line,$errorstr,'TRACE'); | |
$_SESSION["form.errors"] = array($errorstr); | |
header('Location: /user/login.php'); | |
exit(1); | |
default: | |
Logger->trace($file,$line,$errorstr,'TRACE'); | |
$_SESSION["form.errors"] = array("Error happened during login"); | |
header('Location: /user/login.php'); | |
exit(1); | |
} | |
//do not execute PHP error handler | |
return true ; | |
} | |
Code for error check and user data | |
include ($_SERVER['APP_WEB_DIR'].'/callback/error.inc'); | |
set_error_handler('login_error_handler'); | |
$fbAppId = Config::getInstance()->get_value("facebook.app.id"); | |
$fbAppSecret = Config::getInstance()->get_value("facebook.app.secret"); | |
$host = "http://".$_SERVER["HTTP_HOST"]; | |
$fbCallback = $host. "/callback/fb2.php"; | |
$code = NULL; | |
if(array_key_exists('code',$_REQUEST)) { | |
$code = $_REQUEST["code"]; | |
} | |
$error = NULL ; | |
if(array_key_exists('error',$_REQUEST)) { | |
$error = $_REQUEST['error'] ; | |
$description = $_REQUEST['error_description'] ; | |
$message = sprintf(" Facebook returned error :: %s :: %s ",$error,$description); | |
trigger_error($message,E_USER_ERROR); | |
exit ; | |
} | |
if(empty($code) && empty($error)) { | |
//see how to launch an FB dialog again on Facebook URL given above | |
} | |
//last state token | |
$stoken = $gWeb->find('fb_state',true); | |
if(!empty($code) && ($_REQUEST['state'] == $stoken)) { | |
//request to get access token | |
$fbTokenUrl = "https://graph.facebook.com/oauth/access_token?client_id=".$fbAppId ; | |
$fbTokenUrl .= "&redirect_uri=" . urlencode($fbCallback). "&client_secret=" . $fbAppSecret ; | |
$fbTokenUrl .= "&code=" . $code; | |
$response = file_get_contents($fbTokenUrl); | |
$params = null; | |
parse_str($response, $params); | |
$graph_url = "https://graph.facebook.com/me?access_token=".$params['access_token']; | |
$user = json_decode(file_get_contents($graph_url)); | |
processUser($user); | |
} | |
else { | |
$message = "http://www.bestfishingrodsreview.com and Facebook state mismatch"; | |
trigger_error($message,E_USER_ERROR); | |
} | |
Code to process User Info | |
function processUser($user) { | |
$id = $user->id; | |
$name = $user->name; | |
$firstName = $user->first_name ; | |
$lastName = $user->last_name ; | |
$link = $user->link ; | |
$gender = $user->gender ; | |
$email = $user->email ; | |
if(empty($name) && empty($firstName)) { | |
$name = "Anonymous" ; | |
} | |
$message = sprintf("Login:Facebook :: id %d ,email %s \n",$id,$email); | |
Logger::getInstance()->info($message); | |
$facebookDao = new \com\indigloo\sc\dao\Facebook(); | |
$loginId = $facebookDao->getOrCreate($id,$name,$firstName,$lastName,$link,$gender,$email); | |
if(empty($loginId)) { | |
trigger_error("Unable to create login",E_USER_ERROR); | |
} | |
\com\indigloo\sc\auth\Login::startFacebookSession($loginId,$name); | |
header("Location: / "); | |
} | |
jQuery Loading Fallback | |
<!-- Grab Google CDN's jQuery and load local version if necessary --> | |
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script> | |
<script type="text/javascript">!window.jQuery && document.write('<script src="js/jquery-1.4.2.min.js"><\/script>')</script> | |
Destroy Cookie while Logging out. | |
@RequestMapping(value = "/logout", method = RequestMethod.POST) | |
public void logout(HttpServletRequest request, | |
HttpServletResponse response) { | |
/* Getting session and then invalidating it */ | |
HttpSession session = request.getSession(false); | |
if (request.isRequestedSessionIdValid() && session != null) { | |
session.invalidate(); | |
} | |
handleLogOutResponse(response); | |
} | |
/** | |
* This method would edit the cookie information and make JSESSIONID empty | |
* while responding to logout. This would further help in order to. This would help | |
* to avoid same cookie ID each time a person logs in | |
* @param response | |
*/ | |
private void handleLogOutResponse(HttpServletResponse response) { | |
Cookie[] cookies = request.getCookies(); | |
for (Cookie cookie : cookies) { | |
cookie.setMaxAge(0); | |
cookie.setValue(null); | |
cookie.setPath("/"); | |
response.addCookie(cookie); | |
} | |
} | |
Creating simple HTML5 slide presentation with impress.js | |
<html lang="en"> | |
<head> | |
<title>Impress Demo</title> | |
</head> | |
<body> | |
<div id="impress"> | |
<div class="step slide" id="start"> | |
<p style='width:1000px;font-size:80px; | |
text-align:center'>Creating Stunning Visualizations</p> | |
<p>Impress.js </p> | |
</div> | |
<div class="step slide" id="slide2" data-x="-1200" data-y="0"> | |
<p style='width:1000px;font-size:80px;'> | |
First Slide Moves From Left To Right</p> | |
<p>Impress.js </p> | |
</div> | |
</div> | |
<script type="text/javascript" src="js/impress.js"></script> | |
<script type="text/javascript">impress().init();</script> | |
</body> | |
</html> | |
With the recent growth of HTML5 adaption, I have seen many people using HTML slides instead of traditional Power Point/Open Office presentation. | |
You can download the impress.js and save in the “js” directory. | |
https://github.com/bartaz/impress.js/blob/master/js/impress.js | |
Extract Youtube Video ID from URL | |
/* Source : http://stackoverflow.com/questions/3452546/javascript-regex-how-to-get-youtube-video-id-from-url */ | |
var regExp = /^.*(youtu.be\/|v\/|u\/\w\/|embed\/|watch\?v=)([^#\&\?]*).*/; | |
var match = url.match(regExp); | |
if (match&&match[2].length==11){ | |
return match[2]; | |
}else{ | |
//error | |
} | |
Save any image from url using php | |
<?php | |
$im=imagecreatefromjpeg('http://images.websnapr.com/?size=size&key=Y64Q44QLt12u&url=http://google.com'); | |
header('Content-type:image/jpeg'); | |
imagejpeg($im); | |
?> | |
Back up Mysql database via PHP | |
<?php | |
##################### | |
//CONFIGURATIONS | |
##################### | |
// Define the name of the backup directory | |
define('BACKUP_DIR', './myBackups' ) ; | |
// Define Database Credentials | |
define('HOST', 'localhost' ) ; | |
define('USER', 'testd!b' ) ; | |
define('PASSWORD', 'k^$2y4n9@#VV' ) ; | |
define('DB_NAME', 'test123' ) ; | |
/* | |
Define the filename for the sql file | |
If you plan to upload the file to Amazon's S3 service , use only lower-case letters | |
*/ | |
$fileName = 'mysqlbackup--' . date('d-m-Y') . '@'.date('h.i.s').'.sql' ; | |
// Set execution time limit | |
if(function_exists('max_execution_time')) { | |
if( ini_get('max_execution_time') > 0 ) set_time_limit(0) ; | |
} | |
########################### | |
//END OF CONFIGURATIONS | |
########################### | |
// Check if directory is already created and has the proper permissions | |
if (!file_exists(BACKUP_DIR)) mkdir(BACKUP_DIR , 0700) ; | |
if (!is_writable(BACKUP_DIR)) chmod(BACKUP_DIR , 0700) ; | |
// Create an ".htaccess" file , it will restrict direct accss to the backup-directory . | |
$content = 'deny from all' ; | |
$file = new SplFileObject(BACKUP_DIR . '/.htaccess', "w") ; | |
$file->fwrite($content) ; | |
$mysqli = new mysqli(HOST , USER , PASSWORD , DB_NAME) ; | |
if (mysqli_connect_errno()) | |
{ | |
printf("Connect failed: %s", mysqli_connect_error()); | |
exit(); | |
} | |
// Introduction information | |
$return .= "--\n"; | |
$return .= "-- A Mysql Backup System \n"; | |
$return .= "--\n"; | |
$return .= '-- Export created: ' . date("Y/m/d") . ' on ' . date("h:i") . "\n\n\n"; | |
$return = "--\n"; | |
$return .= "-- Database : " . DB_NAME . "\n"; | |
$return .= "--\n"; | |
$return .= "-- --------------------------------------------------\n"; | |
$return .= "-- ---------------------------------------------------\n"; | |
$return .= 'SET AUTOCOMMIT = 0 ;' ."\n" ; | |
$return .= 'SET FOREIGN_KEY_CHECKS=0 ;' ."\n" ; | |
$tables = array() ; | |
// Exploring what tables this database has | |
$result = $mysqli->query('SHOW TABLES' ) ; | |
// Cycle through "$result" and put content into an array | |
while ($row = $result->fetch_row()) | |
{ | |
$tables[] = $row[0] ; | |
} | |
// Cycle through each table | |
foreach($tables as $table) | |
{ | |
// Get content of each table | |
$result = $mysqli->query('SELECT * FROM '. $table) ; | |
// Get number of fields (columns) of each table | |
$num_fields = $mysqli->field_count ; | |
// Add table information | |
$return .= "--\n" ; | |
$return .= '-- Tabel structure for table `' . $table . '`' . "\n" ; | |
$return .= "--\n" ; | |
$return.= 'DROP TABLE IF EXISTS `'.$table.'`;' . "\n" ; | |
// Get the table-shema | |
$shema = $mysqli->query('SHOW CREATE TABLE '.$table) ; | |
// Extract table shema | |
$tableshema = $shema->fetch_row() ; | |
// Append table-shema into code | |
$return.= $tableshema[1].";" . "\n\n" ; | |
// Cycle through each table-row | |
while($rowdata = $result->fetch_row()) | |
{ | |
// Prepare code that will insert data into table | |
$return .= 'INSERT INTO `'.$table .'` VALUES ( ' ; | |
// Extract data of each row | |
for($i=0; $i<$num_fields; $i++) | |
{ | |
$return .= '"'.$rowdata[$i] . "\"," ; | |
} | |
// Let's remove the last comma | |
$return = substr("$return", 0, -1) ; | |
$return .= ");" ."\n" ; | |
} | |
$return .= "\n\n" ; | |
} | |
// Close the connection | |
$mysqli->close() ; | |
$return .= 'SET FOREIGN_KEY_CHECKS = 1 ; ' . "\n" ; | |
$return .= 'COMMIT ; ' . "\n" ; | |
$return .= 'SET AUTOCOMMIT = 1 ; ' . "\n" ; | |
//$file = file_put_contents($fileName , $return) ; | |
$zip = new ZipArchive() ; | |
$resOpen = $zip->open(BACKUP_DIR . '/' .$fileName.".zip" , ZIPARCHIVE::CREATE) ; | |
if( $resOpen ){ | |
$zip->addFromString( $fileName , "$return" ) ; | |
} | |
$zip->close() ; | |
$fileSize = get_file_size_unit(filesize(BACKUP_DIR . "/". $fileName . '.zip')) ; | |
$message = <<<msg | |
<h2>BACKUP completed ,</h2> | |
the archive has the name of : <b> $fileName </b> and it's file-size is : $fileSize . | |
This zip archive can't be accessed via a web browser , as it's stored into a protected directory . | |
It's highly recomended to transfer this backup to another filesystem , use your favorite FTP client to download the archieve . | |
msg; | |
echo $message ; | |
// Function to append proper Unit after file-size . | |
function get_file_size_unit($file_size){ | |
switch (true) { | |
case ($file_size/1024 < 1) : | |
return intval($file_size ) ." Bytes" ; | |
break; | |
case ($file_size/1024 >= 1 && $file_size/(1024*1024) < 1) : | |
return intval($file_size/1024) ." KB" ; | |
break; | |
default: | |
return intval($file_size/(1024*1024)) ." MB" ; | |
} | |
} | |
List Directory Contents in PHP | |
<?php | |
/* Source: http://www.apphp.com/index.php?snippet=php-list-directory-contents */ | |
function list_directory_content($dir){ | |
if(is_dir($dir)){ | |
if($handle = opendir($dir)){ | |
while(($file = readdir($handle)) !== false){ | |
if($file != '.' && $file != '..' && $file != '.htaccess'){ | |
echo '<a target="_blank" href="'.$dir.$file.'">'.$file.'</a> | |
'."\n"; | |
} | |
} | |
closedir($handle); | |
} | |
} | |
} | |
?> | |
getJSON on Drop Down Change Event | |
function populateDropDown() { | |
$.getJSON('/getData.aspx', { Name:$('#parm').val()}, function(data) { | |
var select = $('#DDLControl'); | |
var options = select.attr('options'); | |
$('option', select).remove(); | |
$.each(data, function(index, array) { | |
options[options.length] = new Option(array['variety']); | |
}); | |
}); | |
} | |
$(document).ready(function() { | |
populateDropDown(); | |
$('#DDLchangeData').change(function() { | |
populateDropDown(); | |
}); | |
}); | |
Find Duplicate records in SQL table | |
Suppose our tablename is masterorder with column orderid for which we are goin to find duplicate records. | |
SELECT orderid, COUNT(*) TotalCount | |
FROM masterorder | |
GROUP BY orderid | |
HAVING COUNT(*) > 1 | |
Get URL Parameters | |
function getURLParameter(name){ | |
return decodeURI( | |
(RegEXP(name + '=' + '(.+?)(&|$)').exec(location.search)||[,null])[1] | |
); | |
} | |
Re-create Array Index | |
If you want to re-index starting to zero, simply do the following: | |
$iZero = array_values($arr); | |
If you need it to start at one, then use the following: | |
$iOne = array_combine(range(1, count($arr)), array_values($arr)); | |
Here are the manual pages for the functions used: | |
array_values() | |
array_combine() | |
range() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment