php fails to restore backup sql - php

i'm creating a restore database script in php but its not working. this is the code so far
<form action = '' method = 'POST'>
<h2>Restore</h2>
<table>
<tr><td><input type=file name="file"></td></tr>
<tr><td><input type = 'submit' name = "restore" value="restore"></tr></td>
</table>
</form>
<?php
$host = 'localhost';
$user = 'root';
$pass = ' ';
$dbname = 'itravel';
//date_default_timezone_set('Asia/Kuala_Lumpur');
//$currentdate = date('YmdGis');
$restore_name = $_POST['file'];
$custompath = $_POST['path'];
if(isset($_POST['restore']))
{
$restore = "c:/xampp/mysql/bin/mysql -h $host -u $user $dbname < $backup_name";
system($restore);
}
?>
nothing happening after clicking the restore button. please help

$restore = "c:/xampp/mysql/bin/mysql -h $host -u $user $dbname < $backup_name";
^^^^^^^^^^^
nowhere do you define $backup_name. Shouldn't it be $restore_name?
Uploads also do not appear in $_POST. They show up via $_FILES.
You should also NEVER assuming an upload succeeded. Especially for a mysql dump file. It is possible that the upload was truncated, yet you blindly feed the file back into MySQL, which could leave you with a partially/totally trashed database.
ALWAYS check for upload errors:
if ($_FILES['files']['error'] !== UPLOAD_ERR_OK) {
die("Upload failed with error " . $_FILES['files']['error']);
}
$restore_name = $_FILES['files']['tmp_name']; // temp file PHP stores upload in

Related

Click Button To Export All Data In Database In To Myfile As .sql (Extension)

There is my Function to download backup is sql format
public function actionBackup()
{
// Set the database access credentials
$db_host = 'localhost';
$db_username = 'root';
$db_password = '';
$db_name = 'fads';
// Set the backup filename and path
$backup_file = 'backup.sql';
$backup_path = "C:/Users/" . get_current_user() . "/Downloads/" . $backup_file;
// Execute the mysqldump command
$path = "C: \ xampp_7.3\mysql\bin";
$command = "mysqldump -u {$db_username} -p{$db_password} {$db_name} > {$backup_path}";
// echo $path.$command;die;
exec("$path > $command");
// Send the backup file as a download
Yii::$app->response->sendFile($backup_path);
// Delete the backup file
unlink($backup_path);
}
It's download backup.sql but its empty i don't understand that where is my code wrong and why i received blank backup.sql
First look if you use correct path for command and backup file.
Avoid spaces in paths.
Try this code:
public function actionBackup()
{
// Set the database access credentials
$db_host = 'localhost';
$db_username = 'root';
$db_password = '';
$db_name = 'fads';
// Set the backup filename and path
$backup_file = 'backup.sql';
$backup_path = "C:\Users\" . get_current_user() . "\Downloads\" . $backup_file;
// Execute the mysqldump command
$command = "\"C:\\xampp_7\\mysql\\bin\\mysqldump.exe\""; // path to mysqldump command
// $commandParams = "-u {$db_username} -p{$db_password} {$db_name} > {$backup_path}"; // mysqldump params
$commandParams = "--host={$db_host} --user={$db_username} --password={$db_password} {$db_name} > {$backup_path}"; // mysqldump params
exec("$command $commandParams");
// Send the backup file as a download
Yii::$app->response->sendFile($backup_path);
// Delete the backup file
unlink($backup_path);
}
Updated the answer

restore database in php

I'm trying to restore my database using this code and it doesn't work
$server_name = "localhost";
$username = "root";
$password = "admin";
$database_name = "uvatravelclone";
$file = basename($_POST["file_open"]);
//$cmd = "mysql -h {$server_name} -u {$username} -p{$password} {$database_name} $file";
$cmd = "mysql -e {$file}";
if (exec($cmd) == true){
echo "succes";
}
else{
echo " error";
}
i need to get the file name or file path of the data because i'm using
<input type=file>
to open the file.
When you use <input type="file" name="file_open">, the information about the uploaded file is put in $_FILES, not $_POST. The file contents are put into a temporary file, and $_FILES['file_open']['tmp_name'] contains the pathname to this temporary file. You can then redirect this to the mysql command, using < filename for shell input redirection.
$server_name = "localhost";
$username = "root";
$password = "admin";
$database_name = "uvatravelclone";
$file = $_FILES['file_open']['tmp_name']
$cmd = "mysql -h {$server_name} -u {$username} -p{$password} {$database_name} < $file";
if (exec($cmd)){
echo "success";
}
else{
echo " error";
}
Note that the return value of exec() is the last line of output of the command, not a true/false value that indicates success.
Things to be known, when you have a type=file in your HTML Form, its necessary to use method="post" and enctype="multipart/form-data"
Example
<form method="post" enctype="multipart/form-data">
<input type="file" name="filename" />
<button>Upload Now</button>
</form>
Render Using PHP
<?php
$getFile = $_FILES["filename"];
var_dump($getFile); //Prints uploaded file details
//Use copy or move_uploaded_file to store the uploaded file on server
//its always better to use move_uploaded_file for the purpose.
?>
Know more it in this link http://www.w3schools.com/php/php_file_upload.asp.
+1 to Barmar's answer, but here's another tip: exec() can fetch the exit status of the command you execute, and this is a more accurate indicator of success or failure.
Traditionally, when a command has an exit status of 0 it means success, and any nonzero value means some error.
exec($cmd, $output, $exitStatus);
if (0 == $exitStatus)){
echo "success";
}
else{
echo " error";
}
See http://php.net/manual/en/function.exec.php

