Showing posts with label php. Show all posts

Tutorial Truncate Long String Exactly In Middle

by in , 0

This will truncate a longer string to a smaller string of specified length (e.g. the "25" value in the code below) while replacing the middle portion with a separator exactly in the middle. Useful when you need to truncate a string but still show the beginning (e.g. for sorting and because it is most recognizable) and also show the end (perhaps to show a file name).


$longString = 'abcdefghijklmnopqrstuvwxyz0123456789z.jpg';
$separator = '/.../';
$separatorlength = strlen($separator) ;
$maxlength = 25 - $separatorlength;
$start = $maxlength / 2 ;
$trunc =  strlen($longString) - $maxlength;

echo substr_replace($longString, $separator, $start, $trunc);

//prints "abcdefghij/.../56789z.jpg"


Tutorial Time Ago Function

by in , 0

This can be used for comments and other from of communication to tell the time ago instead of the exact time which might not be correct to some one in another time zone.

The function only uses unix time stamp like the result of time();

Technique #1

function ago($time)
   $periods = array("second", "minute", "hour", "day", "week", "month", "year", "decade");
   $lengths = array("60","60","24","7","4.35","12","10");

   $now = time();

       $difference     = $now - $time;
       $tense         = "ago";

   for($j = 0; $difference >= $lengths[$j] && $j < count($lengths)-1; $j++) {
       $difference /= $lengths[$j];

   $difference = round($difference);

   if($difference != 1) {
       $periods[$j].= "s";

   return "$difference $periods[$j] 'ago' ";

Technique #2

function _ago($tm,$rcs = 0) {
   $cur_tm = time(); $dif = $cur_tm-$tm;
   $pds = array('second','minute','hour','day','week','month','year','decade');
   $lngh = array(1,60,3600,86400,604800,2630880,31570560,315705600);
   for($v = sizeof($lngh)-1; ($v >= 0)&&(($no = $dif/$lngh[$v])<=1); $v--); if($v < 0) $v = 0; $_tm = $cur_tm-($dif%$lngh[$v]);

   $no = floor($no); if($no <> 1) $pds[$v] .='s'; $x=sprintf("%d %s ",$no,$pds[$v]);
   if(($rcs == 1)&&($v >= 1)&&(($cur_tm-$_tm) > 0)) $x .= time_ago($_tm);
   return $x;

Needs a time() value, and it will tell you how many seconds/minutes/hours/days/years/decades ago.

Tutorial Simple Zipcode Range Tester

by in , 0

This regex below tests the provided zip code if it starts with the numbers 096 and that there are exactly 2 numbers after it. If it does, it echos Yes, if not, it echos No. In this test case, it would echo Yes.

echo 'Zipcode in range?<br />';
if(preg_match('/^096[0-9]{2}$/', $zipcode))
       echo "Yes";
       echo "No";

Tutorial Server Side Image Resizer

by in , 0

The code uses PHP to resize an image (currently only jpeg). Using this method, the resized image is of much better quality than a browser-side resizing. The file size of the new downsized image is also smaller (quicker to download).

The code comes in two parts:

imageResizer() is used to process the image loadimage() inserts the image url in a simpler format

   function imageResizer($url, $width, $height) {

		header('Content-type: image/jpeg');

		list($width_orig, $height_orig) = getimagesize($url);

		$ratio_orig = $width_orig/$height_orig;

		if ($width/$height > $ratio_orig) {
		  $width = $height*$ratio_orig;
		} else {
		  $height = $width/$ratio_orig;

		// This resamples the image
		$image_p = imagecreatetruecolor($width, $height);
		$image = imagecreatefromjpeg($url);
		imagecopyresampled($image_p, $image, 0, 0, 0, 0, $width, $height, $width_orig, $height_orig);

		// Output the image
		imagejpeg($image_p, null, 100);

	//works with both POST and GET
	$method = $_SERVER['REQUEST_METHOD'];
	if ($method == 'GET') {

		imageResize($_GET['url'], $_GET['w'], $_GET['h']);
	 } elseif ($method == 'POST') {

	    imageResize($_POST['url'], $_POST['w'], $_POST['h']);

	// makes the process simpler
	function loadImage($url, $width, $height){
         echo 'image.php?url=', urlencode($url) ,



Above code would be in a file called image.php.

Images would be displayed like this:

<img src="<?php loadImage('image.jpg', 50, 50) ?>"

Tutorial Separate First and Last Name

by in , 0

$name = "John S Smith";

list($fname, $lname) = split(' ', $name,2);

echo "First Name: $fname, Last Name: $lname";

Works with or without middle name.

Tutorial Send Email

by in , 0

1) HTML Form with Inputs

<form action="" method="post">
  <label for="name">Name:</label>
  <input type="text" name="name" id="name" />

  <label for="Email">Email:</label>
  <input type="text" name="email" id="email" />

  <label for="Message">Message:</label><br />
  <textarea name="message" rows="20" cols="20" id="message"></textarea>

  <input type="submit" name="submit" value="Submit" />

2) Process with PHP

This could be in a seperate file (e.g. sendemail.php) in which you'd set the action URL of the form to go there. Or, have the form submit to itself (leave action URL blank) and test for one of the values of the form being POSTed and process there.

       // from the form
       $name = trim(strip_tags($_POST['name']));
       $email = trim(strip_tags($_POST['email']));
       $message = htmlentities($_POST['message']);

       // set here
       $subject = "Contact form submitted!";
       $to = '';

       $body = <<<HTML

       $headers = "From: $email\r\n";
       $headers .= "Content-type: text/html\r\n";

       // send the email
       mail($to, $subject, $body, $headers);

       // redirect afterwords, if needed
       header('Location: thanks.html');

3) Test it

And make sure to keep up with security news around the web.

Tutorial Send a Text Message

by in , 0

You'll need a TextMagic account and to download their PHP helper which they provide after signing up.

// Include the TextMagic PHP lib

// Set the username and password information
$username = 'myusername';
$password = 'mypassword';

// Create a new instance of TM
$router = new TextMagicAPI(array(
	'username' => $username,
	'password' => $password

// Send a text message to '999-123-4567'
$result = $router->send('Wake up!', array(9991234567), true);

// result:  Result is: Array ( [messages] => Array ( [19896128] => 9991234567 ) [sent_text] => Wake up! [parts_count] => 1 )

Reference URL

Tutorial Sanitize Database Inputs

by in , 0

1) Function for stripping out malicious bits

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;

2) Sanitization function

Uses the function above, as well as adds slashes as to not screw up database functions.

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;


  $bad_string = "Hi! <script src=''></script> It's a good day!";
  $good_string = sanitize($bad_string);
  // $good_string returns "Hi! It\'s a good day!"

  // Also use for getting POST/GET variables
  $_POST = sanitize($_POST);
  $_GET  = sanitize($_GET);

Reference URL

Tutorial Return Only One Variable from MySQL Query

by in , 0


function mysql_get_var($query,$y=0){
       $res = mysql_query($query);
       $row = mysql_fetch_array($res);
       $rec = $row[$y];
       return $rec;


$name = mysql_get_var("SELECT name from people where email = ''");

Will return the name field, so what gets returned will be "Roger" (if that was my name in the database).

Reference URL

Tutorial Read/Write Files

by in , 0

Append to a file

function fileWrite($file, $message) {
  fwrite(fopen($file, 'a'), $message . "\n");

Read and display entire file

function fileRead($file){
   $lines = file($file);
   foreach ($lines as $line_num => $line) {
      echo  $line,  '</br>';

Tutorial Randomize File Name

by in , 0

function randomizeFileName( $real_file_name ) {
               $name_parts = @explode( ".", $real_file_name );
               $ext = "";
               if ( count( $name_parts ) > 0 ) {
                       $ext = $name_parts[count( $name_parts ) - 1];
               return substr(md5(uniqid(rand(),1)), -16) . "." . $ext;

Tutorial Randomize Background Image

by in , 0

1. Above the DOCTYPE

Set up and array of filenames, which correspond to the file names of the images you are trying to randomize.

  $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

1. CSS in the <head>

Normally you'd want to keep CSS out of the HTML, but we'll just use it here to echo out the random file name we selected above.

<style type="text/css">
background: url(images/<?php echo $selectedBg; ?>) no-repeat;

Tutorial Random String from Pre-Determined Characters

by in , 0

$string = "abcdwxyz456789";
   $pos = rand(0,13);
   $str .= $string{$pos};
echo $str;

Tutorial Random Slogan Displayer

by in , 0

Create a text file called slogans.txt with permissions that it can be read by the server. Put each slogan on a different line, e.g.:

Building websites since before there was a web.
The internet is for lovers.

       $f_contents = file ("slogans.txt");
       $line = $f_contents[array_rand ($f_contents)];
       print $line;

Tutorial Random Hex Color

by in , 0

Technique #1

    $rand = array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f');
    $color = '#'.$rand[rand(0,15)].$rand[rand(0,15)].$rand[rand(0,15)].$rand[rand(0,15)].$rand[rand(0,15)].$rand[rand(0,15)];

Then echo out the $color value anywhere you need it. For example:

<body style="background: <?php echo $color; ?>;">

Technique #2

<?php printf( "#%06X\n", mt_rand( 0, 0xFFFFFF )); ?>

There is also a JavaScript version.

Reference URL

Tutorial Quick Alphabetic Navigation

by in , 0

Could be useful for an address book style navigation.

foreach (range('a', 'z') as $char) {
 print '<a href="#' . $char . '">' . $char . '</a> | ';

Tutorial POST Validation Loop

by in , 0


You have an HTML form with a variety of inputs. The action attribute of the form points to a PHP file that contains the code below.

Notes about code

This code starts by creating an array that holds the name of various inputs being submitted via a POST. getFormData() is then called, where the required fields are passed in. Inside the function an array is created to hold various pieces of data related to the form. $formData['valid'] is a boolean referencing if all data was provided and valid, $formData['fields'] is an array keyed by the name of the input with their respective value from the POST data, $formData['notValidFields'] is an array that will contain the names of any inputs that were not passed or that had non-valid data.

This logic can be easily extended with regular expressions to check for stricter data, such as email addresses and urls.


$requiredFields = array('field1', 'field2', 'field3', 'field4');
$formData = getFormData($requiredFields);

function getFormData($requiredFields){
       $formData = array();
       $formData['valid'] = true;
       $formData['fields'] = array();
       $formData['notValidFields'] = array();

       for($a = 0; $a < count($requiredFields); $a++){
               $field = $requiredFields[$a];
                       $value = $_POST[$field];
                               $formData['valid'] = false;
                               $formData['notValidFields'][] = $field;
                               $formData['fields'][$field] = $value;
                       $formData['valid'] = false;
                       $formData['notValidFields'][] = $field;
       return $formData;

Tutorial PHP Zebra Striping a Table

by in , 0

Table row in a loop:

<!-- Before loop -->
<?php $c = 0; ?>

<!-- Start loop -->
<tr class="<?=($c++%2==1) ? 'odd' : 'even' ?>">
<!-- End loop -->


.even { background-color:#FFF; }
.odd { background-color:#666; }

Tutorial PHP Redirect

by in , 0

  header( 'Location:' ) ;

Tutorial PHP Include

by in , 0

Can be used multiple times:

<?php include("navigation.php"); ?>

Once only:

<?php include_once("navigation.php"); ?>

Including from the root:

   $path = $_SERVER['DOCUMENT_ROOT'];
   $path .= "/common/header.php";

Reference URL