Quickly backup your 000webhost site?

Please ensure you take regular backups of your files and don’t rely on one single backup forever - if you regularly make changes to your site I’d recommend a full backup BEFORE you make the changes.

Firstly download

  1. backup.php here

Else create a NEW file via File Manager in PUBLIC_HTML called backup.php

PASTE THIS CODE INTO IT and SAVE AND CLOSE.

<?php
/**
 * Backup your entire public_html with this script hopefully.
 */
?>
<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>000webhosting community backup script</title>
	<style type="text/css">
		body{
			font-family: arial;
			font-size: 14px;
			padding: 0;
			margin: 0;
			text-align: center;
		}
		h3{
			text-align: center;
		}
		.container{
			width: 600px;
			margin: 100px auto 0 auto;
			max-width: 100%;
		}
		label{
			font-weight: bold;
			margin: 10px 0;
		}
		input[type="text"]{
			border: 1px solid #eee;
			padding: 10px;
			display: block;
			margin: 10px auto;
		}
		input[type="submit"]{
			padding: 10px 20px;
			display: block;
			margin: 10px auto;
			border: 2px solid green;
			background: #fff;
		}
		.copyright{
			position: fixed;
			bottom:0;
			background: #333;
			color: #fff;
			width: 100%;
			padding: 10px 20px;
			text-align: center;
		}
		.copyright a{
			color: #eee;
		}
	</style>
</head>
<body>
	<div class="container">
		<h2>000WEBHOST Community Backup Script</h2>
		<img src="https://www.000webhost.com/static/default.000webhost.com/images/logo.png " alt="logo">
<h3>Ensure this backup.php is uploaded into your PUBLIC_HTML directory if you want a full backup</h3>
		<form action="" method="POST">
			<label for="zip-file-name">Backup File Name</label> <br>
			<input type="text" id="zip-file-name" name="zip_file_name" value="" placeholder="Choose a suitable backup name" />
			<input type="submit" value="Backup into a zip file" />
		</form>
		<?php
			if(isset($_POST['zip_file_name'])){
				if(!empty($_POST['zip_file_name'])){
					ini_set('max_execution_time', 1000000);
					/* creates a compressed zip file */
					function generate_zip_file($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;
						}
					}

					function getDirItems($dir, &$results = array()){
					    $files = scandir($dir);
					    foreach($files as $key => $value){
					        $path = realpath($dir.DIRECTORY_SEPARATOR.$value);
					        list($unused_path, $used_path) = explode(basename(__DIR__).'/', $path);
					        $file_name = $dir.DIRECTORY_SEPARATOR.$value;
					        if(!is_dir($path)) {
					            $results[] = $used_path;
					        } else if($value != "." && $value != "..") {
					            getDirItems($path, $results);
					            $results[] = $value.'/';
					        }
					    }
					    return $results;
					}
					$get_name = $_POST['zip_file_name'];
					$get_ext  = '.zip';
					$final_name = $get_name.$get_ext;
					//if true, good; if false, zip creation failed
					$result = generate_zip_file(getDirItems(dirname(__FILE__)),$final_name);
					if($result){
						echo "Successfully Created a backup of your 000webhost public_html directory in Zip file $final_name";
					} else {
						echo "Failed to create zip file, Please try again, if you are still having issues seek community assistance on the forum. It mostly likely is that your site is too big for the backup script to run within the free limits - you'll be better off downloading your public_html via FTP client instead.";
					}
				} else {
					echo "Please provide a suitable ZIP File Name for your 000webhost Backup";
				}
			}
		?>
	</div>

	<div class="copyright">000webhost Community Backup Method&copy; <?php echo date("Y"); ?> .  <a href="http://000webhost.com/forum/" target="_blank">Community Forums</a></div>
</body>
</html>

If you have downloaded the file instead above then UPLOAD THIS FILE to PUBLIC_HTML :slight_smile:

