Uploading an image to the database - php

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)
);

Related

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

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
}

inserting image into mysql using php

I'm trying to insert uploaded image into mysql with the user's user_id from session variable. I found an online tutorial and changed it as below:
<?php
require_once('../Login/includes/session_timeout_db.inc.php');
$dbuser="";
$dbname="";
$dbpass="";
$dbserver="";
$con = mysql_connect($dbserver,$dbuser,$dbpass);
if (!$con){ die('Could not connect: ' . mysql_error()); }
mysql_select_db($dbname, $con);
// Make sure the user actually
// selected and uploaded a file
if (isset($_FILES['image']) && $_FILES['image']['size'] > 0) {
// Temporary file name stored on the server
$tmpName = $_FILES['image']['tmp_name'];
// Read the file
$fp = fopen($tmpName, 'r');
$data = fread($fp, filesize($tmpName));
$data = addslashes($data);
fclose($fp);
// Create the query and insert
// into our database.
$query = "INSERT INTO images, owner_id";
$query .= "(image) VALUES ('$data', '.$_SESSION['id'].')";
$results = mysql_query($query, $link);
// Print results
print "Thank you, your file has been uploaded.";
}
else {
print "No image selected/uploaded";
}
// Close our MySQL Link
mysql_close($link);
?>
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Strict//EN”
“http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd”>
<html xmlns=”http://www.w3.org/1999/xhtml”>
<head>
<meta http-equiv=”Content-Type” content=”text/html; charset=utf-8” />
<title>Manage Tasks</title>
<link rel="stylesheet" type="text/css" href="../allcss/style.css" />
</head>
<body>
<?php
require('../Login/includes/header.inc.php');
?>
<div id="content">
<form enctype="multipart/form-data" action="" method="post" name="changer">
<input name="MAX_FILE_SIZE" value="102400" type="hidden">
<input name="image" accept="image/jpeg" type="file">
<input value="Submit" type="submit">
</form>
</div>
</body>
</html>
I'm having and error on the second line of my query:
$query = "INSERT INTO images, owner_id";
$query .= "(image) VALUES ('$data', '.$_SESSION['id'].')";
$results = mysql_query($query, $link);
*the error is Parse error: syntax error, unexpected T_ENCAPSED_AND_WHITESPACE, expecting T_STRING or T_VARIABLE or T_NUM_STRING on line 28*
could someone please help?
Thanks in adnvance
Your images field would need to be of type BLOB. Don't do this though, save your files in the filesystem and save the directory path to the image in your database.
change :
"(image) VALUES ('$data', '.$_SESSION['id'].')";
into :
"(image) VALUES ('$data', '".$_SESSION['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.

To upload a image in MySql database via php

I am currently working on a website that needs to upload the images of different products by its users. I am implementing it by using MySql database via php.
My code for a basic form for taking input from users is:
<form enctype="multipart/form-data" action="testimage1.php" method="post" name="changer">
<input name="MAX_FILE_SIZE" value="102400" type="hidden">
<input name="image" accept="image/jpeg" type="file">
<input value="Submit" type="submit">
</form>
My database table is:
mysql> CREATE TABLE tbl_images (
> id tinyint(3) unsigned NOT NULL auto_increment,
> image blob NOT NULL,
> PRIMARY KEY (id)
> );
testimage1.php has the following code:-
$username = "root";
$password = "";
$host = "localhost";
$database = "thinstrokes";
$link = mysql_connect($host, $username, $password);
if (!$link) {
die('Could not connect: ' . mysql_error());
}
// Select your database
mysql_select_db ($database);
if (isset($_FILES['image']) && $_FILES['image']['size'] > 0) {
// Temporary file name stored on the server
$tmpName = $_FILES['image']['tmp_name'];
// Read the file
$fp = fopen($tmpName, 'r');
$data = fread($fp, filesize($tmpName));
$data = addslashes($data);
fclose($fp);
// Create the query and insert
// into our database.
$query = "INSERT INTO tbl_images ";
$query .= "(image) VALUES ('$data')";
$results = mysql_query($query, $link) or die(mysql_error());
// Print results
print "Thank you, your file has been uploaded.";
}
else {
print "No image selected/uploaded";
}
On submitting the form I am getting an error: No image selected/uploaded
I am not getting the error... and I've already asked for this before as:
mysql error during inserting a image in mysql database
How can I insert an image in a MySQL database using PHP?
But until now I am not successful in storing the image in the database.
Your script is working just fine, This is what I test:
<?
if (isset($_FILES['image']) && $_FILES['image']['size'] > 0) {
// Temporary file name stored on the server
$tmpName = $_FILES['image']['tmp_name'];
// Read the file
$fp = fopen($tmpName, 'r');
$data = fread($fp, filesize($tmpName));
$data = addslashes($data);
fclose($fp);
// Create the query and insert
// Print results
print "Thank you, your file has been uploaded.";
}
else {
print "No image selected/uploaded";
}
?>
<form enctype="multipart/form-data" action="" method="post" name="changer">
<input name="MAX_FILE_SIZE" value="102400" type="hidden">
<input name="image" accept="image/jpeg" type="file">
<input value="Submit" type="submit">
</form>
And it works just fine, if you want to see it in action I can send you the link.
It must be something else that is ruining your code (*note that I removed the DB queries to avoid getting mysql errors but the script was working even with them there.
//Here is the solution for your problem
<form enctype="multipart/form-data" action="" method="post" name="changer">
<input name="MAX_FILE_SIZE" value="102400" type="hidden">
<input name="image" accept="image/jpeg" type="file">
<input value="Submit" type="submit">
</form>
<?php
// connection to database
include 'includes/connection.php';
?>
<?php
if (isset($_FILES['image']) && $_FILES['image']['size'] > 0) {
// Temporary file name stored on the server
$tmpName = $_FILES['image']['tmp_name'];
// Read the file
$fp = fopen($tmpName, 'r');
$data = fread($fp, filesize($tmpName));
$data = addslashes($data);
fclose($fp);
$result = mysql_query("INSERT INTO image (image)VALUES ( '$data')", $connection);
if(!$result)
{
die("Database query failed: ". mysql_error());
}
// Print results
print "Thank you, your file has been uploaded.";
}
else
{
print "No image selected/uploaded";
}
?>
<?php
//close connection
include 'includes/close.php';
?>

Categories