Pages

Trimming Excess Whitespace

Excess whitespace is a constant problem when working with form data. The trim() function is usually the first tool a programmer turns to, because it removes any excess spaces from the beginning or end of a string. For example, " Wicked Cool PHP   " becomes "Wicked Cool PHP." In fact, it's so handy that you may find yourself using it on almost every available piece of user-inputted, non-array data:
$user_input = trim($user_input);
But sometimes you have excessive whitespace inside a string—when someone may be cutting and copying information from an email, for instance. In that case, you can replace multiple spaces and other whitespace with a single space by using the preg_replace() function. The reg stands for regular expression, a powerful form of pattern matching that you will see several times in this chapter.
function remove_whitespace($string) {
 $string = preg_replace('/\s+/', ' ', $string);
 $string = trim($string);
 return $string;
}
You'll find many uses for this script outside of form verification. It's great for cleaning up data that comes from other external sources.

Text transformation

When dealing with user input, you will often come across people who keep their Caps Lock key permanently enabled, which can make reading what they write difficult on the eye. It also looks like they are shouting. To diminish or entirely remove this problem, use this function , which also supports three other upper- and lowercase text transformations
/*
$text A string variable containing the text to be transformed
$type A string containing the type of transformation to make:
 “u” – Capitalize all letters
 “l” – Set all letters to lowercase
 “w” – Capitalize the first letter of every word
 “s” – Capitalize the first letter of every sentence
*/

function TextTransform($text, $type) {
 switch($type)  {
 case "u": return strtoupper($text);
 case "l": return strtolower($text);
 case "w":
  $newtext = "";
  $words  = explode(" ", $text);
  foreach($words as $word)
   $newtext .= ucfirst(strtolower($word)) . " ";
  return rtrim($newtext);
 case "s":
  $newtext = "";
  $sentences = explode(".", $text);
  foreach($sentences as $sentence)
   $newtext .= ucfirst(ltrim(strtolower($sentence))) . ". ";
  return rtrim($newtext);
 }
return $text;
}
Use : The $text argument should contain the string to transform, while the second argument should be one of the four letters shown (in lowercase).
echo TextTransform("Text to transform","l")

File upload error messages

PHP returns an appropriate error code along with the file array. The error code can be found in the error segment of the file array that is created during the file upload by PHP. In other words, the error might be found in $_FILES['userfile']['error']. Here is the function which explain what actually error come means.
function Upload_Error($error_code) {
    switch ($error_code) {
        case UPLOAD_ERR_INI_SIZE:
            return 'The uploaded file exceeds the upload_max_filesize directive in php.ini';
        case UPLOAD_ERR_FORM_SIZE:
            return 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form';
        case UPLOAD_ERR_PARTIAL:
            return 'The uploaded file was only partially uploaded';
        case UPLOAD_ERR_NO_FILE:
            return 'No file was uploaded';
        case UPLOAD_ERR_NO_TMP_DIR:
            return 'Missing a temporary folder';
        case UPLOAD_ERR_CANT_WRITE:
            return 'Failed to write file to disk';
        case UPLOAD_ERR_EXTENSION:
            return 'File upload stopped by extension';
        default:
            return 'Unknown upload error';
    }
}
Use :
Upload_Error($_FILES['upfile']['error']);

// Or you can use as your requirement. 

Generating Random Passwords

Random (but difficult-to-guess) strings are important in user security. For example, if someone loses a password and you're using MD5 hashes, you won't be able to, nor should you want to, look it up. Instead, you should generate a secure random password and send that to the user. Another application for random number generation is creating activation links in order to access your site's services. Here is a function that creates a password:
<?php
function make_password($num_chars) {
 if ((is_numeric($num_chars)) && ($num_chars > 0) && (! is_null($num_chars))) {
  $password = '';
  $accepted_chars = 'abcdefghijklmnopqrstuvwxyz1234567890';
  // Seed the generator if necessary.
  srand(((int)((double)microtime()*1000003)) );
  for ($i=0; $i<=$num_chars; $i++) {
   $random_number = rand(0, (strlen($accepted_chars) -1));
   $password .= $accepted_chars[$random_number] ;
  }
 return $password;
 }
}
?>
Using above function The make_password() function returns a string, so all you need to do is supply the length of the string as an argument:
<?php
$fifteen_character_password = make_password(15);
?>

Image manipulation and upload class

It oversees file uploads for you. In short, it deals with the uploaded file, and permits you to do whatever you need with the file, particularly in the event that it is a picture, and the same number of times as you need.

It is the perfect class to rapidly incorporate file upload in your site. If the file is a picture, you can change over, resize, crop it from multiple points of view. You can likewise apply channels, include outskirts, content, watermarks, and so on... That is everything you need for an exhibition script for example. Upheld configurations are PNG, JPG, GIF and BMP.

You can likewise utilize the class to chip away at nearby files, which is particularly valuable to  image manipulation features. The class additionally backings Flash uploaders.
include(upload.php);
$foo = new Upload($_FILES['form_field']);
if ($foo->uploaded) {
  // save uploaded image with no changes
  $foo->Process('/home/user/files/');
  if ($foo->processed) {
    echo 'original image copied';
  } else {
    echo 'error : ' . $foo->error;
  }
  // save uploaded image with a new name
  $foo->file_new_name_body = 'foo';
  $foo->Process('/home/user/files/');
  if ($foo->processed) {
    echo 'image renamed "foo" copied';
  } else {
    echo 'error : ' . $foo->error;
  }
  // save uploaded image with a new name,
  // resized to 100px wide
  $foo->file_new_name_body = 'image_resized';
  $foo->image_resize = true;
  $foo->image_convert = gif;
  $foo->image_x = 100;
  $foo->image_ratio_y = true;
  $foo->Process('/home/user/files/');
  if ($foo->processed) {
    echo 'image renamed, resized x=100
          and converted to GIF';
    $foo->Clean();
  } else {
    echo 'error : ' . $foo->error;
  }
}

File Download Script

This document downloading script will permit you to set up a download zone on your site which links to files that don't exist physically on the website. Rather, the documents to be downloaded can exist in an exchange area on the document framework. It is really the script being used right on this page for downloading these records.
// Modify this line to indicate the location of the files you want people to be able to download
// This path must not contain a trailing slash.  ie.  /temp/files/download
 
$download_path = $_SERVER['DOCUMENT_ROOT'] . "/download_semisecure";
$filename = $_GET['filename'];
 
// Detect missing filename
if(!$filename) die("I'm sorry, you must specify a file name to download.");
 
// Make sure we can't download files above the current directory location.
if(eregi("\.\.", $filename)) die("I'm sorry, you may not download that file.");
$file = str_replace("..", "", $filename);

// Make sure we can't download .ht control files.
if(eregi("\.ht.+", $filename)) die("I'm sorry, you may not download that file.");
 
// Combine the download path and the filename to create the full path to the file.
$file = "$download_path/$file";
 
// Test to ensure that the file exists.
if(!file_exists($file)) die("I'm sorry, the file doesn't seem to exist.");
 
// Extract the type of file which will be sent to the browser as a header
$type = filetype($file);

// Get a date and timestamp
$today = date("F j, Y, g:i a");
$time = time();

// Send file headers
header("Content-type: $type");
header("Content-Disposition: attachment;filename=$filename");
header('Pragma: no-cache');
header('Expires: 0');

// Send the file contents.
readfile($file);