Now visit http://REPLACEWITHYOURURL.000webhostapp.com/backup.php in the browser and you should see the backup page!

Choose a suitable ZIP File Name like 20August2018 or current date and hit “Create Zip File”

If it works then you should see similar message

Head to PUBLIC_HTML and download the backup ZIP!

Once downloaded, verify all the files you require are then, and make sure the open correctly and are not CORRUPT!

Ensure your backups are kept in a safe place, good ideas would be an external media drive, online file storage like Google Drive or Dropbox!

Any questions or comments do drop them below!

2 Likes

Backing up your database is a seperate task!

Head to 000webhost.com and click Manage Database

Select the required database then Manage and phpMyAdmin

Once launched ensure you click your DATABASE ON THE LEFT HAND SIDE.

Now along the top CLICK EXPORT

Quick and then GO

The database then should download straight away into your browser in .SQL format

Keep this is safe place as well.

**

  1. Once you’ve completed the backup PLEASE REMOVE THE BACKUP.PHP FILE FROM YOUR PUBLIC_HTML or DELETE IT preferably, if another user stumbled onto it they could backup your site and download all of your files (which some might not mind) but if you store personal information or configuration files/ database backups then you’ll soon be unhappy!

**

There is a different version if anyone would like a look.

Download via here: clicky

Or paste this code into a file called backup.php or superbackup.php etc in your PUBLIC_HTML directory.

<?php
/**
 */
define('VERSION', '0.0.1 Beta');

$timestart = microtime(TRUE);
$GLOBALS['status'] = array();

$unzipper = new Unzipper;
if (isset($_POST['dounzip'])) {
  // Check if an archive was selected for unzipping.
  $archive = isset($_POST['zipfile']) ? strip_tags($_POST['zipfile']) : '';
  $destination = isset($_POST['extpath']) ? strip_tags($_POST['extpath']) : '';
  $unzipper->prepareExtraction($archive, $destination);
}

if (isset($_POST['dozip'])) {
  $zippath = !empty($_POST['zippath']) ? strip_tags($_POST['zippath']) : '.';
  // Resulting zipfile e.g. zipper--2016-07-23--11-55.zip.
  $zipfile = '000webhostbackup-' . date("Y-m-d--H-i") . '.zip';
  Zipper::zipDir($zippath, $zipfile);
}

$timeend = microtime(TRUE);
$time = round($timeend - $timestart, 4);



/**
 * Class Unzipper
 */
class Unzipper {
  public $localdir = '.';
  public $zipfiles = array();

  public function __construct() {
    // Read directory and pick .zip, .rar and .gz files.
    if ($dh = opendir($this->localdir)) {
      while (($file = readdir($dh)) !== FALSE) {
        if (pathinfo($file, PATHINFO_EXTENSION) === 'zip'
          || pathinfo($file, PATHINFO_EXTENSION) === 'gz'
          || pathinfo($file, PATHINFO_EXTENSION) === 'rar'
        ) {
          $this->zipfiles[] = $file;
        }
      }
      closedir($dh);

      if (!empty($this->zipfiles)) {
        $GLOBALS['status'] = array('info' => 'There are backup .zip or .gz or .rar files found, ready for extraction see below to extract these files');
      }
      else {
        $GLOBALS['status'] = array('info' => 'No previous backup .zip or .gz or rar files found. So only the backup functionality available.');
      }
    }
  }

  /**
   * Prepare and check zipfile for extraction.
   *
   * @param string $archive
   *   The archive name including file extension. E.g. my_archive.zip.
   * @param string $destination
   *   The relative destination path where to extract files.
   */
  public function prepareExtraction($archive, $destination = '') {
    // Determine paths.
    if (empty($destination)) {
      $extpath = $this->localdir;
    }
    else {
      $extpath = $this->localdir . '/' . $destination;
      // Todo: move this to extraction function.
      if (!is_dir($extpath)) {
        mkdir($extpath);
      }
    }
    // Only local existing archives are allowed to be extracted.
    if (in_array($archive, $this->zipfiles)) {
      self::extract($archive, $extpath);
    }
  }

