Friday, September 27, 2013

Database exported automatically in mysql

Simply to export database in mysql and stored in your particular path. See the following code and run in your system with your db details. After run successfully set the file in cron job. so you get the db backup daily or weekly or monthly to store automatically and take from particular path. cheers :)

<?php
$db_host="localhost"; //your host name
$db_user="root"; //your db user name
$db_pass="root"; //your db password
$db_name="test_db"; //your db name
$tables="*"; // all tables to select as *

db_backup($db_host,$db_user,$db_pass,$db_name,$tables);


function db_backup($db_host,$db_user,$db_pass,$db_name,$tables = '*')
{

  $con= mysql_connect($db_host,$db_user,$db_pass);
  mysql_select_db($db_name,$con);

  //get all of the tables
  if($tables == '*')
  {
    $tables = array();
    $result = mysql_query('SHOW TABLES');
    while($row = mysql_fetch_row($result))
    {
      $tables[] = $row[0];
    }
  }
  else
  {
    $tables = is_array($tables) ? $tables : explode(',',$tables);
  }

  //cycle through
  foreach($tables as $table)
  {
    $result = mysql_query('SELECT * FROM '.$table);
    $num_fields = mysql_num_fields($result);

    $return.= 'DROP TABLE IF  EXISTS '.$table.';';
    $row2 = mysql_fetch_row(mysql_query('SHOW CREATE TABLE '.$table));
    $return.= "\n\n".$row2[1].";\n\n";

    for ($i = 0; $i < $num_fields; $i++)
    {
      while($row = mysql_fetch_row($result))
      {
        $return.= 'INSERT INTO '.$table.' VALUES(';
        for($j=0; $j<$num_fields; $j++)
        {
          $row[$j] = addslashes($row[$j]);
          $row[$j] = ereg_replace("\n","\\n",$row[$j]);
          if (isset($row[$j])) { $return.= '"'.$row[$j].'"' ; } else { $return.= '""'; }
          if ($j<($num_fields-1)) { $return.= ','; }
        }
        $return.= ");\n";
      }
    }
    $return.="\n\n\n";
  }

  //save file
  $filename='db-backup-'.time().'.sql';
  $handle = fopen($filename,'w+');
  fwrite($handle,$return);
  fclose($handle);
}
?>

Tuesday, September 03, 2013

Downloading a remote file using curl

Just like the contents of a remote url can be fetched, a remote file with a given url can be downloaded and saved to local storage too.

    /**
        Download remote file in php using curl
        Files larger that php memory will result in corrupted data
    */
     $url  = 'http://localhost/sugar.zip';
     $path = '/var/www/lemon.zip';

     $ch = curl_init($url);
     if($ch === false)
     {
         die('Failed to create curl handle');
     }

     curl_setopt($ch, CURLOPT_URL, $url);
     curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

     $data = curl_exec($ch);
     file_put_contents($path, $data);
     echo 'File download complete';

     curl_close($ch); 

The above program can download remote files but has few restrictions. If the download file size is larger than the total amount of memory available to php, then either a memory exceeded error would be thrown or the downloaded file would be corrupt.

PHP Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 60527991 bytes) in  /var/www/curl.php on line 19

Hence the problem has to be fixed as shown in the next code example  


/**
    Download remote file in php using curl
    chunking with fopen
*/
$url  = 'http://localhost/bang.zip';
$path = '/var/www/lemon.zip';

$ch = curl_init($url);
if($ch === false)
{
    die('Failed to create curl handle');
}

$fp = fopen($path, 'w');
  
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_FILE, $fp);
  
$data = curl_exec($ch);
  
curl_close($ch);
fclose($fp);

The above code would download large files and save them without any problem. The option CURLOPT_FILE tells curl to write the output to a file.