Uploading images to MySQL (blob) with PHP - php

For security reasons I've decided that uploading user profile images to a database, rather than just a folder and uploading the image addresses, would be a good idea.
I've never dealt with file uploads in a backend before, but having read up about this from various sources, I believe that I'm doing everything correctly. However no useful binary data is being uploaded.
in php.ini
file_uploads=On
In the frontend
<form enctype="multipart/form-data" method="post" autocomplete="on" action="upload/">
<p>
<input type="file" id="avatar" name="avatar" accept="image/png, image/jpeg" required />
<label for="avatar">*Profile photo</label>
</p>
<p class="submitter two-thirds columns">
<input type="submit" value="Apply" />
</p>
</form>
In the backend
if(isset($_SESSION['id']))
$UserID = $_SESSION['id'];
else exit(1);
if (!empty($_FILES['avatar'])){
$photo = fopen($_FILES['avatar']["tmp_name"], 'rb');
$photo_mime = $_FILES['avatar']["type"];
}
else exit(1);
$values_data = array(
$UserID,
$photo,
$photo_mime,
);
$sql = "INSERT INTO `user`
(
UserID,
photo,
photo_mime
)
VALUES
(
:UserID,
:photo,
:photo_mime
)
ON DUPLICATE KEY UPDATE
photo = :photo,
photo_mime = :photo_mime
";
$sth = $dbh->prepare($sql);
$sth->bindValue(':UserID', $values_data[0]);
$sth->bindValue(':photo', $values_data[1]);
$sth->bindValue(':photo_mime', $values_data[2]);
$sth->execute();
And the database does get some information
However those image binaries are all 1KB. Looking inside them they have data that is like this
Resource id #13
So the binaries are getting messed up or dropped somewhere along the line... but where?

fopen() doesn't return the contents of the file. It returns a file pointer resource, which you then can pass to something like fread() to get the contents.
Something like:
$handler = fopen($_FILES['avatar']["tmp_name"], 'r');
$file = fread($handler, filesize($_FILES['avatar']["tmp_name"]));
fclose($handler);
An easier way would be to use file_get_contents():
$file = file_get_contents($_FILES['avatar']["tmp_name"]);
which will give you the contents in one line.

Related

How to pass POST parameters in a url

Is it possible to upload images/files by sending the POST or REQUEST, parameters in the URL without HTML content?
I created a PHP file that gets a image from my someone, stores that file into the database, and a in a folder on my computer. It works fine but what I want to do now is remove the html content and only allow someone to send the images/files via the URL. I tried using $_GET but I received a lot of errors. I also researched this and read that only $_POST will work.
Here is my PHP source code with HTML but keep in mind, "I want the page blank and the only way for someone to send the images/files is through URL".
PHP:
if(isset($_POST['submit'])){
if(#getimagesize($_FILES['image']['tmp_name']) ==FALSE){
// Select an image
echo "Please select an image.";
}
else{
// THE PATH TO STORE THE UPLOAD IMAGE
$target = "images/".basename($_FILES['image']['name']);
//CONNECT TO DATABASE
$db = mysqli_connect("localhost", "root", "");
mysqli_select_db($db, "magicsever");
if(mysqli_connect_error()){
die ("Database connection error");
}
//GET ALL THE SUBMITTED DATA
$image = $_FILES['image']['tmp_name'];
$name = $_FILES['image']['name'];
//Store te submitted data to database
$sql = "INSERT INTO image_test (name, image)VALUES ('$name','$image')";
$query = mysqli_query($db, $sql);
//Now lets move the uploaded image into the folder
$nullResult = array();
$nullResult['Image'] = (move_uploaded_file($_FILES['image']['tmp_name'], $target))? "Successful": "Unsuccessful";
echo json_encode($nullResult);
}
}
HTML:
<form action="index.php" method="post" enctype="multipart/form-data">
<input type="file" name="image">
<br></br>
<input type="submit" name="submit" value="Upload">
</form>
$_POST['']; Parameters come from the usually the form that has the method set to POST, like yours has, that input type you have (file, named image) will be returned has $_POST['image'], $_REQUEST on the other hand is the "GET" method, it works in the same way, the only difference is it's not secure and it comes in the url. I would recommend using POST to be honest. Also use PDO because your code is vulnerable to SQL injection. (mentioned by Alex Howansky)

