SQL Insert Statement Hangs - php

Here is my code. I am not getting an error statement, but the data is not inserted into the table. I tried running the query in PHPMyAdmin and it worked fine. It is also not because of user privileges.
if ($mysql->connect_errno) {
echo("Connect failed: ". $mysql->connect_error);
die();
}
echo "I am confused by this thing<br>";
if(isset($_POST['upload']) && $_FILES['userfile']['size'] > 0)
{
echo "Trying to figure out the errors!!!!<br>";
$fileName = $mysql->real_escape_string($_FILES['userfile']['name']);
$tmpName = $mysql->real_escape_string($_FILES['userfile']['tmp_name']);
$fileSize = intval($_FILES['userfile']['size']);
$fileType = $mysql->real_escape_string($_FILES['userfile']['type']);
echo $fileName."<br>";
echo $tmpName."<br>";
echo $fileSize."<br>";
echo $fileType."<br>";
//reads the file information
$fp = fopen($tmpName, 'r');
$content = fread($fp, filesize($tmpName));
$content = $mysql->real_escape_string(addslashes($content));
fclose($fp);
//this just adds slashes
This adds slashes
if(!get_magic_quotes_gpc())
{
$fileName = addslashes($fileName);
}
//This inserts into the databse
$query = "INSERT INTO upload VALUES ('', '$fileName', '$fileType', $fileSize, '$content')";
This is the line where the code messes up... It just hangs and never prints out the die message
$updateDB = $mysqli->query($query) or die($mysqli->error);
It never prints out this line.
echo "<br>File $fileName uploaded<br>";
}

You are working with $mysql object on the top and abruptly, you triggered your query on $mysqli object.
Change
$updateDB = $mysqli->query($query) or die($mysqli->error);
to
$updateDB = $mysql->query($query) or die($mysql->error);

Related

PHP - Sending sql command as a string thru two php files

EDIT: This is a original code, that is working ok. sorry for formating.
<?php
$target = "images/";
if(!is_dir($target)) mkdir($target); $target = $target . basename( $_FILES['photo']['name']);
$uvod = $_POST['uvod']; $text = $_POST['text']; $nadpis = $_POST['nadpis']; $datum = date("Y-m-d");
if (isset($_POST['zobrazeno'])) {
$zobrazeno = 1; } else {
$zobrazeno = 0; }
$fname=($_FILES['photo']['name']); $funiquename = uniqid() . $fname; $tmpName = $_FILES['photo']['tmp_name']; $fileSize = $_FILES['photo']['size']; $fileType = $_FILES['photo']['type'];
$fp = fopen($tmpName, 'r'); $content = fread($fp, filesize($tmpName)); $content = addslashes($content); fclose($fp);
if(!get_magic_quotes_gpc()){ $fname = addslashes($fname);}
require_once 'db_config.php'; $db_server=mysql_connect($db_hostname,$db_username,$db_password);
if(!$db_server) die("Unable to connect to MySQL" .mysql_error());
mysql_select_db($db_database,$db_server) or die("Unable to connect to database" .mysql_error());
$sql = "INSERT INTO `aktuality` (`nadpis`, `uvod`, `text`, `datum`, `zobrazeno`, `obr_nazev`, `obr_pripona`, `obr_velikost`, `obr_data`) VALUES ('$nadpis', '$uvod', '$text', '$datum', '$zobrazeno', '$funiquename','$fileType','$fileSize','$content')";
mysql_query($sql);
if(move_uploaded_file($_FILES['photo']['tmp_name'], $target)) {
echo "The file ". basename( $_FILES['photo']['name']). " has been uploaded, and your information has been added to the directory";
} else {
echo "Sorry, there was a problem uploading your file.";
}
?>
Im a php beginner.
I have a problem with sending sql command as a string thru two php files.
This php file should call function sql_string() in sql.php, but there is nothing happens.
<?php
------some code here-------
include 'sql.php';
mysql_query(sql_string1());
------some code here------
?>
sql.php
<?php
function sql_string1()
{
$sql ="INSERT INTO `aktuality` (`nadpis`, `uvod`, `text`, `datum`, `zobrazeno`, `obr_nazev`, `obr_pripona`, `obr_velikost`, `obr_data`) VALUES ('$nadpis', '$uvod', '$text', '$datum', '$zobrazeno', '$funiquename','$fileType','$fileSize','$content')";
return $sql;
}
?>
Thanks for your help!
Try doing this for the query to work:
<?php
------some code here-------
include 'sql.php';
$sql = sql_string1() ;
mysql_query($sql) or die(mysql_error());
------some code here------
?>
You should also be able to see what the error is if that query failed.

