Codes & Snippets

I have listed a few of the best code snippets that I have used in yaknivek.

Get a user IP address from behind a proxy

This code I use when i want to upload anything to a database so I can keep a record of who uploaded the image. Just in case there are malicious images' being uploaded.

function GetIP()
{
if (!empty($_SERVER['HTTP_CLIENT_IP'])) //check ip from share internet
{
$IP=$_SERVER['HTTP_CLIENT_IP'];
}
elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) //to check ip is pass from proxy
{
$IP=$_SERVER['HTTP_X_FORWARDED_FOR'];
}
else
{
$ip=$_SERVER['REMOTE_ADDR'];
}
return $IP;
}



Add a Facebook Share button

At first I wasn't going to add a Facebook share button because I thought what was the point. But after realizing that Facebook is were I mainly find out about new image sites as more pictures are being uploaded there daily. This share button is just the share link which I fort was light weight and able to do eveything I needed
<a title="Share this post/page"
href="http://www.facebook.com/sharer.php?
s=100p[url]={URL YOU WANT TO SHARE}
&p[images][0]={IMAGE THUMBNAIL}
&p[title]={TITLE TO DISPLAY}
&p[summary]={A LITTLE DISCRIPTION}"
target=”_blank”>
Share
</a>
You may need to play around with to get it to work.


Take URL out of a string

The reason I use this is mainly to stop people adding hyperlinks into my website eg in titles ect. Allowing links to be inserted could be very bad for the website.
$string = preg_replace('/\b(https?|ftp|file):\/\/
[-A-Z0-9+&@#\/%?=~_|$!:,.;]*[A-Z0-9+&@#\/%=~_|$]/i', '', $string);



Determine the dominant color of an image

This code will be super useful for people managing images or photography website. With it, you can analyze any image and get its dominant color (R, G, or B).
$i = imagecreatefromjpeg("image.jpg");

for ($x=0;$x<imagesx($i);$x++) {
    for ($y=0;$y<imagesy($i);$y++) {
        $rgb = imagecolorat($i,$x,$y);
        $r   = ($rgb >> 16) & 0xFF;
        $g   = ($rgb >>  & 0xFF;
        $b   = $rgb & 0xFF;

        $rTotal += $r;
        $gTotal += $g;
        $bTotal += $b;
        $total++;
    }
}

$rAverage = round($rTotal/$total);
$gAverage = round($gTotal/$total);
$bAverage = round($bTotal/$total);


Watermark images automatically

I first saw this code whilst browsing catswhocode.com
If you’re displaying your own images on your websites, chances are that you don’t want to see them everywhere on the web the next day. To prevent image theft and make sure to be credited as the original creator of the image, watermarking them is generally a good idea. The following function allows you to automatically add a watermark on your images.
//$S_File = the source file
//$WMarkText = the text which your placing on the image
//$D_File = The destination file
//$w = width
//$h = height

function watermarkImage ($S_File, $WMarkText, $D_File)
 { 
   list($w, $h) = getimagesize($S_File);
   $img_p = imagecreatetruecolor($wth, $height);
   $img = imagecreatefromjpeg($S_File);
   imagecopyresampled($img_p, $img, 0, 0, 0, 0, $w, $h, $w, $h); 
   $b = imagecolorallocate($img_p, 0, 0, 0);
   $f = 'arial.ttf';
   $font_size = 10; 
   imagettftext($img_p, $font_size, 0, 10, 20, $b, $f, $WMarkText);
   if ($D_File<>'') {
      imagejpeg ($img_p, $D_File, 100); 
   } else {
      header('Content-Type: image/jpeg');
      imagejpeg($image_p, null, 100);
   }
   imagedestroy($image); 
   imagedestroy($image_p); 
}
/******** usage **********/

$SourceFile = '/home/user/www/images/image1.jpg';
$DestinationFile = '/home/user/www/images/image1-watermark.jpg'; 
$WaterMarkText = 'Copyright phpJabbers.com';
watermarkImage ($SourceFile, $WaterMarkText, $DestinationFile);



Time elapse using sql timestamp

This function is extremely useful as it helps the user determine when a upload too place. I originally got the code from zenverse.net and just added one line to help with what i was looking for.

   $timestamp = strtotime($timestamp);
By removing this line you are able to convert normal time stamps and not just sql
function smartdate($timestamp) {
   $timestamp = strtotime($timestamp);
   $diff = time() - $timestamp;
 
   if ($diff <= 0) {
      return 'Now';
   }
   else if ($diff < 60) {
      return grammar_date(floor($diff), ' second(s) ago');
   }
   else if ($diff < 60*60) {
      return grammar_date(floor($diff/60), ' minute(s) ago');
   }
   else if ($diff < 60*60*24) {
      return grammar_date(floor($diff/(3600)), ' hour(s) ago');
   }
   else if ($diff < 60*60*24*30) {
      return grammar_date(floor($diff/(86400)), ' day(s) ago');
   }
   else if ($diff < 60*60*24*30*12) {
      return grammar_date(floor($diff/(86400*30)), ' month(s) ago');
   }
   else {
      return grammar_date(floor($diff/(604800*52)), ' year(s) ago');
   }
}
 
 
function grammar_date($val, $sentence) {
   if ($val > 1) {
 return $val.str_replace('(s)', 's', $sentence);
   } else {
 return $val.str_replace('(s)', '', $sentence);
   }
}




Compress images and change format

This is another snippet from zenverse.net I've edited the version in which help run my website for security reasons.
function compress_image($source_url, $destination_url, $quality) {
 $info = getimagesize($source_url);
 
 if ($info['mime'] == 'image/jpeg') 
                  $image = imagecreatefromjpeg($source_url);
 elseif ($info['mime'] == 'image/gif')
                  $image = imagecreatefromgif($source_url);
 elseif ($info['mime'] == 'image/png') 
                  $image = imagecreatefrompng($source_url);
 
 //save it
 imagejpeg($image, $destination_url, $quality);
 
 //return destination file url
 return $destination_url;
}
/*******usage*******/

$source_photo = 'images/image.jpg';
$dest_photo = 'images/compresedimage.jpg';
 
$d = compress_image($source_photo, $dest_photo, 90);
 

1 comment: