Upload and Download Php MySQL Script - 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, 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
}

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!!!!

How to insert an image?

Following is my code file...
I am not able to insert the image. Getting an error as, Undefined variable: image
<html>
<head>
<title> Upload an image </title>
</head>
<body>
<form action="image-disp.php" method="post" enctype="multipart/form-data">
File:
<input type="file" name="image" value=iamge><br>
<input type="submit" value="Upload">
</form>
<?php
mysql_connect("localhost", "root", " ") or die(mysql_error());
mysql_select_db("mysql") or die(mysql_error());
echo "connected";
if (!isset($_FILES['image'] ['tmp_name'])) {
echo "Choose an image";
} else {
echo $image = addslashes($_FILES['image'] ['tmp_name']);
echo $image_name = addslashes($_FILES['image']['name']);
echo $image_size = getimagesize($_FILES['image'] ['tmp_name']);
}
if ($image_size = FALSE) {
echo "It's not an image";
} else {
$result = "INSERT INTO testblob (image_id, image, image_size) "
. "VALUES (' ' ,'$image', '$image_size')";
}
echo "inserted";
?>
</body>
</html>
better save just the name of the image in database, and the file in some folder
$result = "INSERT INTO testblob ( image, image_size)
VALUES ('$image_name', '$image_size')";
then you retrieve it like that:
<img src="path/<?php echo $row['image_name'];?>">
First create a table.
Mysql-Query
CREATE TABLE storeimage ( image_id tinyint(3) NOT NULL AUTO_INCREMENT, image blob NOT NULL, KEY image_id (image_id) ) ENGINE=MyISAM DEFAULT CHARSET=latin1;
Code to store image in database:
<html>
<body>
<form action="image-disp.php" method="POST" enctype="multipart/form-data">
File:
<input type="file" name="image" method="POST">
<input type="submit" value="submit" name= "submit">
</form>
<?php
mysql_connect("localhost", "root", "root") or die (mysql_error());
mysql_select_db("mysql") or die (mysql_error());
if (isset($_FILES['image']['tmp_name']))
{
$image = addslashes(file_get_contents($_FILES['image']['tmp_name']));
$image_name = $_FILES['image']['name'];
}
if(isset($_POST['submit']))
{
$insert = mysql_query("INSERT INTO storeimage VALUES ('', '$image')");
echo " file inserted";
}
?>
</body>
</html>
Your error is coming from PHP, not MySQL. It's saying your variable, $image, isn't defined because it's not filled with anything.
Your code isn't going to store the actual image, but instead, the filename.
You need to remove the space.
echo $image = addslashes($_FILES['image']['tmp_name']);
Also, you don't even have it executing a query...
if ($image_size == FALSE) {
echo "It's not an image";
} else {
$result = mysql_query("INSERT INTO testblob (image_id, image, image_size) "
. "VALUES (' ' ,'$image', '$image_size')");
}
Take a look here for a basic example: http://www.w3schools.com/php/php_file_upload.asp

Uploading an image to the database

This is the code for the upload form to enable me to upload an image to the database
<html>
<head>
<title>File Uploading Form</title>
</head>
<body>
<h3>File Upload:</h3>
Select a file to upload: <br />
<form action="file_uploader.php" method="post" enctype="multipart/form-data">
<input type="file" name="file" size="50" />
<br />
<input type="submit" value="Upload File" />
</form>
</body>
</html>
This is the code that I have in a in a file called file_uploader.php. When trying to complete this I get the error Could not copy file!
<?php
if( $_FILES['file']['name'] != "" )
{
copy( $_FILES['file']['name'], "databasehostdetails" ) or
die( "Could not copy file!");
}
else
{
die("No file specified!");
}
?>
<html>
<head>
<title>Uploading Complete</title>
</head>
<body>
<h2>Uploaded File Info:</h2>
<ul>
<li>Sent file: <?php echo $_FILES['file']['name']; ?>
<li>File size: <?php echo $_FILES['file']['size']; ?> bytes
<li>File type: <?php echo $_FILES['file']['type']; ?>
</ul>
</body>
</html>
You need to use tmp_name. Also, what is databasehostdetails? The second parameter is the destination (where you want to copy the file to).
copy($_FILES['file']['tmp_name'], DESTINATION_PATH);
Here is a simple way to do this. I am giving you my script
index.html
But be carefull:
It is not recommended since it is to costly for your database to store files
Fix any sql injection vurnelabilities. I my self don't know how to do this. You can make a research and fix it.
Also check out here Storing Images in DB - Yea or Nay?
However the code works pretty good if it not a large scale application and no sql injection attacks could happen.
<html>
<body>
<form method="post" enctype="multipart/form-data" action="doupload.php">
<input type="hidden" name="MAX_FILE_SIZE" value="2000000">
<input name="userfile" type="file" id="userfile">
<input name="upload" type="submit" id="upload" value=" Upload ">
</form>
</body>
</html>
doupload.php
<?php
include("config.php");
$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);
}
$query = "INSERT INTO upload set name='".$fileName."', size='".$fileSize."', type='".$fileType."', content='".$content."'";
mysql_query($query) ;
?>
getuploaded.php
<?php
// select records from database if exists to display
include("config.php");
$query1 = "SELECT id, name FROM upload";
$result1 = mysql_query($query1) or die('Error, query failed');
if(mysql_num_rows($result1)>0)
{
while(list($id, $name) = mysql_fetch_array($result1))
{
?>
<?php echo $name;?> <br>
<?php
}
}
?>
download.php
<?php
//header("Content-type: $type");
include("config.php");
$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");
echo $content;
?>
config.php
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die('Error connecting to mysql');
$dbname = 'uploadfile';
mysql_select_db($dbname);
?>
Createing the table
CREATE TABLE upload (
id INT NOT NULL AUTO_INCREMENT,
name VARCHAR(30) NOT NULL,
type VARCHAR(30) NOT NULL,
size INT NOT NULL,
content MEDIUMBLOB NOT NULL,
PRIMARY KEY(id)
);

PHP upload to MySQL database with download and view file

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.

Categories