PHP upload to MySQL database with download and view file - php

Does not download correctly: can't open the link. Help appreciated. I am new to PHP and MySQL. I have MySQL set to BLOB for the content and I am not sure how to be clearer, I can see the link(s) for the file with the respective id to the file content $id in the url, but when I click on the link nothing opens up, I want to be able to open the file inthe brownser. I intend on being able to open .zip files and extract in later development. A sfar as security please also explain in good details so I can learn. I see my code was mod, but still not working in the array link.
UPLOAD.PHP:
<?php
$dbname="upload";
$host="localhost";
$user="SELF";
$pass="PICME";
$link = mysql_connect($hostname, $user, $pass);
mysql_select_db($dbname, $link);
?>
<form method="post" enctype="multipart/form-data">
<table width="350" border="0" cellpadding="1" cellspacing="1" class="box">
<tr>
<td width="246">
<input type="hidden" name="MAX_FILE_SIZE" value="2000000">
<input name="userfile" type="file" id="userfile">
</td>
<td width="80"><input name="upload" type="submit" class="box" id="upload" value=" Upload "></td>
</tr>
</table>
</form>
<?php
if(isset($_POST['upload']) && $_FILES['userfile']['size'] > 0)
{
$fileName = $_FILES['userfile']['name'];
$tmpName = $_FILES['userfile']['tmp_name'];
$fileType = $_FILES['userfile']['type'];
$fileSize = $_FILES['userfile']['size'];
$fp = fopen($tmpName, 'r');
$content = fread($fp, filesize($tmpName));
$content = addslashes($content);
fclose($fp);
if(!get_magic_quotes_gpc())
{
$fileName = addslashes($fileName);
}
$query = "INSERT INTO upload (name, type, size, content) ".
"VALUES ('$fileName', '$fileType', '$fileSize', '$content')";
mysql_query($query) or die('Error, query failed');
echo "<br>File $fileName uploaded<br>";
}
?>'
(DOWNLOAD.PHP)FILE
'<?php
$dbname="upload";
$host="localhost";
$user="SELF";
$pass="PICME";
$link = mysql_connect($hostname, $user, $pass);
mysql_select_db($dbname, $link);
$query = "SELECT id, name FROM upload";
$result = mysql_query($query) or die('Error, query failed');
if(mysql_num_rows($result) == 0)
{
echo "Database is empty <br>";
}
else
{
while(list($id, $name) = mysql_fetch_array($result))
{
?>
<?php echo urlencode($name);?> <br>
<?php
}
}
exit;
?>
<?php
$dbname="upload";
$host="localhost";
$user="SELF";
$pass="PICME";
$link = mysql_connect($hostname, $user, $pass);
mysql_select_db($dbname, $link);
$query = "SELECT id, name FROM upload";
if(isset($_GET['id']))
{
// if id is set then get the file with the id from database
$id = $_GET['id'];
$query = "SELECT name, type, size, content " .
"FROM upload WHERE id = '$id'";
$result = mysql_query($query) or die('Error, query failed');
list($name, $type, $size, $content) = mysql_fetch_array($result);
$content = $row['content'];
header("Content-Disposition: attachment; filename=$name");
header('Content-type: image/jpeg' . $type); // 'image/jpeg' for JPEG images
header('Content-Length:' . $size);
exit;
print $content;
ob_clean();
flush();
echo $content;
}
?>

It seems you are not validating the Mime type of the file while uploading and setting Mimetype for JPEG while downloading.
Please make sure you are uploading the correct file format.
Also, the id is urlencoded but not decoded while retrieving from DB.

Related

Opening a Downloaded file in a PHP and mysql does not work

Hi I'm trying make an application that uploads then download the file but I'm having a problem in opening a file except for the txt file. I get an error that says"failed to open".
Please help me to fix this problem so I provided my code.
Thank you.
so here's my code:
upload.php
<?php 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);
}
include_once 'dbConnect.php';
$query = "INSERT INTO gravator (name, size, type, content ) ".
"VALUES ('$fileName', '$fileSize', '$fileType', '$content')";
mysqli_query($conn,$query) or die('Error, query failed');
echo " File $fileName uploaded";
}
?>
<form method="post" enctype="multipart/form-data">
<table width="350" border="0" cellspacing="1" cellpadding="1">
<tbody>
<tr>
<td width="246">
<input type="hidden" name="MAX_FILE_SIZE" value="2000000" />
<input id="userfile" type="file" name="userfile" /></td>
<td width="80"><input id="upload" type="submit" name="upload" value="Upload
" /></td>
</tr>
</tbody>
</table>
</form>
upload.php
<?php
include_once 'dbConnect.php';
$sql = "Select * from gravator";
$res = mysqli_query($conn,$sql) or die('Error, query failed');
if(isset($_GET['id'])) { // if id is set then get the file with the id from
database
$id = $_GET['id'];
$query = "SELECT name, type, size, content FROM gravator WHERE id = $id";
$result = mysqli_query($conn,$query) or die('Error, query failed');
list($name, $type, $size, $content) =
mysqli_fetch_array($result);
header("Content-length: $size");
header("Content-type: $type");
header("Content-Disposition: attachment; filename=$name");
echo $content; exit;
}
?>
<?php
$query = "SELECT id, name FROM gravator";
$result = mysqli_query($conn,$query) or die('Error, query failed');
if(mysqli_num_rows($result) == 0)
{
echo "Database is empty";
}
else
{
while(list($id, $name) = mysqli_fetch_array($result))
{
?>
<?php echo $name; ?>
<?php
}
}
?>

Upload Download from mysql php

I've made use of a script which is available online. The File upload.php allows the user to upload a file and then store the selected file in the MySQL database.
Later the download.php script displays the links for all the files stored in the database. When the user clicks the link, the file should be downloaded. I've enclosed the script below.
But the problem is, I am not using any upload.php nor download .php.
I have tried this in wordpress using "php code for post (Only shortcode placed ion the page)" at one shot.
<?php
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'];
$fileType = (get_magic_quotes_gpc() == 0 ? mysql_real_escape_string(
$_FILES['userfile']['type']) :
mysql_real_escape_string(stripslashes($_FILES['userfile'])));
$fp = fopen($tmpName, 'r');
$content = fread($fp, filesize($tmpName));
$content = addslashes($content);
fclose($fp);
if(!get_magic_quotes_gpc())
{
$fileName = addslashes($fileName);
}
mysql_connect("localhost","*****","***");
mysql_select_db("****");
$query = "INSERT INTO wp3_cte (FileupName, size, type, content ) ".
"VALUES ('$fileName', '$fileSize', '$fileType', '$content')";
mysql_query($query) or die('Error, query failed');
echo "File $fileName uploaded";
}
?>
<form method="post" enctype="multipart/form-data">
<table width="350" border="0" cellspacing="1" cellpadding="1">
<tbody>
<tr>
<td width="246">
<input type="hidden" name="MAX_FILE_SIZE" value="2000000" />
<input id="userfile" type="file" name="userfile" /></td>
<td width="80"><input id="upload" type="submit" name="upload" value=" Upload " /></td>
</tr>
</tbody>
</table>
</form>
<html>
<head>
<title>Download File From MySQL Database</title>
<meta http-equiv="Content-Type" content="text/html;
charset=iso-8859-1">
</head>
<body>
<?php
mysql_connect("localhost","**********","**********");
mysql_select_db("**********");
$query = "SELECT id, FileupName FROM wp3_cte";
$result = mysql_query($query) or die('Error, query failed');
if (mysql_num_rows($result) == 0) {
echo "Database is empty <br>";
} else {
while (list($id, $name) = mysql_fetch_array($result)) {
?>
<a href="download.php?id=<?php echo urlencode($id); ?>"
><?php echo urlencode($name); ?></a> <br>
<?php
}
}
mysql_close();
?>
</body>
</html>
<?php
if (isset($_GET['id'])) {
mysql_connect("localhost","**********","**********");
mysql_select_db("**********");
$id = $_GET['id'];
$query = "SELECT FileupName, type, size, content"FROM wp3_cte WHERE id = '$id'";
$result = mysql_query($query) or die('Error, query failed');
list($name, $type, $size, $content) = mysql_fetch_array($result);
header("Content-length: $size");
header("Content-type: $type");
header("Content-Disposition: attachment; filename=$name");
ob_clean();
flush();
echo $content;
mysql_close();
exit;
}
?>
The problem i am facing is in this peace of code:`download.php`.
Uploaded file is showing properly if i click on download file blank page appears.
Id is displayed in Url
The uploaded file is saving in some folder named upload in ftp server i tried a lot but i was out with no result.
can any one help me Thanks in advance!!!!

