Making a database backup - php

I created two simple PHP scripts to back up a MySQL database, but these are not working as expected. I use my program on a Mac using MAMP and using AMPPS on Windows 7.
Here the two scripts I use to backup the database:
[Message edited]
The First and only code
<?php
$host="localhost";
$user="root";
$password="root";
$db="trasporti";
$dbcnx_backup=#mysql_connect("$host", "$user", "$password");
mysql_select_db("$db");
$backupFile = '../../t6/backup/' . $db . date("Y-m-d-H-i-s") . '.sql';
$command = "mysqldump -h $host -u $user -p $password $db > $backupFile";
system($command, $retval);
echo $command;
var_dump($retval);
if ($retval==0)
{
echo "BackUP Riuscito!";
}
else
{
echo "BackUP Fallito!";
}
mysql_close($dbcnx_backup);
?>
Can someone explain what I am doing wrong here?

Remove the space after -p.
You can remove all the calls to the mysql_ functions in your code.
Is safe_mode enabled in your PHP configuration? Use phpinfo() to tell, if yes, you might need to configure PHP properly or turn it off.

Related

Using PHP to access MySQL server to generate table and data schema [duplicate]

Here's the information I have:
I am working with a Linux based system using MySQL and PHP5. I need to be able to generate a mysqldump from within a .php file, and then have that dump be stored in a file on the server in a location I would specify.
As I'm a PHP nooblet, I'd like someone to give me some assistance, guidance, or code, that would do what I require. This would have to be run remotely from the Internet.
You can use the exec() function to execute an external command.
Note: between shell_exec() and exec(), I would choose the second one, which doesn't return the output to the PHP script -- no need for the PHP script to get the whole SQL dump as a string : you only need it written to a file, and this can be done by the command itself.
That external command will :
be a call to mysqldump, with the right parameters,
and redirect the output to a file.
For example :
mysqldump --user=... --password=... --host=... DB_NAME > /path/to/output/file.sql
Which means your PHP code would look like this :
exec('mysqldump --user=... --password=... --host=... DB_NAME > /path/to/output/file.sql');
Of course, up to you to use the right connection information, replacing the ... with those.
If you want to create a backup to download it via the browser, you also can do this without using a file.
The php function passthru() will directly redirect the output of mysqldump to the browser. In this example it also will be zipped.
Pro: You don't have to deal with temp files.
Con: Won't work on Windows. May have limits with huge datasets.
<?php
$DBUSER="user";
$DBPASSWD="password";
$DATABASE="user_db";
$filename = "backup-" . date("d-m-Y") . ".sql.gz";
$mime = "application/x-gzip";
header( "Content-Type: " . $mime );
header( 'Content-Disposition: attachment; filename="' . $filename . '"' );
$cmd = "mysqldump -u $DBUSER --password=$DBPASSWD $DATABASE | gzip --best";
passthru( $cmd );
exit(0);
?>
Take a look here: https://github.com/ifsnop/mysqldump-php ! It is a native solution written in php.
You can install it using composer, and it is as easy as doing:
<?php
use Ifsnop\Mysqldump as IMysqldump;
try {
$dump = new IMysqldump\Mysqldump('database', 'username', 'password');
$dump->start('storage/work/dump.sql');
} catch (\Exception $e) {
echo 'mysqldump-php error: ' . $e->getMessage();
}
?>
It supports advanced users, with lots of options copied from the original mysqldump.
All the options are explained at the github page, but more or less are auto-explicative:
$dumpSettingsDefault = array(
'include-tables' => array(),
'exclude-tables' => array(),
'compress' => 'None',
'no-data' => false,
'add-drop-database' => false,
'add-drop-table' => false,
'single-transaction' => true,
'lock-tables' => false,
'add-locks' => true,
'extended-insert' => true,
'disable-foreign-keys-check' => false,
'where' => '',
'no-create-info' => false
);
For security reasons, it's recommended to specify the password in a configuration file and not in the command (a user can execute a ps aux | grep mysqldump and see the password).
//create a temporary file
$file = tempnam(sys_get_temp_dir(), 'mysqldump');
//store the configuration options
file_put_contents($file, "[mysqldump]
user={$user}
password=\"{$password}\"");
//execute the command and output the result
passthru("mysqldump --defaults-file=$file {$dbname}");
//delete the temporary file
unlink($file);
Here you can find a comprehensive solution to dump mysql structure and data like in PMA (and without using exec, passthru etc.):
https://github.com/antarasi/MySQL-Dump-with-Foreign-keys
It is fork of dszymczuk project with my enhancements.
The usage is simple
<?php
//MySQL connection parameters
$dbhost = 'localhost';
$dbuser = 'dbuser';
$dbpsw = 'pass';
$dbname = 'dbname';
//Connects to mysql server
$connessione = #mysql_connect($dbhost,$dbuser,$dbpsw);
//Set encoding
mysql_query("SET CHARSET utf8");
mysql_query("SET NAMES 'utf8' COLLATE 'utf8_general_ci'");
//Includes class
require_once('FKMySQLDump.php');
//Creates a new instance of FKMySQLDump: it exports without compress and base-16 file
$dumper = new FKMySQLDump($dbname,'fk_dump.sql',false,false);
$params = array(
//'skip_structure' => TRUE,
//'skip_data' => TRUE,
);
//Make dump
$dumper->doFKDump($params);
?>
works like a charm :-)
MajorLeo's answer point me in the right direction but it didn't worked for me. I've found this site that follows the same approach and did work.
$dir = "path/to/file/";
$filename = "backup" . date("YmdHis") . ".sql.gz";
$db_host = "host";
$db_username = "username";
$db_password = "password";
$db_database = "database";
$cmd = "mysqldump -h {$db_host} -u {$db_username} --password={$db_password} {$db_database} | gzip > {$dir}{$filename}";
exec($cmd);
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=\"$filename\"");
passthru("cat {$dir}{$filename}");
I hope it helps someone else!
As long as you are allowed to use exec(), you can execute shell commands through your PHP code.
So assuming you know how to write the mysqldump in the command line, i.e.
mysqldump -u [username] -p [database] > [database].sql
then you can use this as the parameter to exec() function.
exec("mysqldump -u mysqluser -p my_database > my_database_dump.sql");
Well, you can always use PHP's system function call.
http://php.net/manual/en/function.system.php
http://www.php.net/manual/en/function.exec.php
That runs any command-line program from PHP.
<?php
exec('mysqldump --all-databases > /your/path/to/test.sql');
?>
You can extend the command with any options mysqldump takes ofcourse. Use man mysqldump for more options (but I guess you knew that ;))
global $wpdb;
$export_posts = $wpdb->prefix . 'export_posts';
$backupFile = $_GET['targetDir'].'export-gallery.sql';
$dbhost=DB_HOST;
$dbuser=DB_USER;
$dbpass=DB_PASSWORD;
$db=DB_NAME;
$path_to_mysqldump = "D:\xampp_5.6\mysql\bin";
$query= "D:\\xampp_5.6\mysql\bin\mysqldump.exe -u$dbuser -p$dbpass $db $export_posts> $backupFile";
exec($query);
echo $query;
To dump database using shell_exec(), below is the method :
shell_exec('mysqldump -h localhost -u username -ppassword databasename | gzip > dbname.sql.gz');
None of the above codes worked for me. I am using windows.
Below Code worked for me...
$sql = "SELECT * FROM $tableName WHERE yourclause";
$result = $conn->query($sql);
if($result){
if ($result->num_rows > 0) {
$myfile = fopen("daily_events_$district.sql", "w") or die("Unable to open file!");
while($row = $result->fetch_assoc()) {
$rowToString = implode("','",$row);
$writeToFile = "INSERT INTO $tableName VALUES('$rowToString');". PHP_EOL;
fwrite($myfile,$writeToFile);
}
echo "File saved successfully";
}
} else {
echo "No result found";
}
This will save file in your project folder according to your query whatever data you want.
<?php
$toDay = date('d-m-Y');
$dbhost = "localhost";
$dbuser = "YOUR DB USER";
$dbpass = "USER PASSWORD";
$dbname = "DB NAME";
exec("mysqldump --user=$dbuser --password='$dbpass' --host=$dbhost $dbname > /home/....../public_html/".$toDay."_DB.sql");
?>