identified by password in the grant query affecting irrelevant connection

In the code below there are 2 mysql connections, the issue is that the second connection gives a connection error if the password coming in from the form is anything but 123456.
Now, password coming in from the form should have nothing to do with the second connection because that password in for the new database that is made before the second conenction starts. The second connection is connecting to another database all together.
However, if i use the commented out $grantQ query, the second connection works fine. That means that the issue is got something to do with identified by '{$pass}' in the $grantQ query.
The identified by '{$pass}' query should only affect the new database that has been created. Why is it affecting the existing db that the second connection is connecting to?
please help .. sorry about the long summary !
<?php
if(isset($_POST['submit'])){
// SUPER CONNECTION
$maindb_db = "little_maindb";
$maindb_server = "localhost";
$maindb_username = "admin#littlesidegym.com";
$maindb_password = "123456";//
$conn = new mysqli($maindb_server, $maindb_username, $maindb_password, $maindb_db);
if ($conn->connect_error) {
die($contact_cus_supp);
}
//NAME OF DB FROM POST - CUSTOMER VIEW
$new_dbname = mysqli_real_escape_string($conn, $_POST['db_name']);
$new_pass = mysqli_real_escape_string($conn, $_POST['pass']);
// CREATING DATABASE
$sql = "CREATE DATABASE IF NOT EXISTS $new_dbname ";
if (!mysqli_query($conn, $sql)) {
mysqli_close($conn);
exit();
}
$host = "localhost";
$user = $_SESSION['sess_email'];
$flush_pri = "FLUSH PRIVILEGES";
$pass = $new_pass;
// GRANT USER PRIVILEGES
echo $current_project;
$grantQ = "GRANT ALL PRIVILEGES ON " . $new_dbname . ".* TO '{$user}'#'{$host}' identified by '{$pass}'";
//$grantQ = "GRANT ALL PRIVILEGES ON " . $new_dbname . ".* TO '{$user}'#'{$host}'";
if(!mysqli_query($conn,$grantQ)){
mysqli_close($conn);
exit();
}
if(!mysqli_query($conn,$flush_pri)){
mysqli_close($conn);
exit();
}
// SUPER CONNECTION CLOSE
mysqli_close($conn);
// ALTOGETHER A DIFFERENT CONNECTION
$secdb_db = "little_userdb";
$secdb_server = "localhost";
$secdb_username = "user#littlesidegym.com";
$secdb_password = "123456";//
$conn = new mysqli($secdb_server, $secdb_username, $secdb_password, $secdb_db);
if ($conn->connect_error) {
die($contact_cus_supp);
}
echo "HELLO WORLD";
?>
// FORM
echo '<table>';
echo '<form action="create_project.php" method="POST" id = "myform" name = "myform" >';
echo '<tr><th></th></tr><tr><td><input type = "text" value="" name = "db_name" class = "req alphanums" placeholder = "DB Name" ><td></tr>';
echo '<tr><th></th></tr><tr><td><input type = "password" value="" name = "pass" class = "req" placeholder = "Password" ><td></tr>';
echo '<tr><th></th></tr><tr><td><div id = "submit"><input type="submit" id = "submit" name = "submit" value = "Create Project"></div><td></tr>';
echo '</form>';
echo '</table>';
You are using the same user name for newly created database and for accessing little_userdb, thus changing its password each time.
In mysql user is identified by name and hostname mask (mysql looks for first match). So your code changes password for existing user and grants him access to the new db.

store image in sql and retrive it in php

I've create a table where I've saved images through "LongBLOB". I need to show those images.
i can save images in my sql but when i want to read and display them i have a problem,
"can not be displayed because it contains errores"
im usi8ng this code to save the image to my sql table
<?php
$username = "root";
$password = "";
$host = "localhost";
$database = "imgtest";
$link = mysql_connect($host, $username, $password);
if (!$link) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db($database);
if (isset($_FILES['image']) && $_FILES['image']['size'] > 0) {
$tmpName = $_FILES['image']['tmp_name'];
$fp = fopen($tmpName, 'r');
$data = fread($fp, filesize($tmpName));
$data = addslashes($data);
fclose($fp);
$namee = $_FILES['image']['name'];
mysql_query("INSERT INTO image(cap,image) VALUES ('$namee','$data')");
}
?>
and im using this code to read and display the image from my sql table
<?php
$con=mysqli_connect("localhost","root","","imgtest");
$wich=$_POST['wich'];
$resoult=mysqli_query($con,"SELECT * FROM image WHERE id LIKE '$wich'");
$imgd = $_GET['img'];
$row = mysqli_fetch_array($resoult);
$image = $row['image'];
header("content-type:image/jpeg");
echo $image;
?>
anyone can help me with this??
It is strongly advised to store images within your file structure (a directory on your server, cloud server, or other accessible location) and only keep a reference such as a url, file name or path path in the database in order to recreate a link or path to the actual image. It is a bad practice to keep images in a database.
Why are you using mysql_ library - it is deprecated.
You need to store binary data. Use prepared statements. In that way you get back binary data.
From 2 you can dump addslashes. That is the root of the problem

Creating a new page for each submission - PHP errors

Here is the site.
I have the submit page, and a form action to a page that queries the submission info into my database. I'll include that code below. What I want to do, is have it create an individual page for each submission. However, I'm getting tons of errors when I try to upload. It uploads but it definitely doesn't create new page. the I have a template form which I'll show you, but first, here's the upload page:
<?php
// For use in creating individual page
$tpl_file = "submission.php";
$tpl_path = "/~lyons/templates/";
$submissions_path = "/~lyons/submissions";
// For use in querying submitter name
$username = $_GET['username'];
session_start();
$_SESSION['username'] = $username;
//Database Information
$dbhost = "";
$dbname = "";
$dbuser = "";
$dbpass = "";
//Connect to database
mysql_connect ( $dbhost, $dbuser, $dbpass)or die("Could not connect: ".mysql_error());
mysql_select_db($dbname) or die(mysql_error());
$name = $_POST['name'];
$filename = $_POST['filename'];
$submitter = $username;
list($width, $height) = getimagesize("$filename");
$type = exif_imagetype($_POST['filename']);
$checkuser = mysql_query("SELECT filename FROM images WHERE filename='$filename'");
$filename_exist = mysql_num_rows($checkuser);
if($filename_exist > 0){
echo "I'm sorry but this image has already been submitted. Please feel free to try another.";
unset($filename);
include 'upload.php';
exit();
}
if (exif_imagetype($_POST['filename']) == IMAGETYPE_GIF) {
echo "Sorry, but we can't accept GIFs. Please feel free to try uploading another.";
unset($filename);
include 'upload.php';
exit();
}
$query = "INSERT INTO images (name, filename, submitter, width, height, type)
VALUES('$name', '$filename', '$submitter', '$width', '$height', $type)";
mysql_query($query) or die(mysql_error());
mysql_close();
echo "Thanks for your submission!<br/> Upload another <a href='/~lyons/upload.php'>here</a>!";
$placeholders = array("{name}", "{filename}", "{username}");
$tpl = file_get_contents($tpl_path.$tpl_file);
$new_member_file = str_replace($placeholders, $data, $tpl);
$php_file_name = $username.".php";
$fp = fopen($submissions_path.$php_file_name, "w");
fwrite($fp, $new_submission_file);
fclose($fp);
?>
And here's the template file (submission.php)
<html>
<title>{name}</title>
<head>
</head>
<body>
<h1>{name}</h1>
Posted by: {username}
<br/>
<img src="{filename}"/>
</body>
</html>
It looks like you might have a path issue. When you use the path "/~lyons" you may not be pointing to the directory you want. Try making the changes below:
// For use in creating individual page
$tpl_file = "submission.php";
//$tpl_path = "/~lyons/templates/";
$tpl_path = "templates/";
And then please post the new error message(s), if any.
To help you in debugging, try turning error reporting and error display on.
// add after <?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
Opening the file is probably failing, for better error control try this:
$fp = #fopen($submissions_path.$php_file_name, "w");
if (!$fp) {
die('Failed to open file! Reason: ' . $php_errormsg);
}
I think your paths are incorrect, most likely the following 2 lines need to be changed to use a full path.
// change
$tpl_path = "/~lyons/templates/";
$submissions_path = "/~lyons/submissions";
// to
$tpl_path = $_SERVER['DOCUMENT_ROOT'] . "/~lyons/templates/";
$submissions_path = $_SERVER['DOCUMENT_ROOT'] . "/~lyons/submissions";
When you go to open the file, it is trying to open /~lyons/templates/ which is a directory that does not exist, it is probably something like /home/lyons/public_html/templates/ or /home/something/public_html/~lyons/templates or /usr/local/apache2/htdocs/~lyons/templates etc. $_SERVER['DOCUMENT_ROOT'] should fill in the correct value, but in few cases you may need to manually set the correct path and prepend it to your $tpl_path and $submissions_path.
**save the "submission.php" in root folder**
`$tpl_file = "submission.php";`
**create "templates/`" folder in root folder**
`$tpl_path = "templates/";`

Categories