  /**
   * Checks file extension and calls suitable extractor functions.
   *
   * @param string $archive
   *   The archive name including file extension. E.g. my_archive.zip.
   * @param string $destination
   *   The relative destination path where to extract files.
   */
  public static function extract($archive, $destination) {
    $ext = pathinfo($archive, PATHINFO_EXTENSION);
    switch ($ext) {
      case 'zip':
        self::extractZipArchive($archive, $destination);
        break;
      case 'gz':
        self::extractGzipFile($archive, $destination);
        break;
      case 'rar':
        self::extractRarArchive($archive, $destination);
        break;
    }

  }

  /**
   * Decompress/extract a zip archive using ZipArchive.
   *
   * @param $archive
   * @param $destination
   */
  public static function extractZipArchive($archive, $destination) {
    // Check if webserver supports unzipping.
    if (!class_exists('ZipArchive')) {
      $GLOBALS['status'] = array('error' => 'Error: Your PHP version does not support unzip functionality.');
      return;
    }

    $zip = new ZipArchive;

    // Check if archive is readable.
    if ($zip->open($archive) === TRUE) {
      // Check if destination is writable
      if (is_writeable($destination . '/')) {
        $zip->extractTo($destination);
        $zip->close();
        $GLOBALS['status'] = array('success' => 'Website backup successfully unzipped onto your 000webhost hosting');
      }
      else {
        $GLOBALS['status'] = array('error' => 'Error: Directory not writeable by webserver.');
      }
    }
    else {
      $GLOBALS['status'] = array('error' => 'Error: Cannot read backup .zip archive');
    }
  }

  /**
   * Decompress a .gz File.
   *
   * @param string $archive
   *   The archive name including file extension. E.g. my_archive.zip.
   * @param string $destination
   *   The relative destination path where to extract files.
   */
  public static function extractGzipFile($archive, $destination) {
    // Check if zlib is enabled
    if (!function_exists('gzopen')) {
      $GLOBALS['status'] = array('error' => 'Error: Your PHP has no zlib support enabled.');
      return;
    }

    $filename = pathinfo($archive, PATHINFO_FILENAME);
    $gzipped = gzopen($archive, "rb");
    $file = fopen($destination . '/' . $filename, "w");

    while ($string = gzread($gzipped, 4096)) {
      fwrite($file, $string, strlen($string));
    }
    gzclose($gzipped);
    fclose($file);

    // Check if file was extracted.
    if (file_exists($destination . '/' . $filename)) {
      $GLOBALS['status'] = array('success' => 'File unzipped successfully.');

      // If we had a tar.gz file, let's extract that tar file.
      if (pathinfo($destination . '/' . $filename, PATHINFO_EXTENSION) == 'tar') {
        $phar = new PharData($destination . '/' . $filename);
        if ($phar->extractTo($destination)) {
          $GLOBALS['status'] = array('success' => 'Extracted tar.gz archive successfully.');
          // Delete .tar.
          unlink($destination . '/' . $filename);
        }
      }
    }
    else {
      $GLOBALS['status'] = array('error' => 'Error unzipping file.');
    }

  }

  /**
   * Decompress/extract a Rar archive using RarArchive.
   *
   * @param string $archive
   *   The archive name including file extension. E.g. my_archive.zip.
   * @param string $destination
   *   The relative destination path where to extract files.
   */
  public static function extractRarArchive($archive, $destination) {
    // Check if webserver supports unzipping.
    if (!class_exists('RarArchive')) {
      $GLOBALS['status'] = array('error' => 'Error: Your PHP version does not support .rar archive functionality. <a class="info" href="http://php.net/manual/en/rar.installation.php" target="_blank">How to install RarArchive</a>');
      return;
    }
    // Check if archive is readable.
    if ($rar = RarArchive::open($archive)) {
      // Check if destination is writable
      if (is_writeable($destination . '/')) {
        $entries = $rar->getEntries();
        foreach ($entries as $entry) {
          $entry->extract($destination);
        }
        $rar->close();
        $GLOBALS['status'] = array('success' => 'Your backup zip file has been extracted successfully.');
      }
      else {
        $GLOBALS['status'] = array('error' => 'Error: Directory not writeable by webserver. Please seek assistance on the community');
      }
    }
    else {
      $GLOBALS['status'] = array('error' => 'Error: Cannot read .rar archive, most probably corrupt - try checking?.');
    }
  }

}

