Pages

Retrieving a Directory Size

PHP doesn’t currently offer a standard function for retrieving the total size of a directory, a task more often required than retrieving total disk space. And although you could make a system-level call to du using exec() or system(), such functions are often disabled for security reasons. The alternative solution is to write a custom PHP function that is capable of carrying out this task. A recursive function seems particularly well-suited for this task.
function directory_size($directory) {

$directorySize=0;

// Open the directory and read its contents.
if ($dh = @opendir($directory)) {

 // Iterate through each directory entry.
 while (($filename = readdir ($dh))) {
 
  // Filter out some of the unwanted directory entries.
  if ($filename != "." && $filename != "..") {
 
   // File, so determine size and add to total.
   if (is_file($directory."/".$filename))
 
    $directorySize += filesize($directory."/".$filename);
    // New directory, so initiate recursion. */
 
    if (is_dir($directory."/".$filename))
    $directorySize += directory_size($directory."/".$filename);
 
   }
  }
 }
    @closedir($dh);
  return $directorySize;
}

Use :
$directory = "/usr/book/chapter10/";
$totalSize = round((directory_size($directory) / 1048576), 2);
printf("Directory %s: %f MB", $directory: ".$totalSize);
Source : Apress Beginning PHP 5 and MySQL 5, From Novice to Professional

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

PHP timestap to MySQL date

Function given below separates the timestamp and returns as desired,
function timestamp2datime($timestamp){
 $datime = NULL;
 $year = substr($timestamp, 0, 4);
 $month = substr($timestamp, 4, 2);
 $day = substr($timestamp, 6, 2);
 $hour = substr($timestamp, 8, 2);
 $min = substr($timestamp, 10, 2);
 $datime .= "$month/$day/$year {$hour}:$min";

 return $datime;
}
If you wan to change mysql timestamp to php date format,you cann use this.
function timestamp2date($timestamp){
 $date = NULL;
 $year = substr($timestamp, 0, 4);
 $month = substr($timestamp, 4, 2);
 $day = substr($timestamp, 6, 2);  
 $date .= "$month/$day/$year";
 return $date;
}

3 jQuery ebook free download

Book Name : jQuery UI 1.6
Publisher : PACKT
Author : Dan Wellman
ISBN 13 : 9781847195128
Buy : Amazon
Download : Click here
Source code : Click here

Book Name : jQuery in Action
Publisher : PACKT
Author : Bear Bibeault, Yehuda Katz
ISBN 13 : 978-1935182320
Buy : Amazon
Download :  Click here
Source code : Click here
Book Name : Learning jQuery 1.3
Publisher : PACKT
Author : Jonathan Chaffe
ISBN 13 : 9781847195128
Buy : Amazon
Download : Click here
Source code : Click here

English representation of a past date

Function given below returns an english representation of a past date within the last month.
function time2str($ts)
{
 if(!ctype_digit($ts))
  $ts = strtotime($ts);

 $diff = time() - $ts;
 if($diff == 0)
  return 'now';
 elseif($diff > 0)
 {
  $day_diff = floor($diff / 86400);
  if($day_diff == 0)
  {
   if($diff < 60) return 'just now';
   if($diff < 120) return '1 minute ago';
   if($diff < 3600) return floor($diff / 60) . ' minutes ago';
   if($diff < 7200) return '1 hour ago';
   if($diff < 86400) return floor($diff / 3600) . ' hours ago';
  }
  if($day_diff == 1) return 'Yesterday';
  if($day_diff < 7) return $day_diff . ' days ago';
  if($day_diff < 31) return ceil($day_diff / 7) . ' weeks ago';
  if($day_diff < 60) return 'last month';
  return date('F Y', $ts);
 }
 else
 {
  $diff = abs($diff);
  $day_diff = floor($diff / 86400);
  if($day_diff == 0)
  {
   if($diff < 120) return 'in a minute';
   if($diff < 3600) return 'in ' . floor($diff / 60) . ' minutes';
   if($diff < 7200) return 'in an hour';
   if($diff < 86400) return 'in ' . floor($diff / 3600) . ' hours';
  }
  if($day_diff == 1) return 'Tomorrow';
  if($day_diff < 4) return date('l', $ts);
  if($day_diff < 7 + (7 - date('w'))) return 'next week';
  if(ceil($day_diff / 7) < 4) return 'in ' . ceil($day_diff / 7) . ' weeks';
  if(date('n', $ts) == date('n') + 1) return 'next month';
  return date('F Y', $ts);
 }
}
 

Google Hosted Javascript Libraries

The Google Hosted Libraries provides your applications with stable, reliable, high-speed, globally available access to all of the most popular, open-source JavaScript libraries.To load a hosted library, copy and paste the HTML snippet for that library (shown below) in your web page. For instance, to load jQuery, embed the <script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> snippet in your web page.
jQuery
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 

<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 

jQuery Mobile
<link rel="stylesheet" href="//ajax.googleapis.com/ajax/libs/jquerymobile/1.4.3/jquery.mobile.min.css" />

<script src="//ajax.googleapis.com/ajax/libs/jquerymobile/1.4.3/jquery.mobile.min.js"></script> 

jQuery UI
<link rel="stylesheet" href="//ajax.googleapis.com/ajax/libs/jqueryui/1.11.1/themes/smoothness/jquery-ui.css" />

<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.11.1/jquery-ui.min.js"></script> 

Open External Links in New Window - jQuery

Manually attributing all the external links on your site with "target="_blank"" might be an exceptionally disappointing assignment. You can stay away from this wild undertaking by utilizing the below given script.
$('a').each(function() {  
  var a = new RegExp('/' + [removed].host + '/');  
  if(!a.test(this.href)) {  
    $(this).click(function(event) {  
      event.preventDefault();  
      event.stopPropagation();  
      window.open(this.href, '_blank');  
    });  
 }  
});

Fix Broken Img Links - jQuery

It is exceptionally drawn out and additionally rankling to check every last picture broken connection and fix it physically. To spare yourself from this inconvenience, you can utilize the below script to alter all the broken connections without a moment's delay.
$('img').error(function(){
$(this).attr('src', ‘img/broken.png’);
});

Disable right click menu - jQuery

Some web designers disable contextual right-click menu on their webpages. One common reason of doing that is to fight off picture stealer. Notwithstanding the reason, you can bind the right-click menu utilizing this basic piece.
$(document).ready(function(){
    $(document).bind("contextmenu",function(e){
        return false;
    });
});

Toggle Stylesheet

Making more than one stylesheet for a website is really normal. Designers do this every once in a while to make surfing helpful for visitors. For instance, a few sites don a really dynamic color plan, which frequently appears aggravating to a few visitors. The most ideal approach to hold such visitors and provide for them an extraordinary user experience is to offer them an optional template, say a straightforward dark and white perspective, which is possible effortlessly with this snippet.
//Look for the media-type you wish to switch then set the href to your new style sheet
$('link[media='screen']').attr('href', 'Alternative.css');

Add (th, st, nd, rd, th) to the end of a number

This straightforward and simple function will take a number and include "th, st, nd, rd, th" after it. Extremely valuable!
function ordinal($cdnl){
    $test_c = abs($cdnl) % 10;
    $ext = ((abs($cdnl) %100 < 21 && abs($cdnl) %100 > 4) ? 'th'
            : (($test_c < 4) ? ($test_c < 3) ? ($test_c < 2) ? ($test_c < 1)
            ? 'th' : 'st' : 'nd' : 'rd' : 'th'));
    return $cdnl.$ext;
} 
for($i=1;$i<100 data-blogger-escaped-br="" data-blogger-escaped-echo="" data-blogger-escaped-i="" data-blogger-escaped-ordinal="">';
} 
Source : http://phpsnips.com/snip-37

Detect Browser Language

At the point when creating a multilingual site, I truly jump at the chance to recover the browser language and utilize this language as the default language for my site. Here's the way I get the language utilized by the client browser:

function get_client_language($availableLanguages, $default='en'){
 if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
  $langs=explode(',',$_SERVER['HTTP_ACCEPT_LANGUAGE']);

  foreach ($langs as $value){
   $choice=substr($value,0,2);
   if(in_array($choice, $availableLanguages)){
    return $choice;
   }
  }
 } 
 return $default;
}
Source : http://snipplr.com/view/12631/detect-browser-language/php-detect-browser-language