How to read a pdf file saved in mysql database?

I have successfully uploaded pdf files to the database but now when I am trying to read the files I'm getting issue "Failed to load PDF" when I click on the link. I have checked my browser plugins there is no issue with it.
<?php
$con=mysqli_connect("localhost","root","");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_select_db($con,"mahmood_faridi");
$query = "SELECT id, name FROM upload";
$result = mysqli_query($con,$query) or die('Error, query failed');
if(mysqli_num_rows($result)==0){
echo "Database is empty <br>";
}
else{
while(list($id, $name) = mysqli_fetch_array($result)){
echo "$name<br>";
}
}
if(isset($_GET['id'])){
$id = $_GET['id'];
$query = "SELECT content FROM upload WHERE id = '$id'";
$result = mysqli_query($con,$query) or die('Error, query failed');
$row = mysqli_fetch_row($result);
$content=$row['content'];
header('Content-type: application/pdf');
header('Content-Disposition: inline; filename="' . $content . '"');
header('Content-Transfer-Encoding: binary');
header('Accept-Ranges: bytes');
ob_clean();
ob_flush ();
#readfile($content);
}
mysqli_close($con);
?>
This is the “save file” code:
<?php
$con=mysqli_connect("localhost","root","");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if(isset($_POST['upload']) && $_FILES['userfile']['size'] > 0)
{
$fileName = $_FILES['userfile']['name'];
$tmpName = $_FILES['userfile']['tmp_name'];
$fileSize = $_FILES['userfile']['size'];
$fileType = $_FILES['userfile']['type'];
$fp = fopen($tmpName, 'r');
$content = fread($fp, filesize($tmpName));
$content = mysqli_real_escape_string($con,$content);
fclose($fp);
if(!get_magic_quotes_gpc())
{
$fileName = mysqli_real_escape_string($con,$fileName);
}
mysqli_select_db($con,"mahmood_faridi");
$query = "INSERT INTO upload (name, size, type, content ) ".
"VALUES ('$fileName', '$fileSize', '$fileType', '$content')";
mysqli_query($con,$query) or die('Error, query failed');
mysqli_close($con);
echo "<br>File $fileName uploaded<br>";
}
else
echo "File not uploaded"
?>
I was going to post this as a comment, but it got a bit too long.
When saving the file to the database, try base64_encoding the content, and then base64_decoding it when reading it out. PDFs look odd when viewed in text, and the collation of the database can affect the way it saves, or even what is saved. If one single character changes, you'll have a corrupt PDF.
Also make sure that error reporting is turned off, and that you have no spaces being output alongside the PDF which will also show as the file being corrupt.
I'd also consider splitting the functionality you have out into different files. It looks like everything is in one file there, which can lead to output happening when you don't fully expect it, again corrupting a download.
As an alternative, can you not save the PDF to disk and store the location in the database. You can then read the file as needed and output it, and then there's no issue of the PDF content being corrupted within the database. If you go down this route, make sure you give them unique names as two files could be uploaded with the same name and you might accidentally overwrite one.
Oooooops!
We all concentrated about encoding and database storing, but the problem is another!
When you output your PDF, you get the content from database, but you send this content to the user through:
#readfile($content);
readfile($content) outputs the contents of the file with filepath $content, but in $content there is not any filepath!
You simply change this line of code in
echo $content;
and your script will works.
(Read more about readfile)

Files are corrupted when they are retrieved from database

