Location: PHPKode > scripts > WebSite Backup > website-backup/class.backup033b.php
<?

#################################################################

#	GiveMeEnergy Projects										#

#	Powered by []==ThoRĀ® aka Kender								#

#																#

#	WebSite Backup Script										#

#																#

#	This program is free software; you can redistribute 		#

#	it and/or modify it under the terms of the 					#

#	GNU General Public License as published by the 				#

#	Free Software Foundation; either version 2 of the 			#

#	License, or (at your option) any later version				#

#################################################################



/*

	$Id: class.backup.php,v 1.11 2005/04/05 11:18:06 thor Exp $

*/



/*

	VERSION HOSTORY

	vers 0.3.3b

	- eliminated some more quirks in the server-side database backup

	- also updated the second part that I left out the last time b/c I was too lazy (the browser dump)

	- fixed a couple of notices when running under error_reporting ( E_ALL )

	- changed the OS detection to work with other webservers.

	this changes made by Stefan Kudwien <s-m-hide@address.com>		

############################################################

	vers 0.3.2b												

		- added tar and gz command for windows				

		tar and gzip version from:							

		http://unxutils.sourceforge.net/					

		Notes:												

		- tar is not correctly generated if path has ../	

	vers 0.3.1												

		bugs fixed:											

		- the primary keys are not saved					

		- the type (e.g. myisam) are not saved				

		- duplicated INSERT statement on last one			

		- added AUTO_INCREMENT								

		- added creation date and host in dump comment		

		thanks to Markus Michels							

	vers 0.3												

		Database Backup as 'save as...'						

		or directly to a folder on server					

	vers 0.2												

		added Database Backup								

	vers 0.1												

		1st release											

*/



class BackUp	{



	var $WhereBackup;

	var $fileName;

	var $whatBackup;

	var $msg;



	var $dbHeaders			= "";



	Function WhatBackup($whatBackup)	{

		if (	(!$whatBackup) || ($whatBackup == "")	)	{

			die("Specify folder to backup");

		}

		$this->whatBackup	= $whatBackup;

	}



	###	Make dir if not exists	###

	Function WhereBackup($whereBackup)	{

		if (!file_exists($whereBackup))	{

			$patharr	= explode("/", $whereBackup);

			$progr		= "";

			foreach($patharr as $k => $v)	{

				$progr		.= $v;

				if (!file_exists($progr))	{

					$oldumask	= umask(0);

					//echo $progr."<br>";

					if (mkdir($progr, 0777) == FALSE)	{

						trigger_error("impossibile creare la cartella ".$progr." ", E_USER_ERROR);

					}

					@umask($oldumask);

					//	create an empty 'index' to prevent view of folder	//

					if (!file_exists($progr."/index.htm"))	{

						touch($progr."/index.htm");

					}

				}

				$progr	.= "/";

			}

		}

		$this->WhereBackup	= $whereBackup;

	}



	###	Build FileName	###

	Function FileName($fileName)	{

		$today		= date("Y_m_d__H-i");

		$fileName	= (	(!$fileName) || ($fileName == "")	)	? $today : $fileName;

		$this->fileName	= $fileName;

	}



	###	Database Backup For mySQL	###

	###	This function set the default_filename when page is loaded	###

	###	and set up the Headers										###

	Function DBFileName($filename)	{

		$this->filename	= $filename;

	}

	Function SaveAs($filename)	{

		header("Content-disposition: filename=".$filename."");

		header("Content-type: application/octetstream");

		header("Pragma: no-cache");

		header("Expires: 0");

		$this->dbHeaders	= 1;

	}



	###	Based on script of phpMyAdmin	###

