I have a php script, which uploads pictures to a mysql database. The images are taken within the browser. I would like to compress them before uploading, but I'm not quite sure how exactly to compress the uploaded data. What I've got for the moment is this:
if(isset($_FILES['userfile']) && $_FILES['userfile']['size'] > 0)
{
//$positiony = $_POST['posy'];
$fileName = $_FILES['userfile']['name'];
$tmpName = $_FILES['userfile']['tmp_name'];
$fp = fopen($tmpName, 'r');
$content = fread($fp, filesize($tmpName));
$content = addslashes($content);
$content = imagejpeg($content,null,50);
fclose($fp);
if(!get_magic_quotes_gpc())
{
$fileName = addslashes($fileName);
}
$query = "INSERT INTO upload (team_name, id, display, content) ".
"VALUES ('$team_name', 'null', '1', '$content')";
mysql_query($query) or die('Error, query failed'.mysql_error());
echo "<br>File $fileName uploaded<br>";
}
The image uploading works fine, but the uploaded images are broken. Introducing imagejpeg as a form of compressing has caused the issues. Should I be using it on something else?
Most images are already compressed so there is no need to "compress them further".
Storing them in a database is not a recommended thing to do. Just upload them to a location on the server and save the path to that location.
Related
I am currently having problems with displaying image from mysql database. I am able to upload an image to mysql database, however if i want to retrieve it from the database, it is displayed in Gibberish text.
Here is upload.php
if (isset($_FILES['image']) && $_FILES['image']['size'] > 0) {
$filename = mysqli_real_escape_string($mysqli,$_FILES['image']['name']);
$tmpName = $_FILES['image']['tmp_name'];
$fp = fopen($tmpName, 'r');
$data = fread($fp, filesize($tmpName));
$data = addslashes($data);
fclose($fp);
$query = "INSERT INTO `TABLES` (`image`)
VALUES( NULL,'$data')";
$result = $mysqli->query($query);
}
View.php
$mysqlquery = "SELECT * FROM TABLE";
$results = $mysqli->query($mysqlquery);
if($results->num_rows > 0){
while ($row = $results ->fetch_assoc()){
echo '<div align = "center">';
echo "<b>".$row["image"]. "<br></b>";
header("Content-type: image/jpeg");
}
}
Try this and do not forget to give image path before source
echo "<img src='your image location directory/". $row['image'] .'" >";
Oooooh... I just wish I had the answer to this one...
Some thoughts, though.
First, from personal experience I urge against storing images in the database. For one thing, your database backups will quickly become ridiculous. A more common, and better, approach is to store the images in the file system and store only the location (e.g. /img/pic03.jpg ) of the image in the database.
Next, I see you are modifying the received binary data:
$tmpName = $_FILES['image']['tmp_name'];
$fp = fopen($tmpName, 'r');
$data = fread($fp, filesize($tmpName));
$data = addslashes($data);
fclose($fp);
Perhaps you know something that I don't (it's not difficult), but generally, if you gerfingerpoke with binary image data you get ... um... gibberish. Try disabling those lines and see what happens.
I'm studying on MySQL & PHP, and for my first production I've started to work on a review panel. You can simply upload your product reviews to the database and browse them later on, directly from the panel, which in this case is a local website.
The problem is, I can't figure out how to rule over every file format on upload, except .pdf! To be more clear: I only want my upload form to accept .pdf files to be uploaded. At the moment it doesn't restrict anything, here is my code:
<?php
if(isset($_POST['upload']) && $_FILES['userfile']['size'] > 0)
{
$revName = $_POST['revname'];
$revRating = $_POST['rating'];
$revRecommend = $_POST['recommend'];
$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);
}
rename($tmpName,"C:\\xampp\\htdocs\\ReviewArchieve\\files\\reviews\\".$fileName);
include 'include/config.php';
include 'include/opendb.php';
$query = "INSERT INTO files (revname, rating, recommend, name, size, type, content)".
"VALUES ('$revName', '$revRating', '$revRecommend', '$fileName', '$fileSize', '$fileType', '$content')";
mysql_query($query) or die('Error, query failed'.mysql_error());
include 'include/closedb.php';
echo "<br>File $fileName uploaded<br>";
}
?>
Got it working!
Thanks to the MIME refer, I managed to learn something new, and accomplished my task with a little bit of investigation! It was not the part of code offered in the correct answer, that did not work at all in my case, no matter what I did, but instead, I used this method:
I noticed I have already included the file type.
$fileType = $_FILES['userfile']['type'];
So now I just had to make an if from it, like this:
if($fileType == 'application/pdf') {
*** Code to be driven here, same as above on the original code ***
}
else {
echo "Invalid file, upload interrupted!";
}
Answer:
....
if(isset($_POST['upload']) && $_FILES['userfile']['size'] > 0)
{
$tmpName = $_FILES['userfile']['tmp_name'];
if (mime_content_type($tmpname) != 'application/pdf') {
die("uploaded file not valid");
}
....
You have a number of problems here the biggest are:
SQL Injection. You must sanitize your user inputs or little bobby tables will visit you. Think about using parametrized queries
You should check the file's mimetype.
http://www.php.net//manual/en/function.mime-content-type.php works out the box although is deprecated. You should use fileinfo.
I have an image file which is stored onto database as a blob (shown in the code). Once resized to 80*80(thumbnail) I need to store it onto some other database. I have resized and saved it as a file but I couldn't store the resized image onto database. How can I achieve this?
//resize image and save
include('MyImage.php');
$image = new MyImage();
$image->load($tmpName);
$image->resize(80,80);
$image->save('thumbnail.jpg');
//storing original image onto database
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);
}
$query = "INSERT INTO image_tbl (name, size, type, content )".
"VALUES ('$fileName', '$fileSize', '$fileType', '$content')";
mysql_query($query) or die('Error, query failed');
}
The direct question to your answer is
//This goes after the frist block, after "$image->save('thumbnail.jpg');"
$fileSize=filesize('thumbnail.jpg')
$fp = fopen('thumbnail.jpg', 'rb');
$content = fread($fp, $fileSize);
$content = addslashes($content);
fclose($fp);
$query = "INSERT INTO image_tbl (name, size, type, content )".
"VALUES ('thumbnail.jpg', '$fileSize', 'image/jpeg', '$content')";
mysql_query($query) or die('Error, query failed');
You might recognize some elements of that code :-)
But believe me, you do not want this:
Storing BLOBs in the DB, that the DB doesn't understand is a bad idea
using strings and addslashes to achieve it, is very close to the worst case possible: You read the image into a string consisting of ca 50% unprintables, backslash it, transport it to the DB, where it is unbackslashed and parsed. Use prepared statements with parameters (if you really want to save the image in the DB)
Try this:
$file = $path_you_saved_image."/".$your_image_name;
$handle = fopen( $file , "rb" );
$img = fread($handle , filesize($file) );
$img = base64_encode($img);
$query = "insert into images (image) values ('$img')";
mysql_query($query) or die(mysql_error());
you code suggests that you have saved the resized image. Now open this resized image 'thumbnail.jpg' and process it, encode it and save it.
I'm hoping this is an easy one, I'm using mySQL and php to upload an image as a BLOB type using this code:
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);
}
This is all working fine, inserting to the database and everything. I then want to use SimpleImage: http://www.white-hat-web-design.co.uk/blog/resizing-images-with-php/ to perform some resize and compression work on the image before uploading it. I can't see how to combine say:
include('SimpleImage.php');
$image = new SimpleImage();
$image->load($_FILES['userfile']['tmp_name']);
$image->resizeToWidth(150);
$image->output();
With my existing code, I think what I want to do is get $content to become $image, but I've tried for a while and can't find a way of doing it. Any help much appreciated.
Happy Christmases to those who like Christmas and TIA to all.
You are outputting the resized image to the browser (::output()) but you're not saving it. If you want to store it inside the database, you need to change the temporary file first, e.g. by using the ::save() function of SimpleImage.
Next to that, you write you want to resize the picture in the browser before uploading. That can not be done with PHP, but only with javascript and browsers who support that. Additionally the upload handling on the PHP side might differ then. But I'm not really sure if you really meant it that the image is resized before uploading.
Another Idea I had is using an output buffer:
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'];
$image = new SimpleImage();
$image->load($_FILES['userfile']['tmp_name']);
$image->resizeToWidth(150);
ob_start();
$image->output();
$content = ob_get_clean();
$content = addslashes($content);
...
I am trying to upload files to my server using php to save them into a binary form into my mysql database but I cant get it to work, here is the script I’m using, I believe it has something to do with "$_FILES" because when I take this out "&& $_FILES['userfile']['size'] > 0" the script starts to run but then the variables underneath that use "$_FILES" aren’t defined.
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);
}
db_connect();
db_select();
$query = "INSERT INTO upload (name, size, type, content ) ".
"VALUES ('$fileName', '$fileSize', '$fileType', '$content')";
mysql_query($query) or die('Error, query failed');
db_disconnect();
echo "<br>File $fileName uploaded<br>";
}
This is a 2 fold process, first the upload itself and then the manipulation on the server. The first validation would be to make sure the file was even uploaded. For that you can use after the line
$fileName = $_FILES['userfile']['name'];
Use:
if(is_uploaded_file($fileName)) {
// Here goes all the file manipulation/storage/etc
} else {
echo 'Error: File could not be uploaded.';
}
Try to use that and maybe re-post if the file was actually uploaded. Just because $_FILES has content it does not necessarily mean that the file was uploaded to the server.
You should better use the file upload status to check whether the upload was successful.
And don’t use the addslashes function for MySQL queries. Use the mysql_real_escape_string instead.
If you upload the files with a form, does it have a 'enctype="multipart/form-data"' in the "form" tag?
I assume your field that's being posted is named "userfile"?
Also, this is not directly germane to your question, but it's generally considered a better practice to store files in the filesystem rather than in MySQL. Filesystems are designed to store large blocks of binary data, while databases are not.
I assume from your example that your input name is upload. <input type="file" /> results in PHP are not sorted in $_POST but in $_FILES. The documentation uses $_FILES['userfile'] as their example field, but if your input is declared as <input type="file" name="upload" />, you should simply use $_FILES['upload'].
try make print_r( $FILES ) and define what is the problem.
Maybe form have not needed type?