In my website, I want to allow the user to upload files (they will be stored in a database) and then allow them to download the uploaded files after that. The uploading process is done without errors and they are saved in binary.
The downloading process also works but the downloaded files are corrupted !
Any idea why?
The uploading code:
<?php require_once('Connections/databasestudents.php'); ?>
<?php
$fileName = $_FILES['file']['name'];
$tmpName = $_FILES['file']['tmp_name'];
$fileSize = $_FILES['file']['size'];
$fileType = $_FILES['file']['type'];
$fp = fopen($tmpName, 'r');
$content = fread($fp, filesize($tmpName));
$content = addslashes($content);
$studentId = $_POST['studentId'];
fclose($fp);
$query = "INSERT INTO file (studentId, fileName, fileType, fileContent ) ".
"VALUES ('$studentId', '$fileName', '$fileType', '$content')";
mysql_select_db($database_databasestudents, $databasestudents);
mysql_query($query) or die('Error, query failed');
header("Location: students.php");
die();
?>
The download code:
<?php require_once('Connections/databasestudents.php'); ?>
<?php
mysql_select_db($database_databasestudents, $databasestudents);
$query = 'SELECT fileName, fileContent, fileType, LENGTH(fileContent) as fileSize from file WHERE id="'. $_GET ['id'].'";';
$Recordset1 = mysql_query($query, $databasestudents) or die(mysql_error());
$row_Recordset1 = mysql_fetch_assoc($Recordset1);
$result = mysql_query($query);
$row = mysql_fetch_array($result, MYSQL_BOTH);
$size = $row['fileSize'];
$type = $row['fileType'];
$name =$row['fileName'];
$fileContent = $row['fileContent'];
echo $size . "". $type . " ". $name;
header("Content-length: $size");
header("Content-type: $type");
header("Content-Disposition: attachment; filename=$name");
echo $fileContent;
mysql_close();
?>
Use PDOs and prepared statements. This may fix the issue, and it will fix the SQL injection vulnerability in the download code (which currently allows people to hack your database).
PDO has "large objects" (LOBs) support meant for exactly what you are doing. It will be much more efficient than what you are currently doing. The documentation provides excellent example code which does more or less exactly what you want.
I've figured it out .. jus removing this line from the download code:
echo $size . "". $type . " ". $name;

Error FileType after inserting a file as Blob - PHPMySQL

I made a simple script to insert files as BLOB (mediumblob) in MySQL Database.
The script works fine, the file is uploaded and saved into the table but when I download the file and I try to open it, it says: "File type HTML document (text/html) is not supported"!
This means there was an error while saving the file's type!
Here is my code, please tell me what can be wrong in it:
upload.php :
if (isset($_POST['upload']))
{
if(isset($_POST['upload']) && $_FILES['userfile']['size'] > 0)
{
$fileName = $_FILES['userfile']['name'];
$tmpName = $_FILES['userfile']['tmp_name'];
$fileSize = $_FILES['userfile']['size'];
$fileType = $_FILES['userfile']['type'];
$fp = fopen($tmpName, 'r');
$content = fread($fp, filesize($tmpName));
$content = addslashes($content);
fclose($fp);
if(!get_magic_quotes_gpc())
{
$fileName = addslashes($fileName);
}
$p = $cnx->prepare('INSERT INTO commandes (name, size, type, content) VALUES(:name, :size, :type, :content)');
$p->execute(array('name'=>$fileName, 'size'=>$fileSize, 'type'=>$fileType, 'content'=>$content));
echo "<br>File $fileName uploaded<br>";
}
}
Download.php :
$p = $cnx->prepare('SELECT cmd_id, name FROM commandes');
$p->setFetchMode(PDO::FETCH_OBJ);
$p->execute();
if($p->rowCount() == 0)
{
echo "0 Element <br />";
}
else
{
while($data = $p->fetch())
{
?>
<?php echo $data->name;?> <br>
<?php
}
}
if(isset($_GET['id']))
{
$id = $_GET['id'];
$q = $cnx->prepare('SELECT * FROM commandes WHERE cmd_id = :cmd_id');
$q->setFetchMode(PDO::FETCH_OBJ);
$q->execute(array('cmd_id'=>$id));
while($getFile = $q->fetch())
{
header("Content-length: $getFile->size");
header("Content-type: $getFile->type");
header("Content-Disposition: download; filename=$getFile->name");
echo $getFile->pdf;
exit;
}
}
Thank you!
What is the output for the response headers?
Can you ensure that "Content-type" is "Content-Type"
Also, using a debugger to inspect the response is really valuable.
http://fiddler2.com/get-fiddler