Unable to upload image with php

I am trying to upload an image with php; but seems doesn't work, and I can't figure out why. When I try to insert only text without an image, it is working fine (I mean if I remove from php part all code for the image uploads); so I guess the error is in this part, but I can't find it.
This is the upload code that I currently use. Any help with this is appreciated.
if (isset($_POST['add'])) {
$text = $_POST['text'];
$title = $_POST['title'];
$category = $_POST['category'];
$fileName = $_FILES['userfile']['userfile'];
$tmpName = $_FILES['userfile']['tmp_name'];
// make a new image name
$ext = substr(strrchr($fileName, "."), 1);
// generate the random file name
$randName = md5(rand() * time());
// image name with extension
$myFile = $randName . '.' . $ext;
// save image path
$path = "/img/" . $myFile;
$result = move_uploaded_file($tmpName, $path);
if (!$result) {
echo "Error uploading image file <br />";
var_dump($_FILES);
exit;
} else {
$db = new mysqli("localhost", "user", "mypass", "mydb");
if (mysqli_connect_errno()) {
printf("Connect failed: %s<br/>", mysqli_connect_error());
}
mysqli_set_charset($db, "UTF8");
$query = "INSERT INTO posts (post_text, image_name, post_image, post_title, category) VALUES (?, ?, ?, ?, ?)";
$conn = $db->prepare($query);
if ($conn == TRUE) {
$conn->bind_param("ssssi",$text, $myFile, $path, $title, $category);
if (!$conn->execute()) {
echo 'error insert';
} else {
header("Location: index.php");
exit;
}
} else {
die("Error preparing Statement");
}
}
} else {
echo 'error';
}
And here is the form for the upload
<form method="post" action="postblog.php" enctype="multipart/form-data">
Title: <input type="text" name="title" id="title">
Category: <select name="category" id="category">
Desc :<br />
<textarea id="text" name="text" rows="15" cols="80" style="width: 80%"></textarea>
Image: <input type="file" name="userfile" />
<input type="submit" name="add" id="add" value="Добави">
</form>
The error is from here:
if (!$result) { echo "Error uploading image file "; }
change
$fileName = $_FILES['userfile']['userfile']; to $fileName = $_FILES['userfile']['name'];

strip slashes error in file upload

i get the below error msg for the code given below
"Warning: stripslashes() expects parameter 1 to be string, array given in /home/stthohuu/public_html/forms/upload_newsletter.php on line 32"
can you please guide me.. am not aware of file upload processes.. please share your suggestions
<html>
<head></head>
<body>
<form method="post" enctype="multipart/form-data">
<table width="350" border="0" cellpadding="1"
cellspacing="1" class="box">
<tr>
<td><h4>Please select a file</h4></td></tr>
<tr>
<td>
<input type="hidden" name="MAX_FILE_SIZE"
value="16000000">
<input name="userfile" type="file" id="userfile">
</td>
<td width="80"><input name="upload"
type="submit" class="box" id="upload" value=" Upload "></td>
</tr>
</table>
</form>
Back
</body>
</html>
<?php
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'];
$fileType=(get_magic_quotes_gpc()==0 ? mysql_real_escape_string(
$_FILES['userfile']['type']) : mysql_real_escape_string(
stripslashes ($_FILES['userfile'])));
$fp = fopen($tmpName, 'r');
$content = fread($fp, filesize($tmpName));
$content = addslashes($content);
fclose($fp);
if(!get_magic_quotes_gpc())
{
$fileName = addslashes($fileName);
}
$con = mysql_connect('localhost', 'stthohuu_batch', 'abc') or die(mysql_error());
$db = mysql_select_db('stthohuu_church', $con);
/* identify the max id in existing data*/
$max_id[0]='';
$sql="SELECT id FROM newsletter WHERE id=(SELECT max(id) FROM newsletter)";
$result = mysql_query($sql);
$max_id = mysql_fetch_array($result);
if ($max_id[0]=='')
{
$max_id[0]=0;
}
$id=0;
$id=$max_id[0]+1;
/* to insert data into newsletter table */
if($db){
$query = "INSERT INTO newsletter (name, size, type, content ) ".
"VALUES ('$fileName', '$fileSize', '$fileType', '$content')";
mysql_query($query) or die('Error, query failed');
mysql_close();
echo "<br>File $fileName uploaded<br>";
}else { echo "file upload failed"; }
}
?>
This s workin well in local xampp.. But NOT in web server.. :(
you are passing $_FILES['userfile'] array to stripslashes, pass $_FILES['userfile']['name'] or $_FILES['userfile']['tmp_name']
Replace
stripslashes ($_FILES['userfile'])));
to
stripslashes ($_FILES['userfile']['name'])));
stripslashes is string function and you are trying to pass file in it.