/**
 * Class Zipper
 *
 * Copied and slightly modified from http://at2.php.net/manual/en/class.ziparchive.php#110719
 * @author umbalaconmeogia
 */
class Zipper {
  /**
   * Add files and sub-directories in a folder to zip file.
   *
   * @param string $folder
   *   Path to folder that should be zipped.
   *
   * @param ZipArchive $zipFile
   *   Zipfile where files end up.
   *
   * @param int $exclusiveLength
   *   Number of text to be exclusived from the file path.
   */
  private static function folderToZip($folder, &$zipFile, $exclusiveLength) {
    $handle = opendir($folder);

    while (FALSE !== $f = readdir($handle)) {
      // Check for local/parent path or zipping file itself and skip.
      if ($f != '.' && $f != '..' && $f != basename(__FILE__)) {
        $filePath = "$folder/$f";
        // Remove prefix from file path before add to zip.
        $localPath = substr($filePath, $exclusiveLength);

        if (is_file($filePath)) {
          $zipFile->addFile($filePath, $localPath);
        }
        elseif (is_dir($filePath)) {
          // Add sub-directory.
          $zipFile->addEmptyDir($localPath);
          self::folderToZip($filePath, $zipFile, $exclusiveLength);
        }
      }
    }
    closedir($handle);
  }

  /**
   * Zip a folder (including itself).
   *
   * Usage:
   *   Zipper::zipDir('path/to/sourceDir', 'path/to/out.zip');
   *
   * @param string $sourcePath
   *   Relative path of directory to be zipped.
   *
   * @param string $outZipPath
   *   Relative path of the resulting output zip file.
   */
  public static function zipDir($sourcePath, $outZipPath) {
    $pathInfo = pathinfo($sourcePath);
    $parentPath = $pathInfo['dirname'];
    $dirName = $pathInfo['basename'];

    $z = new ZipArchive();
    $z->open($outZipPath, ZipArchive::CREATE);
    $z->addEmptyDir($dirName);
    if ($sourcePath == $dirName) {
      self::folderToZip($sourcePath, $z, 0);
    }
    else {
      self::folderToZip($sourcePath, $z, strlen("$parentPath/"));
    }
    $z->close();

    $GLOBALS['status'] = array('success' => 'Successfully created the backup file, download it by using the File Manager on 000webhost.com or by using a FTP client, else you can simply paste this into your browser http://YOURSITE.000webhostapp.com/
    
    
    ' . $outZipPath); 
  } 
}




?>



<!DOCTYPE html>
<html>
<head>
  <title>000webhost Community Backup Zipper</title>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  <style type="text/css">
    <!--
    body {
      font-family: Arial, sans-serif;
      line-height: 150%;
    }

    label {
      display: block;
      margin-top: 20px;
    }

    fieldset {
      border: 0;
      background-color: #EEE;
      margin: 10px 0 10px 0;
    }

    .select {
      padding: 5px;
      font-size: 110%;
    }

    .status {
      margin: 0;
      margin-bottom: 20px;
      padding: 10px;
      font-size: 80%;
      background: #EEE;
      border: 1px dotted #DDD;
    }

    .status--ERROR {
      background-color: red;
      color: white;
      font-size: 120%;
    }

    .status--SUCCESS {
      background-color: green;
      font-weight: bold;
      color: white;
      font-size: 120%
    }

