0

I am using this code to dump a database backup file to a folder in my htdocs named db_backup, and and option to download the backup file.

<?php
function export_tables($host,$user,$pass,$name,  $tables=false, $backup_name=false )
{
    $link = mysqli_connect($host,$user,$pass,$name);
    // Check connection
    if (mysqli_connect_errno())   {   echo "Failed to connect to MySQL: " . mysqli_connect_error();   }

    mysqli_select_db($link,$name);
    mysqli_query($link,"SET NAMES 'utf8'");

    //get all of the tables
    if($tables === false)
    {
        $tables = array();
        $result = mysqli_query($link,'SHOW TABLES');
        while($row = mysqli_fetch_row($result))
        {
            $tables[] = $row[0];
        }
    }
    else
    {
        $tables = is_array($tables) ? $tables : explode(',',$tables);
    }
    $return='';
    //cycle through
    foreach($tables as $table)
    {
        $result = mysqli_query($link,'SELECT * FROM `'.$table.'`');
        $num_fields = mysqli_num_fields($result);

        $row2 = mysqli_fetch_row(mysqli_query($link, 'SHOW CREATE TABLE `'.$table.'`'));
        $return.= "\n\n".$row2[1].";\n\n";

        for ($i = 0; $i < $num_fields; $i++) 
        {
            $st_counter= 0;
            while($row = mysqli_fetch_row($result))
            {
                //create new command if when starts and after 100 command cycle
                if ($st_counter%100 == 0 || $st_counter == 0 )  {
                    $return.= "\nINSERT INTO `".$table."` VALUES";
                }


                $return.="\n(";
                for($j=0; $j<$num_fields; $j++) 
                {
                    $row[$j] = addslashes($row[$j]);
                    $row[$j] = str_replace("\n","\\n",$row[$j]);
                    if (isset($row[$j])) { $return.= '"'.$row[$j].'"' ; } else { $return.= '""'; }
                    if ($j<($num_fields-1)) { $return.= ','; }
                }
                $return.=")";


                //create new command if when starts and after 100 command cycle (but detect this 1 cycle earlier !)
                if ( ($st_counter+1)%100 == 0  && $st_counter != 0 )    {   $return.= ";";  }
                else                                                {   $return.= ",";  }
                //+++++++
                $st_counter = $st_counter +1 ;
            }
            //as we cant detect WHILE loop end, so, just detect, if last command ends with comma(,) then replace it with semicolon(;)
            if (substr($return, -1) == ',') {$return = substr($return, 0, -1). ';'; }
        }
        $return.="\n\n\n";
    }

    //save file
    $backup_name = $backup_name ? $backup_name : $name."___(".date('H-i-s')."_".date('d-m-Y').').sql';
    file_put_contents('db_backup/'.$backup_name,$return);
    echo 'SUCCESS. Download BACKUP file: <a target="_blank" href="'.'db_backup/'.$backup_name.'">'.$backup_name.'</a>';

}

if (!empty($_GET['delete_filee'])){ chdir(dirname(__file__));       
    if  (unlink($_GET['delete_filee'])) {die('file_deleted');} 
    else                                {die("file doesnt exist");}
}
?>

Executed by:

<?php
                include("../dbbackup_function.php");
                export_tables("localhost","root","password","isys");
            ?>

I would like to know how to save it in another disk in my PC/Server and also in a network PC.

For the disk, I tried:

file_put_contents('D:/db_backup/'.$backup_name,$return);
        echo 'SUCCESS. Download BACKUP file: <a target="_blank" href="'.'D:/db_backup/'.$backup_name.'">'.$backup_name.'</a>';

The dump works fine but the download doesn't. It errors:

enter image description here

So how can I fix the download error for this?

For the network PC, I tried:

file_put_contents('//DevServer/Users/Administrator/Downloads/test/'.$backup_name,$return);
            echo 'SUCCESS. Download BACKUP file: <a target="_blank" href="'.'//DevServer/Users/Administrator/Downloads/test/'.$backup_name.'">'.$backup_name.'</a>';

The dump errors:

Warning: file_put_contents(//DevServer/Users/Administrator/Downloads/test/test___(03-25-01_12-11-2014).sql) [function.file-put-contents]: failed to open stream: Permission denied in E:\xampp\htdocs\sample\test2.php on line 71

While the download errors Object Not Found.

So how can I access the network PC? I have the credentials, I just don't know how to do it thru the code.

Any help would be appreciated.

xjshiya
  • 915
  • 7
  • 16
  • 44
  • To use `file_put_contents()` you first have to have a `string` to write to the file. Instead try using `copy()` [see PHP manual here](http://php.net/manual/en/function.copy.php) – RiggsFolly Nov 12 '14 at 03:46

2 Answers2

1

When you link to the file stored on a local (or networked) drive make sure you prepend the path with file://.

Similar question at How to open a pdf file located in a local c drive

Community
  • 1
  • 1
Kai Schaller
  • 443
  • 3
  • 9
0

For MySQL dump you can take:

function export_tables($host, $user, $pass, $name, $tables=false, $backup_name=false )
{
    $tables = is_array($tables) ? implode(" ",$tables) : "";
    $backup_name = $backup_name ? $backup_name : $name."___(".date('H-i-s')."_".date('d-m-Y').').sql';
    $backup_path = dirname(__FILE__).DIRECTORY_SEPARATOR."db_backup".DIRECTORY_SEPARATOR.$backup_name;

    //****this part can be omited if mysqldump is a system variable
    $link = mysqli_connect($host,$user,$pass,$name);
    if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); }
    mysqli_select_db($link,$name);
    $mysql_home = mysqli_fetch_assoc(mysqli_query($link, "SELECT @@basedir as mysql_home"));
    $mysql_path = str_replace("/", DIRECTORY_SEPARATOR, $mysql_home["mysql_home"]."/bin/mysqldump");

    //****so instead of {$mysql_path} --> mysqldump
    exec("{$mysql_path} --add-drop-table --host={$host} --user={$user} --password={$pass} {$name} {$tables} > {$backup_path}");

    //this part is consider a security vulnerability so limited in some web browsers
    //here you check some answers for this (by @Spiral57):  http://stackoverflow.com/questions/23759756/how-to-open-href-to-local-file
    echo 'SUCCESS. Download BACKUP file: <a target="_blank" href="file:///'.$backup_path.'">'.$backup_name.'</a>';
}

And use it like:

export_tables("localhost","root","password","isys",["table1","table2"]);