Upload and Download Php MySQL Script

I've made use of a script which is available online. The File upload.php allows the user to upload a file and then store the selected file in the MySQL database. Later the download.php script displays the links for all the files stored in the database. When the user clicks the link, the file should be downloaded. I've enclosed the script below. But the problem is, when I click the link the content of the file gets displayed instead of getting downloaded.
upload.php
<!--
CREATE TABLE IF NOT EXISTS `upload` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(30) NOT NULL,
`type` varchar(30) NOT NULL,
`size` int(11) NOT NULL,
`content` longblob NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=5 ;
-->
<html>
<head></head>
<body>
<form method="post" enctype="multipart/form-data">
<table width="350" border="0" cellpadding="1"
cellspacing="1" class="box">
<tr>
<td>please select a file</td></tr>
<tr>
<td>
<input type="hidden" name="MAX_FILE_SIZE"
value="16000000">
<input name="userfile" type="file" id="userfile">
</td>
<td width="80"><input name="upload"
type="submit" class="box" id="upload" value=" Upload "></td>
</tr>
</table>
</form>
</body>
</html>
<?php
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'];
$fileType = (get_magic_quotes_gpc() == 0 ? mysql_real_escape_string(
$_FILES['userfile']['type']) : mysql_real_escape_string(
stripslashes($_FILES['userfile'])));
$fp = fopen($tmpName, 'r');
$content = fread($fp, filesize($tmpName));
$content = addslashes($content);
fclose($fp);
if (!get_magic_quotes_gpc()) {
$fileName = addslashes($fileName);
}
$con = mysql_connect('localhost', 'root', 'root') or die(mysql_error());
$db = mysql_select_db('test', $con);
if ($db) {
$query = "INSERT INTO upload (name, size, type, content ) " .
"VALUES ('$fileName', '$fileSize', '$fileType', '$content')";
mysql_query($query) or die('Error, query failed');
mysql_close();
echo "<br>File $fileName uploaded<br>";
} else {
echo "file upload failed";
}
}
?>
Download.php
<html>
<head>
<title>Download File From MySQL Database</title>
<meta http-equiv="Content-Type" content="text/html;
charset=iso-8859-1">
</head>
<body>
<?php
$con = mysql_connect('localhost', 'root', 'root') or die(mysql_error());
$db = mysql_select_db('test', $con);
$query = "SELECT id, name FROM upload";
$result = mysql_query($query) or die('Error, query failed');
if (mysql_num_rows($result) == 0) {
echo "Database is empty <br>";
} else {
while (list($id, $name) = mysql_fetch_array($result)) {
?>
<a href="download.php?id=<?php echo urlencode($id); ?>"
><?php echo urlencode($name); ?></a> <br>
<?php
}
}
mysql_close();
?>
</body>
</html>
<?php
if (isset($_GET['id'])) {
$con = mysql_connect('localhost', 'root', 'root') or die(mysql_error());
$db = mysql_select_db('test', $con);
$id = $_GET['id'];
$query = "SELECT name, type, size, content " .
"FROM upload WHERE id = '$id'";
$result = mysql_query($query) or die('Error, query failed');
list($name, $type, $size, $content) = mysql_fetch_array($result);
header("Content-length: $size");
header("Content-type: $type");
header("Content-Disposition: attachment; filename=$name");
ob_clean();
flush();
echo $content;
mysql_close();
exit;
}
?>
download.php is displaying all the HTML at the top even when the user has selected a file to download. You need to put that entire section in an if so it doesn't get put at the beginning of the download:
if (!isset($_GET['id']) { ?>
<html>
...
</html>
<?php } else {
$con = mysql_connect('localhost', 'root', 'root') or die(mysql_error());
... // rest of script
}

Categories