7 Handy PHP Code Snippets to Save Time

Snippets are often helpful in adding small features to projects or apps in no time. One simply needs to copy and paste the snippet in their projects or apps, and voila!

In this article, I will be featuring 7 awesome and really handy code snippets in PHP, which might prove to be a super time saver for you.

1) Automatic Word Sensor

Word Sensor

This code snippet works like a charm to automatically censor words which you define in an array by replacing them with other words which you can choose to set. This snippet is obtained from phpsnips.com.

 <?php
    function censorWords($text){
       $find = array('/badword1/i','/badword2/i','/badword3/i');
       $replace = array('goodword1','goodword2','goodword3');
       return preg_replace($find,$replace,$text);
    }
    $text = 'That badword1 cat is badword2 stupid.';
    echo censorWords($text);
?> 

2) Crop Images

Crop Images

This code snippet lets you easily crop images from a specified X and Y coordinates and a specified size. This snippet is obtained from css-tricks.com.

 <?php
    $filename= "test.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);
?> 

3) Time to Words

Time to Words

This code snippet will convert any given time in numeric format to the corresponding time in formatted words and numbers, like the above example. This snippet is obtained from viralpatel.net.

 function secsToStr($secs) {
    if($secs>=86400){
       $days=floor($secs/86400);
       $secs=$secs%86400;
       $r=$days.' day';
       if($days<>1){$r.='s';}
       if($secs>0){$r.=', ';}
    }
    if($secs>=3600){
       $hours=floor($secs/3600);
       $secs=$secs%3600;
       $r.=$hours.' hour';
       if($hours<>1){$r.='s';}
       if($secs>0){$r.=', ';}
    }
    if($secs>=60){
       $minutes=floor($secs/60);
       $secs=$secs%60;
       $r.=$minutes.' minute';
       if($minutes<>1){$r.='s';}
       if($secs>0){$r.=', ';}
    }
    $r.=$secs.' second';
    if($secs<>1){$r.='s';}
    return $r;
} 

4) Date Format Validation

Date Validation

This code snippet checks whether an input date is given in a specific format or not, which in our case is YYYY/MM/DDThis snippet is obtained from viralpatel.net.

 function checkDateFormat($date) {
    //match the format of the date
    if (preg_match ("/^([0-9]{4})-([0-9]{2})-([0-9]{2})$/", $date, $parts)) {
       //check whether the date is valid or not
       if(checkdate($parts[2],$parts[3],$parts[1]))
          return true;
       else
          return false;
   }
   else
       return false;
} 

5) Check for Opened Email

Email Status

This code snippet lets you check whether your sent email has been opened or not by the recipient. You need to include the following line of HTML code within your email and then save the rest in an image.php file. This snippet is obtained from emoticode.net.

<img src=”http://www.yourhost.com/image.php”>

Copy the following within image.php,

 <?php
    error_reporting(0);
    Header("Content-Type: image/jpeg");
    //Get IP
    if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
       $ip=$_SERVER['HTTP_CLIENT_IP'];
    }
    elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
       $ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
    }
    else {
       $ip=$_SERVER['REMOTE_ADDR'];
    }
    //Time
    $actual_time = time();
    $actual_day = date('Y.m.d', $actual_time);
    $actual_day_chart = date('d/m/y', $actual_time);
    $actual_hour = date('H:i:s', $actual_time);
    //GET Browser
    $browser = $_SERVER['HTTP_USER_AGENT'];
    //LOG
    $myFile = "log.txt";
    $fh = fopen($myFile, 'a+');
    $stringData = $actual_day . ' ' . $actual_hour . ' ' . $ip . ' ' . $browser . ' ' . "rn";
    fwrite($fh, $stringData);
    fclose($fh);
    //Generate Image (Es. dimesion is 1x1)
    $newimage = ImageCreate(1,1);
    $grigio = ImageColorAllocate($newimage,255,255,255);
    ImageJPEG($newimage);
    ImageDestroy($newimage);
?> 

6) Force File Download

Force Download

This code snippet forces your users to download a specified file instead of viewing directly within the browser. For specifying forced downloads you need to add links in the following manner,

<a href=”downloadFile.php?file=7383″>Download</a>

Here downloadFile.php will contain the following lines of code. This snippet is obtained from phpsnips.com.

 <?php

    $filename = $_GET['file']; //Get the fileid from the URL
    // Query the file ID
    $query = sprintf("SELECT * FROM tableName WHERE id = '%s'",mysql_real_escape_string($filename));
    $sql = mysql_query($query);
    if(mysql_num_rows($sql)>0){
      $row = mysql_fetch_array($sql);
      // Set some headers
      header("Pragma: public");
      header("Expires: 0");
      header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
      header("Content-Type: application/force-download");
      header("Content-Type: application/octet-stream");
      header("Content-Type: application/download");
      header("Content-Disposition: attachment; filename=".basename($row['FileName']).";");
      header("Content-Transfer-Encoding: binary");
      header("Content-Length: ".filesize($row['FileName']));
      @readfile($row['FileName']);
      exit(0);
    }
    else {
      header("Location: /");
      exit(0);
    }
?> 

7) Display your Latest Tweet

Latest Tweet

This code snippet will display the latest tweet from a specified twitter username. You can set your preferred username in the username variable. This snippet is obtained from perishablepress.com.

 <?php // import & display latest tweet
    $username = "corephp";
    $feed = "http://search.twitter.com/search.atom?q=from:".$username."&rpp=2";
    // $prefix = '<h3>corePHP</h3>';
    // $suffix = '<p><a href="http://twitter.com/'.$username.'">Follow us on Twitter</a></p>';
    function parse_feed($feed) {
       $stepOne = explode('<content type="html">', $feed);
       $stepTwo = explode('</content>', $stepOne[1]);
       $tweet = $stepTwo[0];
       $tweet = str_replace("&lt;", "<", $tweet);
       $tweet = str_replace("&gt;", ">", $tweet);
       return $tweet;
    }
    $latest_tweet = file_get_contents($feed);
    // echo stripslashes($prefix) . parse_feed($latest_tweet) . stripslashes($suffix);
    echo parse_feed($latest_tweet);
?> 

Wrapping Up

This brings us to the end of this list of some handy code snippets. I hope that these snippets will prove to be helpful for you and save your precious development time. In meantime, why not tell us which snippets have you tried out?

Rahul Chowdhury
Writer at 'corePHP'
A blogger and a happy guy who loves to write articles and make lists related to technology and web, Rahul is a Contributing Author to the 'coreTechnology' Blog.