	Function DBMakeBackup($host,$port,$user,$pwd,$dbname)	{

		$i		= 0;

		$crlf	= "\r\n";

		$schema_insert	= "";

		$host	= (!$host)		? "localhost"	: $host;

		$port	= (!$port)		? "3306"		: $port;

		$user	= (!$user)		? "root"		: $user;

		$dbname	= (!$dbname)	? die("No Database specified")		: $dbname;

		$password	= ($pwd == "")	? "NO" : "YES";

		@mysql_pconnect($host.":".$port, $user, $pwd) or die("Can't connect to ".$host.":".$port." (using password: ".$password.") ");

		@mysql_select_db($dbname) or die ("Unable to select database");

		$tables			= mysql_list_tables($dbname);

		$num_tables		= @mysql_numrows($tables);

		$Year		= date("Y");

		$Month		= date("m");

		$Day		= date("d");

		$lang		= $_SERVER['HTTP_ACCEPT_LANGUAGE'];

		$country	= StrToUpper($lang);

		$loc	= array("".$lang."_".$country."@euro","".$lang."_".$country."","".$lang."","".$country."");

		foreach ($loc as $GetRightLocale)	{

			If (setlocale(LC_TIME,$GetRightLocale)) {		//	Found a Valid SetLocale

				break;

			}

		}

		###	Search and Replace \n \r in the INSERT Statement	###

		###	for each records									###

		$search       = array("\x00", "\x0a", "\x0d", "\x1a"); //\x08\\x09, not required

		$replace      = array('\0', '\n', '\r', '\Z');



		$DataCreation	= strftime("%d %B %Y", mktime(0,0,0,$Month,$Day,$Year));

		$Time			= date("H:i:s");

		###	Save to Server	###

		If ($this->dbHeaders == 0)	{

			$content	= "";

			$content	.= $crlf;

		    $content	.= "# --------------------------------------------------------".$crlf."";

		    $content	.= "#".$crlf."";

		    $content	.= "# Dump Script for '".$dbname."' ".$crlf."";

		    $content	.= "#".$crlf."";

			$content	.= "# Host: ".$host."".$crlf."";

			$content	.= "#".$crlf."";

			$content	.= "# created on ".$DataCreation." at ".$Time."".$crlf."";

			$content	.= "#".$crlf."";

		    $content	.= $crlf;

			$content	.= "# --------------------------------------------------------".$crlf."";

			##	Open file for writing	##

			$fp = fopen($this->filename, 'w');

			while($i < $num_tables)	{

				$table	= mysql_tablename($tables, $i);

				$content	.= $crlf;

			    $content	.= "# --------------------------------------------------------".$crlf."";

			    $content	.= "#".$crlf."";

			    $content	.= "# Table Structure for '".$table."' ".$crlf."";

			    $content	.= "#".$crlf."";

			    $content	.= $crlf;

				#################################################

				#	Build Table Structure			#

				#################################################

				/*	Table Structure	*/

				$schema_create = "";

				$schema_create .= "DROP TABLE IF EXISTS `".$table."`;".$crlf;

				$schema_create .= "CREATE TABLE `".$table."` (".$crlf;

				$result			= mysql_db_query($dbname, "SHOW FIELDS FROM `".$table."`") or die("error select database");

				while($row = mysql_fetch_array($result))	{

					$schema_create .= "   `$row[Field]` $row[Type]";

			        $schema_create .= ($row["Null"] != "YES")	? " NOT NULL" : "";

			        $schema_create .= (isset($row["Default"]) && (!empty($row["Default"]) || $row["Default"] == "0"))

									? " default '$row[Default]'" : "";

			        $schema_create .= ($row["Extra"] != "")		? " ".$row["Extra"] : "";

			        $schema_create .= ",".$crlf;

				}

				$schema_create		= ereg_replace(",".$crlf."$", "", $schema_create);

				/*	Table Keys	*/

				$index		= array();

				$result		= mysql_db_query($dbname, "SHOW KEYS FROM `".$table."`") or die();

				while($row = mysql_fetch_array($result))	{

					if($row['Key_name'] == "PRIMARY")

						$kname			= "PRIMARY KEY";

					elseif($row['Non_unique'] == 0)

						$kname			= "UNIQUE `".$row['Key_name']."`";

					else

						$kname			= "KEY `".$row['Key_name']."`";

					if(!isset($index[$kname]))

						$index[$kname] = array();

					$index[$kname][]	= "`".$row['Column_name']."`".(isset($row['Sub_part']) ? "(".$row['Sub_part'].")" : "");

				}

				foreach($index as $x => $columns)	{

					$schema_create .= ",".$crlf;

					$schema_create .= "   ".$x." (" . implode($columns, ", ") . ")";

				}

				$schema_create .= $crlf.") ";



				#	DataBase Type								#

				$result		= mysql_db_query($dbname, "SHOW TABLE STATUS FROM ".$dbname." LIKE '".$table."'") or die();

				$row		= mysql_fetch_array($result);

				$schema_create	.= "Type=".$row['Type'];

				$schema_create	.= (!empty($row['Auto_increment']) ? " AUTO_INCREMENT=".$row['Auto_increment'] : "");

				$schema_create	.= ";".$crlf.$crlf;

				$content	.= $schema_create;

				$schema_create	= "";

				#################################################

				#	Build Table Content (INSERT)		#

				#################################################

				$content	.= "#".$crlf."";

				$content	.= "# Dumping data for table '".$table."'".$crlf."";

				$content	.= "#$crlf";

				$content	.= $crlf;

				$result = mysql_db_query($dbname, "SELECT * FROM `$table`") or die();

				$a		= 0;

				while($row = mysql_fetch_row($result))	{

					$table_list = "(";

					for($j=0; $j<mysql_num_fields($result);$j++)

						$table_list .= "`".mysql_field_name($result,$j)."`, ";

						$table_list = substr($table_list,0,-2);

						$table_list .= ")";

					if(isset($GLOBALS["showcolumns"]))

						$schema_insert .= "INSERT INTO `".$table."` ".$table_list." VALUES (";

					else

						$schema_insert .= "INSERT INTO `".$table."` VALUES (";

					for($j=0; $j<mysql_num_fields($result);$j++)	{

						if(!isset($row[$j]))

							$schema_insert .= " NULL,";

						elseif($row[$j] != "")

							$schema_insert .= " '".Str_Replace($search,$replace,addslashes($row[$j]))."',";

						else

							$schema_insert .= " '',";

					}

					$schema_insert = ereg_replace(",$", "", $schema_insert);

					$schema_insert .= ");".$crlf;

					//$handler(trim($schema_insert));

					$a++;

				}

				$content	.= $schema_insert."".$crlf."";

				$schema_insert	= "";

				$i++;

			}

			##	Write to file	##

			fwrite($fp, $content);

			fclose($fp);

		} else {

		###	Save As			###

			print $crlf;

		    print "# --------------------------------------------------------".$crlf."";

		    print "#".$crlf."";

		    print "# Dump Script for '".$dbname."' ".$crlf."";

		    print "#".$crlf."";

			print "# Host: ".$host."".$crlf."";

			print "#".$crlf."";

			print "# created on ".$DataCreation." at ".$Time."".$crlf."";

			print "#".$crlf."";

		    print $crlf;

			print "# --------------------------------------------------------".$crlf."";

			$schema_insert	= "";

			$table			= "";

			$schema_create	= "";

			$i              = 0;

			while($i < $num_tables)	{

			    print $crlf;

				$table	= mysql_tablename($tables, $i);

				print $crlf;

			    print "# --------------------------------------------------------".$crlf."";

			    print "#".$crlf."";

			    print "# Table Structure for '".$table."' ".$crlf."";

			    print "#".$crlf."";

			    print $crlf;

				#################################################

				#	Build Table Structure			#

				#################################################

				/*	Table Structure	*/

				$schema_create .= "DROP TABLE IF EXISTS `".$table."`;".$crlf;

				$schema_create .= "CREATE TABLE `".$table."` (".$crlf;

				$result			= mysql_db_query($dbname, "SHOW FIELDS FROM `".$table."`") or die("error select database");

				while($row = mysql_fetch_array($result))	{

					$schema_create .= "   `$row[Field]` $row[Type]";

			        $schema_create .= ($row["Null"] != "YES")	? " NOT NULL" : "";

			        $schema_create .= (isset($row["Default"]) && (!empty($row["Default"]) || $row["Default"] == "0"))

									? " default '$row[Default]'" : "";

			        $schema_create .= ($row["Extra"] != "")		? " ".$row["Extra"] : "";

			        $schema_create .= ",".$crlf;

				}

				$schema_create		= ereg_replace(",".$crlf."$", "", $schema_create);

				/*	Table Keys	*/

				$index		= array();

				$result		= mysql_db_query($dbname, "SHOW KEYS FROM `".$table."`") or die();

				while($row = mysql_fetch_array($result))	{

					if($row['Key_name'] == "PRIMARY")

						$kname			= "PRIMARY KEY";

					elseif($row['Non_unique'] == 0)

						$kname			= "UNIQUE `".$row['Key_name']."`";

					else

						$kname			= "KEY `".$row['Key_name']."`";

					if(!isset($index[$kname]))

						$index[$kname] = array();

					$index[$kname][]	= "`".$row['Column_name']."`".(isset($row['Sub_part']) ? "(".$row['Sub_part'].")" : "");

				}

				foreach($index as $x => $columns)	{

					$schema_create .= ",".$crlf;

					$schema_create .= "   ".$x." (" . implode($columns, ", ") . ")";

				}

				$schema_create .= $crlf.") ";



				#	DataBase Type								#

				$result		= mysql_db_query($dbname, "SHOW TABLE STATUS FROM ".$dbname." LIKE '".$table."'") or die();

				$row		= mysql_fetch_array($result);

				$schema_create	.= "Type=".$row['Type'];

				$schema_create	.= (!empty($row['Auto_increment']) ? " AUTO_INCREMENT=".$row['Auto_increment'] : "");

				$schema_create	.= ";".$crlf.$crlf;

				print $schema_create;

				$schema_create	= "";

				#################################################

				#	Build Table Content (INSERT)				#

				#################################################

				print "#".$crlf."";

				print "# Dumping data for table '".$table."'".$crlf."";

				print "#$crlf";

				print $crlf;

				$result = mysql_db_query($dbname, "SELECT * FROM `$table`") or die();

				$a		= 0;

				while($row = mysql_fetch_row($result))	{

					$table_list = "(";

					for($j=0; $j<mysql_num_fields($result);$j++)

						$table_list .= "`".mysql_field_name($result,$j)."`, ";

						$table_list = substr($table_list,0,-2);

						$table_list .= ")";

					if(isset($GLOBALS["showcolumns"]))

						$schema_insert .= "INSERT INTO `".$table."` ".$table_list." VALUES (";

					else

						$schema_insert .= "INSERT INTO `".$table."` VALUES (";

					for($j=0; $j<mysql_num_fields($result);$j++)	{

						if(!isset($row[$j]))

							$schema_insert .= " NULL,";

						elseif($row[$j] != "")

							$schema_insert .= " '".Str_Replace($search,$replace,addslashes($row[$j]))."',";

						else

							$schema_insert .= " '',";

					}

					$schema_insert = ereg_replace(",$", "", $schema_insert);

					$schema_insert .= ");".$crlf;

					//$handler(trim($schema_insert));

					$a++;

				}

				print $schema_insert."".$crlf."";

				$schema_insert	= "";

				$i++;

			}		##	=>	End while

		}			##	=>	End If save as..

	}