file downloaded from mysql database using php is changed

I'm able to upload a file to mysql but when i download it, the content changes.. example i have test.txt with
"hello"
on it.. when i download it, the test.txt becomes
< pre class='xdebug-var-dump' dir='ltr'>string 'sfasfsafasfsaf' (length=14)
sfasfsafasfsaf
not sure, what's wrong..
this is my code for downloading the file:
<?php include("class_lib.php");
$db = new database();
$db->connect();
if(isset($_GET["file_id"])){
$file_id = $_GET["file_id"];
$query = "SELECT filename, filetype, filesize, bin_data " .
"FROM file_tbl WHERE id = '$file_id'";
$result = mysql_query($query) or die('Error, query failed' . mysql_error());
list($filename, $filetype, $filesize, $bin_data) = mysql_fetch_array($result);
var_dump($bin_data);
header("Content-length: $filesize");
header("Content-type: $filetype");
header("Content-Disposition: attachment; filename=$filename");
echo $bin_data;
}
?>
for images also, it downloads but there's no image anymore.. it only shows "no preview available".. is this with my download script above?
or maybe this upload script i have:
$fileid = (string) ($lastemp_id + 1);
$fileName = basename($_FILES['binFile']['name']);
$extension = pathinfo($fileName, PATHINFO_EXTENSION);
$fileName .= "_fileid_" . $fileid;
$fileName = $fileName.".".$extension;
$tmpName = $_FILES['binFile']['tmp_name'];
$fileSize = $_FILES['binFile']['size'];
$fileType = $_FILES['binFile']['type'];
$fileDesc = $_POST["txtDescription"];
$fp = fopen($tmpName, 'r');
$content = fread($fp, filesize($tmpName));
$content = addslashes($content);
fclose($fp);
if(!get_magic_quotes_gpc()){ $fileName = addslashes($fileName); }
if (isset($fileName)) {
$sql = "INSERT INTO file_tbl ";
$sql .= "(file_desc, bin_data, filename, filesize, filetype) ";
$sql .= "VALUES ('$fileDesc', '$content', ";
$sql .= "'$fileName', '$fileSize', '$fileType')";
mysql_query($sql, $db->connection) or die('Error: query failed' . mysql_error());
$message = "File uploaded.<br>"; var_dump($content);
}
else $message = "No file uploaded. (opt)";
what is wrong here exactly??
You're recklessly jamming binary data into your database without even a whiff of proper SQL escaping. What did you expect to happen? This short sample of code is so full of severe SQL injection bugs I hope for your sake it isn't deployed on the public internet.
For your own safety you should immediately stop using the creaky, old, deprecated mysql_query interface and spend the small amount of time necessary to switch your queries to PDO.
You would not have problems like this if you were using placeholders.
What you're seeing is probably the result of your spurious var_dump statement before you output your proper content.
Please try this, if upload file is flawless.
You can encode your binary data to 64 format when insert into database and also decode before download it.
<?php
ob_start();
include("class_lib.php");
$db = new database();
$db->connect();
if(isset($_GET["file_id"])){
$file_id = $_GET["file_id"];
$query = "SELECT filename, filetype, filesize, bin_data " .
"FROM file_tbl WHERE id = '$file_id'";
$result = mysql_query($query) or die('Error, query failed' . mysql_error());
list($filename, $filetype, $filesize, $bin_data) = mysql_fetch_array($result);
var_dump($bin_data);
ob_end_clean();
header("Content-length: $filesize");
header("Content-type: $filetype");
header("Content-Disposition: attachment; filename=$filename");
echo $bin_data;
exit;
}
?>

Categories