Unable to run php mysqli script from ubuntuserver

I got hosted ubuntu server where I got apache2 and phpmyadmin. I wrote small script to connect to my mysql database. I placed that script in /var/www/html/ . When I enter to 193.219.91.103:5858/init.php I just see blank page. I use php 7. I found that I could check if mysqli enabled with php -m | grep mysql it did showed me mysqli.
<?php
$db_name = "AndroidDatabase";
$mysql_user = "dbreader";
$mysql_pass = "dbreader";
$server_name = "localhost";
$port = 3306
$con = mysqli_connect($server_name,$mysql_user,$mysql_pass,$db_name,$port);
if(!$con)
{
echo "Connection error".mysqli_connect_error();
}
else
{
echo "<h3>Database connection success</h3>";
}
?>
EDIT:
Fixed all i missed was extra argument $port

Trouble with mysqldump when backing up db as xml

I'm trying to backup one of my databases with mysqldump and I'm trying to export it to an xml file which already exists. Here is what I have:
<?php
$dbUser = 'user'; // db User
$dbPass = 'pass'; // db User Password
$dbName = 'db'; // db name
$dest = $_SERVER['DOCUMENT_ROOT'] . 'backup'; // Path to directory
class MySQLDump {
private $cmd;
function MySQLDump($dbUser,$dbPass,$dbName,$dest) {
$fname = $dbName.'.xml';
$this->cmd='mysqldump -X -u'.$dbUser.' -p'.$dbPass.' '.$dbName.
' >'.$dest.'/'.$fname;
}
public function backup() {
system($this->cmd, $error);
if($error) {
trigger_error ('Backup failed: ' . $error . '<br />Attempted: ' . $this->cmd);
}
}
} // end class def
$mysqlDump = new MySQLDump($dbUser, $dbPass, $dbName, $dest);
$mysqlDump->backup();
?>
This always generates the error thrown in the backup function. Here is a sample of $cmd's output:
mysqldump -X -udan -pdanPass danDB >/var/www/prod/dan/web/backup/danDB.xml
Any idea what's going wrong? I've never really used mysqldump so I'm not sure if I'm approaching this correctly. Any help is greatly appreciated.
try adding a space between -u and your $dbUser.
According to Does mysqldump return a status? something is going wrong, yes. We can not say if a warning or an error because you didn't share the return code.
Apart from that you can easily learn what exactly goes wrong by looking into STDERR output returned from the mysqldump command. E.g. you can pipe it into database.err:
mysqldump -X -udan -pdanPass danDB >/path/to/backup/danDB.xml 2>database.err
^^^^^^^^^^^^^^
This one work for me
mysqldump --user=xxx --password=xxx databasename --xml > file.xml