	Function Debug()	{

		$this->msg	= "<br>";

		$this->msg	.= "WhatBackup: ".$this->whatBackup."<br>";

		$this->msg	.= "WhereBackup: ".$this->WhereBackup."<br>";

		$this->msg	.= "FileName: ".$this->fileName.".tar.gz<br>";

	}

	###	Do It	###

	Function Backup()	{

		$comm			= "";

		$comm2			= "";

		switch ((bool)(substr(PHP_OS, 0, 3) == 'WIN'))	{

			default:

			case false:

				//	command

				$comm 		= "tar cfvz ".$this->WhereBackup."/".$this->fileName.".tar.gz ".$this->whatBackup."";

			break;

			case true:

				$comm 		= "tar cf ".$this->WhereBackup."/".$this->fileName.".tar ".$this->whatBackup."";

				$comm2		= "gzip ".$this->WhereBackup."/".$this->fileName.".tar";

			break;

		}

		$theScript	= $_SERVER['SCRIPT_NAME'];

		$today		= date("Y_m_d__H-i");

		###	If u want All output, use passthru() function	###

		$run		= exec($comm);

		if ($comm2)	{

			$run		= exec($comm2);

		}

		$msg		= ($run != "") ? "Backup OK" : "Backup KO";

		echo "".$this->msg."";

	}



}

?>

Return current item: WebSite Backup