    .small {
      font-size: 0.7rem;
      font-weight: normal;
    }

    .version {
      font-size: 80%;
    }

    .form-field {
      border: 1px solid #AAA;
      padding: 8px;
      width: 280px;
    }

    .info {
      margin-top: 0;
      font-size: 80%;
      color: #777;
    }

    .submit {
      background-color: #378de5;
      border: 0;
      color: #ffffff;
      font-size: 15px;
      padding: 10px 24px;
      margin: 20px 0 20px 0;
      text-decoration: none;
    }

    .submit:hover {
      background-color: #2c6db2;
      cursor: pointer;
    }
    .copyright{
			position: fixed;
			bottom:0;
			background: #333;
			color: #fff;
			width: 100%;
			padding: 10px 20px;
			text-align: center;
		}
		.copyright a{
			color: #eee;
		}
    -->
  </style>
</head>
<body>
<p class="status status--<?php echo strtoupper(key($GLOBALS['status'])); ?>">
  Status: <?php echo reset($GLOBALS['status']); ?><br/>
  <span class="small">000webhost processing Time: <?php echo $time; ?> seconds</span>
</p>
<img src="https://www.000webhost.com/static/default.000webhost.com/images/logo.png " alt="logo">
<form action="" method="POST">
  <fieldset>
    <h1>Website Unzipper Function</h1>
    <label for="zipfile">Select the backup ZIP file to unzip into your public_html directory.</label>
    <select name="zipfile" size="1" class="select">
      <?php foreach ($unzipper->zipfiles as $zip) {
        echo "<option>$zip</option>";
      }
      ?>
    </select>
    <label for="extpath">Extraction path (keep this blank for public_html):</label>
    <input type="text" name="extpath" class="form-field" />
    <p class="info"> or if you want to extract a backup into a new directory then type it here: such as images to extract a backup zip into a directory called images</p>
    <input type="submit" name="dounzip" class="submit" value="Unzip Previous Backup File"/>
  </fieldset>

  <fieldset>
    <h1>Website Zipping Function</h1>
    <label for="zippath">Leave this BLANK to backup your PUBLIC_HTML folder - so click the blue button below and you'll be backing up your entire folder as long as you've uploaded this file backup.php to your PUBLIC_HTML directory. </label>
    <input type="text" name="zippath" class="form-field" />
    <p class="info">Else if you want to backup a single directory for example type images to backup ONLY the directory images</p>
    <input type="submit" name="dozip" class="submit" value="Backup Your Website"/>
  </fieldset>
</form>
<p class="version">000webhost Community Backup Script: <?php echo VERSION; ?></p>
<div class="copyright">000webhost Community Backup Method&copy; <?php echo date("Y"); ?> .  <a href="http://000webhost.com/forum/" target="_blank">Community Forums</a></div>
</body>
</html>

Visit the backup.php file via yoursite.000webhostapp.com/backup.php

Backup using the bottom feature

Leave the field EMPTY providing you’ve uploaded this script to PUBLIC_HTML and it will zip all files within public_html

It will then give you a green banner if the process works.

You can download your backup via FTP client - pull the zip into your home computer, or using File Manager at 000webhost.com - download the .zip file or via the browser by visiting yoursite.000webhostapp.com/000webhostbackup-date-time.zip file directly.

If you’ve uploaded a previous backup and want to extract the website then make sure your PUBLIC_HTML has the .php script uploaded and the .zip backup - make sure the rest of the directory is near empty to avoid over-writing.

Select your backup zip and click extract!

You can use the script to only zip certain directories if you want like typing “downloads” would only archive your directory under public_html/downloads

:slight_smile:
Any questions, comments or issues please discuss below.

As per previous post - DELETE THIS SCRIPT after you’ve taken the backups or move it outside public_html to avoid members of the public stumbling on it…

The other version of the code worked. Thanks for your prompt response.

2 Likes