20 Useful PHP Snippets for Beginner Web Developers

Share!

Check out these 20 useful PHP snippets for beginner web developers. These PHP snippets are perfect for all web developers, especially beginners since these codes can ease the development process and are easy to understand without any extensive PHP knowledge.

In this article, you will find code snippets for various functions such as associative array syntax, calendar function, check if a file exists, append a number to a name, change graphics based on season, adjust server time, and more.

You can even learn how to use PHP to convert HEX to RGB, create data URI’s, detect location by IP, crop image, validate email addresses, find all links to a page, get file size, find file extension, randomize background image, and more!

Adjust Server Time

This is a useful PHP snippet that allows you to adjust the server time. This is a simple code that can be used by beginner web developers.

$today = date('Y-m-d-G'); $today = strftime("%Y-%m-%d-%H", strtotime("$today -5 hour"));

Append Non-Breaking Space Between Last Two Words

Here is a great code line that you can use to append non-breaking space between last two words. This PHP snippet is perfect for beginner web developers.

<?php

function word_wrapper($text,$minWords = 3) {
 $return = $text;
 $arr = explode(' ',$text);
 if(count($arr) >= $minWords) {
 $arr[count($arr) - 2].= '&nbsp;'.$arr[count($arr) - 1];
 array_pop($arr);
 $return = implode(' ',$arr);
 }
 return $return;
}


?>

Associative Array Syntax

Here is a PHP snippet of an associative array syntax. You have 3 variations that you can use: simple, array of associative arrays, and looping.

$carParts = array( 
 'Tires'=>100, 
 'Window'=>1042, 
 'DoorHandle'=>917 
);

Automatic Mailto Links

Use this PHP snippet to create automatic Mailto links. This can be used by all designers, beginners to advanced. Check out the code lines and see if you can use them in your projects!

$string = eregi_replace('([_\.0-9a-z-]+@([0-9a-z][0-9a-z-]+\.)+[a-z]{2,3})','<a href="mailto:\\1">\\1</a>', $text);
echo $string;

Basic SimplePie Usage

Check out this small part of basic SimplePie usage PHP snippet that is perfect for beginner web developers. Take a look at this PHP snippet and use it in your current or upcoming projects.

<?php
require_once('inc/simplepie.inc');
 
$feed = new SimplePie();
 
$feed->set_feed_url(array(
'http://search.twitter.com/search.atom?q=movie'
));
 
$feed->enable_cache(true);
$feed->set_cache_location('cache');
$feed->set_cache_duration(15);

Calendar Function

Here you have a part of a PHP code snippet that you can use to create calendars. In the code page, you have a preview of the result. Enjoy!

<?php