Fail to upload picture into existing row in the table

I have a booking table which contain file_name and file_path, I need to upload a picture into the user row based on the noic, after I select a picture and click the upload button, it show upload success, but in the database doesn't have the picture and picture name.
$target = "upload/";
$target = $target . basename( $_FILES['file']['name']);
//This gets all the other information from the form
$file=basename( $_FILES['file']['name']);
$filename=$_POST['file_name'];
//Writes the file to the server
if(move_uploaded_file($_FILES['file']['tmp_name'], $target)) {
//Tells you if its all ok
echo "The file ". basename( $_FILES['file']['name']). " has been uploaded, and your information has been added to the directory";
// Connects to your Database
//Writes the information to the database
mysql_query("UPDATE INTO booking (file_path,file_name)
VALUES ('$file', '$filename') WHERE noic = '$_SESSION[noic]'") ;
} else {
//Gives and error if its not
echo "Sorry, there was a problem uploading your file.";
}
<form enctype="multipart/form-data" action="userstatus.php" method="POST">
<p> File Name :
<input style="background:grey;" type="text" name="file_name" value="" >
</p>
<p>
<input type="file" name="file" >
</p>
<p>
<input type="submit" name="submit" value="Upload file" style="background:grey;">
</p>
</form>
Your MySQL query is incorrect, it should be UPDATE SET... MySQL Insert statement does not support the WHERE clause so your query will fail if you directly replace UPDATE with INSERT, make the following changes,
//Writes the information to the database
mysql_query("UPDATE booking SET file_path='$file',
file_name='$filename' WHERE noic = '$_SESSION[noic]'") ;
}
NOTE: PLEASE AVOID USING php mysql* class for database queries, it has been deprecated and should not be used, Switch to PDO or MySQLi. PDO reference - http://php.net/manual/en/book.pdo.php
Have you tried to run your query
UPDATE INTO booking (file_path,file_name) VALUES ('$file', '$filename') WHERE noic = '(replace here the noic you want)'
On phpMyAdmin or MySql Workbench??
Why don't you try to run the query like this:
UPDATE booking SET file_path = '$file', SET file_name= '$filename' WHERE noic = '$_SESSION[noic]'
Also check If you have set the 775 permission to the /upload folder..
Hope I help you!

Cannot store picture in database(no error messages appear)

Hello I am here yet again with another problem.
As I followed a tutorial I tried to save images to my database. It all worked fine and dandy with no error messages but for some reason the image refuse the get stored. Nothing show up at all!
<html>
<body>
<form action="test.php" method="POST" enctype="multipart/form-data">
<input type="file" name="image"><input type="submit" name="submit" value="Upload" />
</form>
<?php
if(isset($_POST['submit'])) {
mysql_connect("localhost","root","") or die("Could not find database!");
mysql_select_db("Image") or die("Could not find database!");
$imageName = mysql_real_escape_string($_FILES["image"]["name"]);
$imageData = mysql_real_escape_string(file_get_contents($_FILES["image"]["tmp_name"]));
$imageType = mysql_real_escape_string($_FILES["image"]["type"]);
if(substr($imageType,0,5) == "image") {
mysql_query("INSERT INTO 'blob' VALUES ('','$imageName','$imageData')");
echo "File uploaded!";
}
else
{
echo "Only images are allowed!";
}
}
?>
</body>
</html>
Database:
id, name, image:
int(Auto increment), varchar(40), mediumblob(because of the size)
The only odd thing about this is that "file_get_contents" is blacked out(I use notepad++).
Otherwise I don't see whats wrong, I have checked guides and whatnot but the thing is that I need to use this method in another form that have a large amount of information stored(15 fields including a description). I am still very new to this and its hard to know what to keep and how to write the best way. But anyway if you can help me it would be awesome.
If you have any questions regardning anything or just some tips just comment.
Your table name blob should be surrounded by back-ticks, not apostrophes.
However, I recommend that you change the name of this table to something that is not a reserved word in MySQL.

Error while displaying images from mysql php using blob datatype

I am trying to display images from my mysql database using php. The image is not getting displayed fully. It gets cut while trying to display an image more than 200 kb (determined from trials , but not too sure).
HTML Code:
<form enctype="multipart/form-data" action="insertimage.php" method="post" name="changer">
<input name="MAX_FILE_SIZE" value="10240000" type="hidden">
<input name="image" accept="image/jpeg|image/jpg|image|JPG|image/png|image/gif" type="file">
<input value="Submit" type="submit">
PHP Code:
<?php
require('myconnect.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);
// Create the query and insert
// into our database.
$query = "Update whyangry.posts set Photo='$data' where Pid=2";
$results = mysql_query($query, $con);
// Print results
print "Thank you, your file has been uploaded.";
$sql = "SELECT * FROM helpme.posts WHERE Pid=2";
$res = mysql_query($sql,$con);
while ($res1=mysql_fetch_assoc($res))
{
$content = $res1['Photo'];
$id=$res1['Pid'];
}
echo '<img src="data:image/png|image/jpeg|image/gif;base64,' . base64_encode( $content ) . '" />';
echo 'Hello world.';
}
else {
print "No image selected/uploaded";
}
?>
Also i am getting the below error while uploading file in phpmyadmin to a blob datatype
UPDATE `helpme`.`posts` SET `Photo` = 0xffd8ffe000104a46494600010201006000600000ffe10f074578696600004d4d002a0000000800060132000200000014000000564746000300000001000300004749000300000001003200009c9d00010000000e00000000ea1c0007000007f40000000087690004000000010000006a000000d4323030393a30333a31322031333a34373a34330000059003000200000014000000ac9004000200000014000000c0929100020000000335340000929200020000000335340000ea1c0007000007b40000000000000000323030383a30333a31342031333a35393a323600323030383a30333a31342031333a35393a3236000005010300030000000100060000011a00050000000100000116011b0005000000010000011e020100040000000100000126020200040000000100000dd90000000000000048000000010000004800000001ffd8ffe000104a46494600010100000100010000ffdb004300100b0c0e0c0a100e0d0e1211101318281a181616183123251d283a333d3c3933383740485c4e404457453738506d51575f626768673e4d71797064785c656763ffdb0043011112121815182f1a1a2f634238426363636363636363636363636363636363636363636363636363636363636363636363636363636363636363636363[...]
MySQL said:
2006 - MySQL server has gone away
Please let me know how to fix the issue. The issue is while displaying images. Whether some size issue is there i dont know please help here.
Using addslashes is nowhere near the correct way to do a SQL query. It will not always work correctly with binary data. I don't know what resource you're using, but it's teaching you very bad habits.
Please DO NOT USE mysql_query in new applications. This is a legacy interface from the 1990s that is in the process of being retired because of the hazards involved in using it incorrectly, something all too easy to do. It's best to use either mysqli or PDO in new projects.
Your query should look like this:
Update whyangry.posts set Photo=? where Pid=?
You can bind to those placeholders when executing the query and avoid having encoding problems. There are many examples on how to do this correctly.

How to save image in MYSQL database without post method?

I want to save gif type image in mySQL database without post method.
<form action="add_file.php" method="post" enctype="multipart/form-data">
<input type="file" name="uploaded_file"><br>
<input type="submit" value="Upload file">
</form>
I want to upload file by php code only. for example:
// Gather all required data
$name = $File_Name;
$mime = $File_Type;
$data = $File_Data;
$size = $File_Size;
// Create the SQL query
$query = "
INSERT INTO `file` (
`name`, `mime`, `size`, `data`, `created`
)
VALUES (
'{$name}', '{$mime}', {$size}, '{$data}', NOW()
)";
I have more then 21,0000 image in my local. I want to save image in loop.
Upload the files using FTP, then write a little PHP script that you run only once
that loops through the folder and adds the images to the database.
Make sure to remove the php file after it is done, so that you don't run it again accidentally ;)

Categories