Using a .php file to generate a MySQL dump

Here's the information I have:
I am working with a Linux based system using MySQL and PHP5. I need to be able to generate a mysqldump from within a .php file, and then have that dump be stored in a file on the server in a location I would specify.
As I'm a PHP nooblet, I'd like someone to give me some assistance, guidance, or code, that would do what I require. This would have to be run remotely from the Internet.
You can use the exec() function to execute an external command.
Note: between shell_exec() and exec(), I would choose the second one, which doesn't return the output to the PHP script -- no need for the PHP script to get the whole SQL dump as a string : you only need it written to a file, and this can be done by the command itself.
That external command will :
be a call to mysqldump, with the right parameters,
and redirect the output to a file.
For example :
mysqldump --user=... --password=... --host=... DB_NAME > /path/to/output/file.sql
Which means your PHP code would look like this :
exec('mysqldump --user=... --password=... --host=... DB_NAME > /path/to/output/file.sql');
Of course, up to you to use the right connection information, replacing the ... with those.
If you want to create a backup to download it via the browser, you also can do this without using a file.
The php function passthru() will directly redirect the output of mysqldump to the browser. In this example it also will be zipped.
Pro: You don't have to deal with temp files.
Con: Won't work on Windows. May have limits with huge datasets.
<?php
$DBUSER="user";
$DBPASSWD="password";
$DATABASE="user_db";
$filename = "backup-" . date("d-m-Y") . ".sql.gz";
$mime = "application/x-gzip";
header( "Content-Type: " . $mime );
header( 'Content-Disposition: attachment; filename="' . $filename . '"' );
$cmd = "mysqldump -u $DBUSER --password=$DBPASSWD $DATABASE | gzip --best";
passthru( $cmd );
exit(0);
?>
Take a look here: https://github.com/ifsnop/mysqldump-php ! It is a native solution written in php.
You can install it using composer, and it is as easy as doing:
<?php
use Ifsnop\Mysqldump as IMysqldump;
try {
$dump = new IMysqldump\Mysqldump('database', 'username', 'password');
$dump->start('storage/work/dump.sql');
} catch (\Exception $e) {
echo 'mysqldump-php error: ' . $e->getMessage();
}
?>
It supports advanced users, with lots of options copied from the original mysqldump.
All the options are explained at the github page, but more or less are auto-explicative:
$dumpSettingsDefault = array(
'include-tables' => array(),
'exclude-tables' => array(),
'compress' => 'None',
'no-data' => false,
'add-drop-database' => false,
'add-drop-table' => false,
'single-transaction' => true,
'lock-tables' => false,
'add-locks' => true,
'extended-insert' => true,
'disable-foreign-keys-check' => false,
'where' => '',
'no-create-info' => false
);
For security reasons, it's recommended to specify the password in a configuration file and not in the command (a user can execute a ps aux | grep mysqldump and see the password).
//create a temporary file
$file = tempnam(sys_get_temp_dir(), 'mysqldump');
//store the configuration options
file_put_contents($file, "[mysqldump]
user={$user}
password=\"{$password}\"");
//execute the command and output the result
passthru("mysqldump --defaults-file=$file {$dbname}");
//delete the temporary file
unlink($file);
Here you can find a comprehensive solution to dump mysql structure and data like in PMA (and without using exec, passthru etc.):
https://github.com/antarasi/MySQL-Dump-with-Foreign-keys
It is fork of dszymczuk project with my enhancements.
The usage is simple
<?php
//MySQL connection parameters
$dbhost = 'localhost';
$dbuser = 'dbuser';
$dbpsw = 'pass';
$dbname = 'dbname';
//Connects to mysql server
$connessione = #mysql_connect($dbhost,$dbuser,$dbpsw);
//Set encoding
mysql_query("SET CHARSET utf8");
mysql_query("SET NAMES 'utf8' COLLATE 'utf8_general_ci'");
//Includes class
require_once('FKMySQLDump.php');
//Creates a new instance of FKMySQLDump: it exports without compress and base-16 file
$dumper = new FKMySQLDump($dbname,'fk_dump.sql',false,false);
$params = array(
//'skip_structure' => TRUE,
//'skip_data' => TRUE,
);
//Make dump
$dumper->doFKDump($params);
?>
works like a charm :-)
MajorLeo's answer point me in the right direction but it didn't worked for me. I've found this site that follows the same approach and did work.
$dir = "path/to/file/";
$filename = "backup" . date("YmdHis") . ".sql.gz";
$db_host = "host";
$db_username = "username";
$db_password = "password";
$db_database = "database";
$cmd = "mysqldump -h {$db_host} -u {$db_username} --password={$db_password} {$db_database} | gzip > {$dir}{$filename}";
exec($cmd);
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=\"$filename\"");
passthru("cat {$dir}{$filename}");
I hope it helps someone else!
As long as you are allowed to use exec(), you can execute shell commands through your PHP code.
So assuming you know how to write the mysqldump in the command line, i.e.
mysqldump -u [username] -p [database] > [database].sql
then you can use this as the parameter to exec() function.
exec("mysqldump -u mysqluser -p my_database > my_database_dump.sql");
Well, you can always use PHP's system function call.
http://php.net/manual/en/function.system.php
http://www.php.net/manual/en/function.exec.php
That runs any command-line program from PHP.
<?php
exec('mysqldump --all-databases > /your/path/to/test.sql');
?>
You can extend the command with any options mysqldump takes ofcourse. Use man mysqldump for more options (but I guess you knew that ;))
global $wpdb;
$export_posts = $wpdb->prefix . 'export_posts';
$backupFile = $_GET['targetDir'].'export-gallery.sql';
$dbhost=DB_HOST;
$dbuser=DB_USER;
$dbpass=DB_PASSWORD;
$db=DB_NAME;
$path_to_mysqldump = "D:\xampp_5.6\mysql\bin";
$query= "D:\\xampp_5.6\mysql\bin\mysqldump.exe -u$dbuser -p$dbpass $db $export_posts> $backupFile";
exec($query);
echo $query;
To dump database using shell_exec(), below is the method :
shell_exec('mysqldump -h localhost -u username -ppassword databasename | gzip > dbname.sql.gz');
None of the above codes worked for me. I am using windows.
Below Code worked for me...
$sql = "SELECT * FROM $tableName WHERE yourclause";
$result = $conn->query($sql);
if($result){
if ($result->num_rows > 0) {
$myfile = fopen("daily_events_$district.sql", "w") or die("Unable to open file!");
while($row = $result->fetch_assoc()) {
$rowToString = implode("','",$row);
$writeToFile = "INSERT INTO $tableName VALUES('$rowToString');". PHP_EOL;
fwrite($myfile,$writeToFile);
}
echo "File saved successfully";
}
} else {
echo "No result found";
}
This will save file in your project folder according to your query whatever data you want.
<?php
$toDay = date('d-m-Y');
$dbhost = "localhost";
$dbuser = "YOUR DB USER";
$dbpass = "USER PASSWORD";
$dbname = "DB NAME";
exec("mysqldump --user=$dbuser --password='$dbpass' --host=$dbhost $dbname > /home/....../public_html/".$toDay."_DB.sql");
?>