function build_calendar($month,$year,$dateArray) {

// Create array containing abbreviations of days of week.
 $daysOfWeek = array('S','M','T','W','T','F','S');

// What is the first day of the month in question?
 $firstDayOfMonth = mktime(0,0,0,$month,1,$year);

// How many days does this month contain?
 $numberDays = date('t',$firstDayOfMonth);

Change Graphics Based on Season

This is a small part of the PHP snippet that shows you how to change graphics based on seasons. You have the complete code lines to fully create this result.

<?php

function current_season() {
 // Locate the icons
 $icons = array(
 "spring" => "images/spring.png",
 "summer" => "images/summer.png",
 "autumn" => "images/autumn.png",
 "winter" => "images/winter.png"
 );

// What is today's date - number
 $day = date("z");

Check if File Exists / Append Number to Name

This is a very useful PHP snippet that all beginner web developers can use. When using this code lines, if the name doesn’t exist, you will receive a file name with _number.

function file_newname($path, $filename){
 if ($pos = strrpos($filename, '.')) {
 $name = substr($filename, 0, $pos);
 $ext = substr($filename, $pos);
 } else {
 $name = $filename;
 }

$newpath = $path.'/'.$filename;
 $newname = $filename;
 $counter = 0;
 while (file_exists($newpath)) {
 $newname = $name .'_'. $counter . $ext;
 $newpath = $path.'/'.$newname;
 $counter++;
 }

return $newname;
}

Convert HEX to RGB

Take a look at this PHP snippet and see if you can use it for your projects. This code is great to converts HEX to array RGB values. Enjoy!

function hex2rgb( $colour ) {
 if ( $colour[0] == '#' ) {
 $colour = substr( $colour, 1 );
 }
 if ( strlen( $colour ) == 6 ) {
 list( $r, $g, $b ) = array( $colour[0] . $colour[1], $colour[2] . $colour[3], $colour[4] . $colour[5] );
 } elseif ( strlen( $colour ) == 3 ) {
 list( $r, $g, $b ) = array( $colour[0] . $colour[0], $colour[1] . $colour[1], $colour[2] . $colour[2] );
 } else {
 return false;
 }
 $r = hexdec( $r );
 $g = hexdec( $g );
 $b = hexdec( $b );
 return array( 'red' => $r, 'green' => $g, 'blue' => $b );
}

Create Data URI’s

These can be useful for embedding images into HTML/CSS/JS to save on HTTP requests, at the cost of maintainability. More information. There are online tools to do it, but if you want your own very simple utility, here’s some PHP to do it:

function data_uri($file, $mime) {
 $contents=file_get_contents($file);
 $base64=base64_encode($contents);
 echo "data:$mime;base64,$base64";
}

Crop Image

Here is a preview of the PHP snippet that lets you crop any image. These code lines can be used by all designers, beginners to experienced.

<?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

Detect Location by IP

This PHP code snippet was written by Chris Coyier. Here you have a part of the full code that allows you to detect location by using the IP information.

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();

Email Address Validation

Here you have a very useful PHP code that lets you validate any email address. This comes in handy when needed to verify a given email address.

$email = 'mail@example.com';
$validation = filter_var($email, FILTER_VALIDATE_EMAIL);

if ( $validation ) $output = 'proper email address';
else $output = 'wrong email address';

echo $output;

Find All Links on a Page

Take a look at this PHP snippet and see if you can use it in your current or upcoming projects. These code lines let you identify all the links from 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 />';
}

Find File Extension

Take a look at this useful PHP snippet that you can easily insert into your projects. These code lines are perfect for beginner web developers, but not only.

function findexts ($filename) {

$filename = strtolower($filename) ;

$exts = split("[/\\.]", $filename) ;

$n = count($exts)-1;

$exts = $exts[$n];

return $exts;

}

Find the Full Path to a File

Check out these code lines that you can use to find the exact path to any file. All you need to do is to save the file as ‘fullpath.php’, upload, and then search on your website.

<?php
 echo dirname(__FILE__);
?>

Get File Size

This PHP snippet was written by Chris Coyier. Take a look at these code lines and see if you need it in your current or upcoming projects. Enjoy!

/*
 * @param string $file Filepath
 * @param int $digits Digits to display
 * @return string|bool Size (KB, MB, GB, TB) or boolean
 */

function getFilesize($file,$digits = 2) {
 if (is_file($file)) {
 $filePath = $file;
 if (!realpath($filePath)) {
 $filePath = $_SERVER["DOCUMENT_ROOT"].$filePath;
 }
 $fileSize = filesize($filePath);
 $sizes = array("TB","GB","MB","KB","B");
 $total = count($sizes);
 while ($total-- && $fileSize > 1024) {
 $fileSize /= 1024;
 }
 return round($fileSize, $digits)." ".$sizes[$total];
 }
 return false;
}

Get Users IP Address

You may sometimes need to get the users IP addresses. This PHP script does exactly that. The code can be used by all web developers, from beginners to experienced.

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'];
}

Pagination Function

Here is a part of a code that helps you when it comes to various pagination functions. This PHP snippet can come in handy at some point.

function pagination($item_count, $limit, $cur_page, $link)
{
 $page_count = ceil($item_count/$limit);
 $current_range = array(($cur_page-2 < 1 ? 1 : $cur_page-2), ($cur_page+2 > $page_count ? $page_count : $cur_page+2));

// First and Last pages
 $first_page = $cur_page > 3 ? '<a href="'.sprintf($link, '1').'">1</a>'.($cur_page < 5 ? ', ' : ' ... ') : null;
 $last_page = $cur_page < $page_count-2 ? ($cur_page > $page_count-4 ? ', ' : ' ... ').'<a href="'.sprintf($link, $page_count).'">'.$page_count.'</a>' : null;

Randomize Background Image

Check out these code lines that you can use in your current or upcoming projects. This PHP snippet can be very helpful if you want to automatically randomize your background images.

<?php
 $bg = array('bg-01.jpg', 'bg-02.jpg', 'bg-03.jpg', 'bg-04.jpg', 'bg-05.jpg', 'bg-06.jpg', 'bg-07.jpg' ); // array of filenames

$i = rand(0, count($bg)-1); // generate random number size of the array
 $selectedBg = "$bg[$i]"; // set variable equal to which random filename was chosen
?>

Recommended for you:





One thought on “20 Useful PHP Snippets for Beginner Web Developers”

Leave a Reply

Your email address will not be published. Required fields are marked *