- Sep 10, 2010
- 11,807
- 26,660
Hi all!
I made this thread for the PHP coders. I will keep updating this thread with code snippets that do various jobs. I have collected these snippets from various sources and use them for my own projects. You can make utility classes to use them, or can simple use this in your project as functions. So let me begin by sharing these:
P.S. If you need to do some task and searching for a snippet, then post here. I will provide you with one
Encryption Decryption function for security:
Make random Strings of specified length
Make seo friendly slug like Wordpress, from any string
Write text over image, with Border (imagettftext alternative)(needs GD library enabled):
Easy Object to Array transformation:
String to boolean (try to guess if a word means yes or no)
Quick Debug function:
Get the sum of numbers passed into a function
Check if current url has https
Validate any youtube url
True email validation in PHP
Import and display Tweets through PHP
Echo multiple strings in new lines
Check if a string is utf
Check if data is serialized
"x" "time" ago - Return twitter / facebook like time difference of a post
Prevent caching of a page by calling this function
Get gravatar url of an email
Updates coming soon....
I made this thread for the PHP coders. I will keep updating this thread with code snippets that do various jobs. I have collected these snippets from various sources and use them for my own projects. You can make utility classes to use them, or can simple use this in your project as functions. So let me begin by sharing these:
P.S. If you need to do some task and searching for a snippet, then post here. I will provide you with one
Encryption Decryption function for security:
Code:
function encrypt($decrypted, $password = 'dasdasdasdasd', $salt = '!kQm*fdasdssdasda28932893s9d9sdm%9') {
// Build a 256-bit $key which is a SHA256 hash of $salt and $password.
$key = hash('SHA256', $salt . $password, true);
// Build $iv and $iv_base64. We use a block size of 128 bits (AES compliant) and CBC mode. (Note: ECB mode is inadequate as IV is not used.)
srand();
$iv = mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC), MCRYPT_RAND);
if (strlen($iv_base64 = rtrim(base64_encode($iv), '=')) != 22)
return false;
// Encrypt $decrypted and an MD5 of $decrypted using $key. MD5 is fine to use here because it's just to verify successful decryption.
$encrypted = base64_encode(@mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $decrypted . md5($decrypted), MCRYPT_MODE_CBC, $iv));
// We're done!
$iv = base64_encode($iv_base64 . $encrypted);
return $iv;
}
function decrypt($encrypted, $password = 'dasdasdasdasd', $salt = '!kQm*fdasdssdasda28932893s9d9sdm%9') {
// Build a 256-bit $key which is a SHA256 hash of $salt and $password.
$encrypted = base64_decode($encrypted);
$key = hash('SHA256', $salt . $password, true);
// Retrieve $iv which is the first 22 characters plus ==, base64_decoded.
$iv = base64_decode(substr($encrypted, 0, 22) . '==');
// Remove $iv from $encrypted.
$encrypted = substr($encrypted, 22);
// Decrypt the data. rtrim won't corrupt the data because the last 32 characters are the md5 hash; thus any \0 character has to be padding.
$decrypted = rtrim(@mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key, base64_decode($encrypted), MCRYPT_MODE_CBC, $iv), "\0\4");
// Retrieve $hash which is the last 32 characters of $decrypted.
$hash = substr($decrypted, -32);
// Remove the last 32 characters from $decrypted.
$decrypted = substr($decrypted, 0, -32);
// Integrity check. If this fails, either the data is corrupted, or the password/salt was incorrect.
if (md5($decrypted) != $hash)
return false;
// Yay!
return $decrypted;
}
Make random Strings of specified length
Code:
function randomString($max = 10) {
$i = 0; //Reset the counter.
$possible_keys = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
$keys_length = strlen($possible_keys);
$str = ""; //Let's declare the string, to add later.
while ($i < $max) {
$rand = mt_rand(1, $keys_length - 1);
$str.= $possible_keys[$rand];
$i++;
}
return $str;
}
Make seo friendly slug like Wordpress, from any string
Code:
function sluggify($string) {
$slug = preg_replace('/[^A-Za-z0-9-]+/', '-', $string);
return trim($slug , '-');
}
Write text over image, with Border (imagettftext alternative)(needs GD library enabled):
Code:
function imagettfborder($im, $size, $angle, $x, $y, $color,$color1, $font, $text, $width) {
// top
imagettftext($im, $size, $angle, $x-$width, $y-$width, $color1, $font, $text);
imagettftext($im, $size, $angle, $x, $y-$width, $color1, $font, $text);
imagettftext($im, $size, $angle, $x+$width, $y-$width, $color1, $font, $text);
// bottom
imagettftext($im, $size, $angle, $x-$width, $y+$width, $color1, $font, $text);
imagettftext($im, $size, $angle, $x, $y+$width, $color1, $font, $text);
imagettftext($im, $size, $angle, $x-$width, $y+$width, $color, $font, $text);
// left
imagettftext($im, $size, $angle, $x-$width, $y, $color1, $font, $text);
// right
imagettftext($im, $size, $angle, $x+$width, $y, $color, $font, $text);
for ($i = 1; $i < $width; $i++) {
// top line
imagettftext($im, $size, $angle, $x-$i, $y-$width, $color1, $font, $text);
imagettftext($im, $size, $angle, $x+$i, $y-$width, $color, $font, $text);
// bottom line
imagettftext($im, $size, $angle, $x-$i, $y+$width, $color1, $font, $text);
imagettftext($im, $size, $angle, $x+$i, $y+$width, $color, $font, $text);
// left line
imagettftext($im, $size, $angle, $x-$width, $y-$i, $color1, $font, $text);
imagettftext($im, $size, $angle, $x-$width, $y+$i, $color, $font, $text);
// right line
imagettftext($im, $size, $angle, $x+$width, $y-$i, $color1, $font, $text);
imagettftext($im, $size, $angle, $x+$width, $y+$i, $color, $font, $text);
}
}
Easy Object to Array transformation:
Code:
function obj2arr($obj = null)
{
if($obj === null)
return false;
$temp = json_encode($obj);
return json_decode($temp , true);
}
String to boolean (try to guess if a word means yes or no)
Code:
function str_to_bool( $string, $default = FALSE )
{
$yes_words = 'affirmative|all right|aye|indubitably|most assuredly|ok|of course|okay|sure thing|y|yes+|yea|yep|sure|yeah|true|t|on|1';
$no_words = 'no*|no way|nope|nah|na|never|absolutely not|by no means|negative|never ever|false|f|off|0';
if ( preg_match( '/^(' . $yes_words . ')$/i', $string ) ) {
return TRUE;
} else if ( preg_match( '/^(' . $no_words . ')$/i', $string ) ) {
return FALSE;
} else {
return $default;
}
}
Quick Debug function:
Code:
function debug($input , $stopCodeExecution = false)
{
echo '<pre>';
var_dump($input);
echo '</pre>';
if($stopCodeExecution)
exit();
}
Get the sum of numbers passed into a function
Code:
function Summit() {
$sum = 0;
foreach (func_get_args() as $arg) {
$sum += $arg;
}
return $sum;
}
use it e.g.:
$result = Summit(1,13,3.4,58000,45 );
Check if current url has https
Code:
function is_https()
{
if ( isset( $_SERVER['HTTPS'] ) && ! empty( $_SERVER['HTTPS'] ) && $_SERVER['HTTPS'] != 'off' ) {
return TRUE;
} else {
return FALSE;
}
}
Validate any youtube url
Code:
class Youtube {
///// Put together by Sugato
////////// $video_id is the youtube video ID /////////////////////////
public $video_id = null;
///////// the Constructer ////////////////////////////////////////
public function __construct($url)
{
if (preg_match('/youtube\.com\/watch\?v=([^\&\?\/]+)/', $url, $id)) {
$this->video_id = $id[1];
} else if (preg_match('/youtube\.com\/embed\/([^\&\?\/]+)/', $url, $id)) {
$this->video_id = $id[1];
} else if (preg_match('/youtube\.com\/v\/([^\&\?\/]+)/', $url, $id)) {
$this->video_id = $id[1];
} else if (preg_match('/youtu\.be\/([^\&\?\/]+)/', $url, $id)) {
$this->video_id = $id[1];
} else {
$this->video_id = NULL;
}
}
/////////// validates if a youtube video actually exists //////////////
function validate()
{
if(empty($this->video_id))
{
return false;
}
else {
$curl = curl_init("http://gdata.youtube.com/feeds/api/videos/" . $this->video_id);
curl_setopt($curl, CURLOPT_HEADER, true);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_exec($curl);
$request = curl_getinfo($curl);
curl_close($curl);
$result = explode(";", $request["content_type"]);
if($result[0] == "application/atom+xml")
{
return true;
} else {
return false;
}
}
}
}
Call it like:
$yt = new Youtube($your_video_link_here);
$exist = $yt->validate();
if($exist)
{
echo "Yaaaayyyyyy!";
} else
{
echo "nAAAAyyyy!!!";
}
True email validation in PHP
Code:
function CheckAndValidateEmail($mail) {
if (filter_var($mail, FILTER_VALIDATE_EMAIL)) {
// ok
list($user, $domaine) = split("@", $mail, 2);
if (!checkdnsrr($domaine, "MX") && !checkdnsrr($domaine, "A")) {
return false;
} else {
return true;
}
} else {
//no
return false;
}
}
Import and display Tweets through PHP
Code:
function twitter_feed($username) {
$feed_url = "http://search.twitter.com/search.atom?q=from:".$username."&rpp=2";
$feed = file_get_contents($feed_url);
$stepOne = explode('<content type="html">', $feed);
$stepTwo = explode('</content>', $stepOne[1]);
$tweet = $stepTwo[0];
$tweet = str_replace("<", "<", $tweet);
$tweet = str_replace(">", ">", $tweet);
return $tweet;
}
echo twitter_feed('lolmyball');
Echo multiple strings in new lines
Code:
function multiecho() {
$args = func_get_args();
foreach ($args as $k => $v) {
echo "$v\r\n";
}
}
call it like:
multiecho("I am" , "a" , "program");
multiecho("Bye!");
Check if a string is utf
Code:
function seems_utf8( $string )
{
if ( function_exists( 'mb_check_encoding' ) ) {
// If mbstring is available, this is significantly faster than
// using PHP regexps.
return mb_check_encoding( $string, 'UTF-8' );
}
$regex = '/(
| [\xF8-\xFF] # Invalid UTF-8 Bytes
| [\xC0-\xDF](?![\x80-\xBF]) # Invalid UTF-8 Sequence Start
| [\xE0-\xEF](?![\x80-\xBF]{2}) # Invalid UTF-8 Sequence Start
| [\xF0-\xF7](?![\x80-\xBF]{3}) # Invalid UTF-8 Sequence Start
| (?<=[\x0-\x7F\xF8-\xFF])[\x80-\xBF] # Invalid UTF-8 Sequence Middle
| (?<![\xC0-\xDF]|[\xE0-\xEF]|[\xE0-\xEF][\x80-\xBF]|[\xF0-\xF7]|[\xF0-\xF7][\x80-\xBF]|[\xF0-\xF7][\x80-\xBF]{2})[\x80-\xBF] # Overlong Sequence
| (?<=[\xE0-\xEF])[\x80-\xBF](?![\x80-\xBF]) # Short 3 byte sequence
| (?<=[\xF0-\xF7])[\x80-\xBF](?![\x80-\xBF]{2}) # Short 4 byte sequence
| (?<=[\xF0-\xF7][\x80-\xBF])[\x80-\xBF](?![\x80-\xBF]) # Short 4 byte sequence (2)
)/x';
return ! preg_match( $regex, $string );
}
Check if data is serialized
Code:
function is_serialized( $data )
{
// If it isn't a string, it isn't serialized
if ( ! is_string( $data ) ) {
return FALSE;
}
$data = trim( $data );
if ( 'N;' == $data ) {
return TRUE;
}
$length = strlen( $data );
if ( $length < 4 ) {
return FALSE;
}
if ( ':' !== $data[1] ) {
return FALSE;
}
$lastc = $data[$length - 1];
if ( ';' !== $lastc && '}' !== $lastc ) {
return FALSE;
}
$token = $data[0];
switch ( $token ) {
case 's' :
if ( '"' !== $data[$length-2] ) {
return FALSE;
}
case 'a' :
case 'O' :
return (bool) preg_match( "/^{$token}:[0-9]+:/s", $data );
case 'b' :
case 'i' :
case 'd' :
return (bool) preg_match( "/^{$token}:[0-9.E-]+;\$/", $data );
}
return FALSE;
}
"x" "time" ago - Return twitter / facebook like time difference of a post
Code:
function human_time_diff( $from, $to = '', $as_text = FALSE, $suffix = ' ago' )
{
if ( $to == '' ) {
$to = time();
}
$from = new DateTime( date( 'Y-m-d H:i:s', $from ) );
$to = new DateTime( date( 'Y-m-d H:i:s', $to ) );
$diff = $from->diff( $to );
if ( $diff->y > 1 ) {
$text = $diff->y . ' years';
} else if ( $diff->y == 1 ) {
$text = '1 year';
} else if ( $diff->m > 1 ) {
$text = $diff->m . ' months';
} else if ( $diff->m == 1 ) {
$text = '1 month';
} else if ( $diff->d > 7 ) {
$text = ceil( $diff->d / 7 ) . ' weeks';
} else if ( $diff->d == 7 ) {
$text = '1 week';
} else if ( $diff->d > 1 ) {
$text = $diff->d . ' days';
} else if ( $diff->d == 1 ) {
$text = '1 day';
} else if ( $diff->h > 1 ) {
$text = $diff->h . ' hours';
} else if ( $diff->h == 1 ) {
$text = ' 1 hour';
} else if ( $diff->i > 1 ) {
$text = $diff->i . ' minutes';
} else if ( $diff->i == 1 ) {
$text = '1 minute';
} else if ( $diff->s > 1 ) {
$text = $diff->s . ' seconds';
} else {
$text = '1 second';
}
if ( $as_text ) {
$text = explode( ' ', $text, 2 );
$text = self::number_to_word( $text[0] ) . ' ' . $text[1];
}
return trim( $text ) . $suffix;
}
Prevent caching of a page by calling this function
Code:
function nocache_headers()
{
if ( ! headers_sent() ) {
header( 'Expires: Wed, 11 Jan 1984 05:00:00 GMT' );
header( 'Last-Modified: ' . gmdate( 'D, d M Y H:i:s' ) . ' GMT' );
header( 'Cache-Control: no-cache, must-revalidate, max-age=0' );
header( 'Pragma: no-cache' );
return TRUE;
} else {
return FALSE;
}
}
Get gravatar url of an email
Code:
function get_gravatar( $email, $size = 32 )
{
$url = 'http://www.gravatar.com/';
$url .= 'avatar/' . md5( $email ) . '?s=' . (int) abs( $size );
return $url;
}
Updates coming soon....