Sunday, June 5, 2011

mysql database dump using php

Sometimes application needs database backup or rather dump on a regular interval or on request.

So we need a faster and easy way to create mysql dump and also compress those database files to save disk space.

 

This could be a very easy if we use some shell commands through php and create mysql dump. See below how we could achieve this.

 

 

<?php

//Database details

$dbhost = "localhost";

$dbname = "bear44_visitusa";

$dbuser = "bear44_visit";

$dbpwd  = "H8JKjfhyur&*HGrjy";

 

 

 

//List of tables you want to dump separated by single space

$tbl = "getaways_leftmenu getaways_seourl getaways_cmspages";

 

//execute command

exec("mysqldump -h $dbhost -u $dbuser -p\"$dbpwd\" $dbname $tbl > sqlfilename.sql");

 

 

//stores location of current directory

$dir = dirname(realpath(__FILE__));

 

 

 

//command to compress previously created sql file, also gzip -9 states to remove original sql file 

$zip = "gzip -9 $dir/sqlfilename.sql";

 

//execute command

exec($zip);

 

?>
   

 

thats it and you have zipped version of your dump file and the original sql file is automatically removed

 

 

Saturday, June 4, 2011

how to validate hexadecimal color code in php

When taking Hex color code as an input from user it is necessary to validate it. We can validate using preg_match function in php which returns 1 if matches found else 0 using following code.
if(preg_match('/^#[a-f0-9]{6}$/i', $hex_color))
{
//color code is valid
....
}
else
{
//Invalid code
....
}

Sunday, May 1, 2011

serving large file downloads in php

i used to serving download to users in a very simple fashion that is to simply setting headers like

header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-Type: $mimetype");
header("Content-Disposition: attachment; filename=\"$filename\"");
header("Content-Transfer-Encoding: binary");
header("Content-Length: " . $filesize);
  and then reading the file and simply outputting it to browser. like
echo readfile($filename);
  but i realized this wont work always, especially for large downloads since this will load the complete file in memory at once. so i looked and had another techniques guaranteeing it. what we need to do is we will split the file and serve it in chunk by chunk.  
define('CHUNK_SIZE', 1024*1024); // Size (in bytes) of chunk

function readfile_chunked($filename, $retbytes = TRUE) {
$buffer = '';
$cnt =0;
// $handle = fopen($filename, 'rb');
$handle = fopen($filename, 'rb');
if ($handle === false) {
return false;
}
while (!feof($handle)) {
$buffer = fread($handle, CHUNK_SIZE);
echo $buffer;
ob_flush();
flush();
if ($retbytes) {
$cnt += strlen($buffer);
}
}
$status = fclose($handle);
if ($retbytes &amp;&amp; $status) {
return $cnt; // return num. bytes delivered like readfile() does.
}
return $status;
}
this worked well for me.

Saturday, January 29, 2011

calculate distance using latitude longitude


Simple php-mysql query to calculate nearby locations

$sql=mysql_query (“SELECT distinct name, ( 3959 * acos( cos( radians( ‘$lat’ ) ) * cos( radians( lat ) ) * cos( radians( lng ) – radians( ‘$long’ ) ) + sin( radians( ‘$lat’ ) ) * sin( radians( lat ) ) ) ) AS distance FROM markers HAVING distance < ’200′ “);
 

where markers is your table, $lat and $long are point given by you, lat lng are your fields in markers table. Above query will result points upto 200 miles distance.

Creating compressed zip files in php


We can create zip files in php in a very easy way by using phps in built functions. See the function below.

what you need to do is to pass the array of files to this function which you wants to add to zip file. How to list files is described next in  list_dir_files().

<?php

/* creates a compressed zip file */
function create_zip($files = array(),$destination = ”,$overwrite = false) {
 //if the zip file already exists and overwrite is false, return false
 if(file_exists($destination) && !$overwrite) { return false; }
 //vars
 $valid_files = array();
 //if files were passed in…
 if(is_array($files)) {
  //cycle through each file
  foreach($files as $file) {
   //make sure the file exists
   if(file_exists($file)) {
    $valid_files[] = $file;
   }
  }
 }
 //if we have good files…
 if(count($valid_files)) {
  //create the archive
  $zip = new ZipArchive();
  if($zip->open($destination,$overwrite ? ZIPARCHIVE::OVERWRITE : ZIPARCHIVE::CREATE) !== true) {
   return false;
  }
  //add the files
  foreach($valid_files as $file) {
   $zip->addFile($file,$file);
  }
  //debug
  //echo ‘The zip archive contains ‘,$zip->numFiles,’ files with a status of ‘,$zip->status;
  //close the zip — done!
  $zip->close();
  //check to make sure the file exists
  return file_exists($destination);
 }
 else
 {
  return false;
 }
}

?>
   

  

Listing Files To Zip

 

$files_to_zip = list_dir_files(–PATH–);

 

and then pass these files to above function.

<?

 /*********Function to Return file paths in directory and sub directories*********/
 function list_dir_files($src){
  global $err,$files_to_zip;

  $dir = opendir($src);

  while(false !== ( $file = readdir($dir) )) {

   if(($file != ‘.’ && $file != ‘..’)){
    if( is_dir($src. ‘/’ . $file) ) {
     list_dir_files($src . ‘/’ . $file);
    }else {
     //$dest = str_replace(”,”,$src);
     array_push($files_to_zip,$src . ‘/’ . $file);
    }
   }
  }
  closedir($dir);
  return $files_to_zip;
 }

 ?>

php resize image keeping constrants proportions

A simplest and efficient method to resize a image keeping the constraint proportions.
<?
list($width, $height) = getimagesize($image);
$new_dimensions = resize_dimensions($targetwidth,$targetheight,$width,$height);
// Calculates restricted dimensions with a maximum of $target_width by $target_height
function resize_dimensions($target_width,$target_height,$width,$height) {
    $return = array(‘width’ => $width, ‘height’ => $height);
    // If the ratio > target ratio and the width > target width resize down to target width
    if ($width/$height > $target_width/$target_height && $width > $target_width) {
        $return['width'] = $target_width;
        $return['height'] = $target_width/$width * $height;
    }
    // Otherwise, if the height > target, resize down to target height
    else if ($height > $target_height) {
        $return['width'] = $target_height/$height * $width;
        $return['height'] = $target_height;
    }
    return $return;
}
?>

Php running a script in background

Some times we want any script to be run in background which may take a longer time to complete and it should run even if the user session is over.

The nohup linux command is useful for such need. Also we can set priority to this script so that server will not get overloaded due to script.

This will execute your script scriptfile.php in background, It returns process id created by the system which you can use to monitor the process.

<?php

$PID = shell_exec(“nohup php -f scriptfile.php 1>/dev/null & echo $!”);

?>
 

If you want to run this script with a low priority, to avoid system overhead use nice keyword

<?php

$PID = shell_exec(“nohup nice php -f scriptfile.php 1>/dev/null & echo $!”);

?>
 

If you want to pass arguments to this script, the arguments will be available in scriptfile.php in array $_SERVER['argv']

<?php

PID = shell_exec(“nohup nice php -f scriptfile.php $arg1 $arg2 1>/dev/null & echo $!”);

?>
 

You can monitor process status like this

<?php

function is_running($PID){

exec(“ps $PID”, $ProcessState);

if(count($ProcessState) >= 2)

{

return ‘yes’;

}

else{

return ‘no’;

}

}

?>