PHP ignoring mysql_connect requests

I'm new to PHP and have installed on Linux to boot (also a newbie).
Anyway, PHP is working...
<?
$myVar = "test";
echo($myVar);
?>
... works just fine.
But...
<?
$dbhost = "localhost";
$dbuser = "myuser";
$dbpass = "mypass";
$dbname = "mydb";
echo($dbhost . "-" . $dbuser . "-" . $dbpass . "-" . $dbname);
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die("Unable to connect to MySQL");
print $conn;
mysql_close($conn);
phpInfo();
?>
... does nothing. Nor errors, nothing. Its as if the code isn't even there.
Any help?
Try to do the following:
First make sure display_errors is turned on in your php configuration file. Also set the level of error_reporting to show all errors, including strict (error_reporting = E_ALL|E_STRICT). After you make changes, restart your webserver.
Run phpinfo(), and check that the mysql extension is installed and working. If it isn't make sure that you uncommented it in the php configuration file (again, remember to restart apache after each change to the configuration file).
At this point MySQL should be loaded and working, and you should be able to tell from the error (if it persists) what's the problem.
Try also dumping the contents of the connection result ($conn) to see what it contains.
In general, I'd recommend using long php tags (<?php and not <?) since it is more portable (short tags are off by default in PHP 5 installations).
Try adding this to the top of your code:
error_reporting(E_ALL);
If it does nothing, doesn't that mean that it connected fine? What output do you expect out of that statement?
You could try
error_reporting(E_ALL);
$conn = mysql_connect("localhost", "myusername", "mypassword");
if(!$conn) {
echo 'Unable to connect';
} else {
echo 'Connected to database';
}
var_dump($conn);
edit: Addressing the comment saying that you have a mysql query setup, if you are not seeing "success" it means something is wrong with your query. Add to the above
$sth = mysql_query("SELECT * FROM tablename");
if(!$sth) {
echo 'unable to query: ' . mysql_error();
} else {
echo 'success';
}
Is there more code than you're showing us? The block you have just sets up a connection. You won't see anything at all if it succeeds, you have to use $conn to do something.
To confirm, try changing your password to a deliberately wrong value, and then see if you get an error. If you do, the code works just fine.
Connecting to a database with
$conn = mysql_connect("localhost", "myusername", "mypassword") or die("Unable to connect");
will have no (visible( results if the connection was made succesfully. However, once you run this statement, you can use the other mysql functions to make make queries to the database.
Connecting to a database tells your program "hey, I want to talk to this database".
This code is supposed to create a db connection, nothing else. What do you expect to see?
Try this
<?php
$conn = mysql_connect("localhost", "myusername", "mypassword")
or die("Unable to connect");
print("code sample");
print $conn;
?>
It should print you something like "resource #1"...
And then you may use that connection to communicate with db server

Categories