Uploading pictures via PHP/MySQL - php

I have a database of 1000 items with one field being 'images'. This is a text field with the name of a particular image file (PNG or JPG). I'm trying to find a way to include an 'upload' button on my website so that users can upload an image to the server, and it be recorded in the MySQL database.
I've looked at several ideas online and not found anything that either suits my needs or I can get working. All images can be stored in the same folder as they will all have different names.
Does anyone know of any tutorials, or can assist me in doing it, many many thanks x

Read this tutorial ...and also check did u give enctype="multipart/form-data" in form...

this is php script to upload image:-
if ($_FILES['inputfieldname']['name']) {
$filename = stripslashes($file[inputfieldname]['name']);
$extension = "get the extension of file";// jpg if image format is jpg
$extension = strtolower($extension);
//set target image name
$image_name1 = date("Ymdhis") . time() . rand() . '.' . $extension;
$target = "target directory path";
if ($this->checkExtensions($extension)) {
$filestatus = move_uploaded_file($file[inputfieldname]['tmp_name'], $target);
#chmod($target, 0777);
if ($filestatus) {
// insert $image_name into database
}
}
}

Related

Converting .pdf to .jpg and displaying on site using Imagick

I'm trying to convert a user-uploaded PDF file to .jpg, to create some sort of thumbnail. I want the thumbnail to be displayed on the same page once they upload their PDF.
I'm using Imagick.
Here's some of my code:
$filePath = $_FILES['file']['tmp_name'];
$fileName = $_FILES['file']['name'];
$pdfThumb = new Imagick();
$pdfThumb->setResolution(300,300);
$pdfThumb->readImage($filePath . '[0]');
$pdfThumb->setImageFormat('jpeg');
$fp = $fileName . '.jpg';
$pdfThumb->writeImage($fp);
I don't feel like anything is really happening, and I want to make sure it saves the thumbnail to my server (possibly temporarily) and show it on a div. Any tips would be much appreciated!

Encoding uploaded files name

I want to ask, if I have a web form, and people use it to upload something to my db. If 2 persons uploaded the same file with the same name, in the uploads directory, one of them will replace the other. So I need to change the name of every file uploaded to db to : filename201405051200.pdf or jpg or...
Here we have the filename per example image1 and the numbers are the date and time of the uploads. So any help. I am using the code shown as an answer in the link below:
Uploading blob files/images into Mysql
I used this code:
$path = "../uploads/".$_FILES['file']['name'];
if(move_uploaded_file($_FILES["file"]["tmp_name"], $path.'_'.time())){
...
}
but now the format type of the file is replaced by the time. So if it is img.jpg it is now img85890338jpg and wont open properly
You can use pathinfo to extract the file extension:
$fileExt = pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);
After that you can create your new file name:
if(move_uploaded_file($_FILES["file"]["tmp_name"], $path.'_'.time().date().'.'.$fileExt)) {
}

How strong is my php file upload security?

I would like to have a check whether an uploaded file sent via email and not saved in the DB, allow only the following extensions.
Is this something secure?
$allowed = array('pdf','doc');
$filename = $_FILES['video_file']['name'];
$ext = pathinfo($filename, PATHINFO_EXTENSION);
if(!in_array($ext,$allowed) ) {
echo 'error';
}
No it isn't (a file could have two extensions : image.php.jpg).
If you are planning to upload only images, one good thing is to try to get image size with getimagesize and remove it from temp folder if it returns false

Speed up image conversion times

If this is a newby question, forgive me. I have coded a php file uploader. After hearing that hackers could attatch/disguise code to images to infect sites, I got an idea to solve that problem. To convert the upload image to another file format (png) and then to another (jpg) with 70% quality. This caused the malware to become corrupted. The problem is, this total conversion process takes a about 1 minute at top speed. The service I'm making needs to be quick to handle the file uploads so that the users can go about the work. How can I speed up this process? The upload code is below (important variables are blanked).
// upload the file
$status = "...recieving the file...";
move_uploaded_file($_FILES["file"]["tmp_name"], "$folder" . $_FILES["file"]["name"]);
$status = "...processing the file...";
// convert the file to destroy viruses
$filename21 = "$folder" . $_FILES["file"]["name"];
imagepng(imagecreatefromstring(file_get_contents($filename21)), "$folder"."debug.".$picture_newname.".png");
$imageTmp=imagecreatefrompng("$folder"."debug.".$picture_newname.".png");
imagejpeg($imageTmp, "$folder".$picture_newname.".jpg", 90);
imagedestroy($imageTmp);
These are the steps it follows:
Scan database for file with the same name
if file with same name is found, rename the current upload
receive the file
"evaluate" the file (the double conversion process to protect the server)
insert the info into the uploads database
If any other codes are needed (or if i should do some more timing) please let me know. Thanks in advance for your assistance.
This is a crazy idea. You're not just tying up the server in converting between image formats, you're also degrading the quality of every uploaded image.
I'd recommend a different approach
When a file is uploaded, use PHP's getimagesize() function to check the image. If this function returns FALSE (or an unexpected image type, or strange dimensions, etc.), then the file is corrupt and can be deleted.
Use exiftool or something similar to strip away all the metadata from the uploaded file before you store it away on the server. That way you can ensure that the file only contains image data.
Perhaps you could check that the value of $_FILES["file"]["name"] doesn't contain anything sneaky like ../../ before you use it to save the file on your server.
It's totally bad idea implement double conversion for security purpose, because of DoS attack.
Balanced solution between speed & security must contain:
Check MIME type.
Check file extension.
Check file size. (highly recommended)
Check image size. (optional, depends on application requirements)
Something like this:
$allowable_types = array(
'png' => 'image/png',
'jpeg' => 'image/jpeg',
'gif' => 'image/gif'
);
$max_file_size = 10240; // 10K limit example
$finfo = new finfo(FILEINFO_MIME_TYPE);
$type = $finfo->file($_FILES['name']['tmp_name']);
$size = filesize($_FILES['name']['tmp_name']);
$info = pathinfo($_FILES['name']['tmp_name']);
if (isset($allowable_types[$info['extension']])
and $type === $allowable_types[$info['extension']]
and $size <= $max_file_size
) {
// check image size if your app require this
move_uploaded_file($_FILES['name']['tmp_name'], $destination);
}
Update
I would not recommend to use $_FILES['file']['name'] in destination path or scan whole directory for same name. Because of some security flaws and performance drop. Better solution is to generate unique name for each image:
$new_name = uniquid() . '.' . $info['extension'];
$destination = $upload_path . $new_name;

What is the most secure method to upload image file to server with PHP?

I know this topic is widely talked about. I've done my research, and decided to store image files onto the server instead of the DB as a blob file. The problem that I am having is trying to figure out the best way to upload the file, store it in a designated folder then storing the destination in the db..say../img/something.jpg - I've tried looking through many resources but most of them are missing some important steps in the process.
Problems:
Finding a secure way for uploading the img file
Limiting the file
size Uploading the image to a destination file
Storing the destination file as a text in the DB
I'm using PHP and MySQL.
Dunno what all your points about, but what you really have to be concerned with is
check for the file extension.
extract it from the filename and compare with allowed ones.
also it would be good to check filename to have only one dot, or at least it doesn't have a name like name.html.jpg, due to some odd Apache behavior.
check for the file contents. the best way would be to create a brand new image out of the uploaded one.
take usual precautions while working with DB.
Here you go, this covers the basic ideas of what you want to do:
<?php
$allowedTypes = array("image/jpg", "image/jpeg", "image/png");
$maxSize = 3 * 1024 * 1024; // 3Mb
$fileType = $_FILES["file"]["type"];
$fileSize = $_FILES["file"]["size"];
// check if there was an error
if ($_FILES["file"]["error"] > 0)
{
die($_FILES["file"]["error"]);
}
// check if the filetype is valid
if (!in_array($fileType, $allowedTypes))
{
die("Invalid file type: $fileType");
}
// check if the size doesn't exceed the limitations
if ($fileSize > $maxSize)
{
die("The file was too big: $fileSize");
}
$name = $_FILES["file"]["name"];
$tmpfile = $_FILES["file"]["tmp_name"];
// check if the filename is valid
if (preg_match("/[\w-]+\.(jpg|jpeg|png)$/", $name) != 1)
{
die("Invalid file name: $name");
}
// create unique name if needed
$path = "/var/www/images/" . $name;
move_uploaded_file($tmpfile, $path);
// add the filepath to mysql
mysql_connect("localhost", "username", "password");
mysql_select_db("imagedb");
mysql_query("INSERT INTO images (Location, Size) VALUES ('$path', '$size');");
?>
This is meant to show how it could be done.
read this
personally I'd use imgur which is used here on stackexchange websites

Categories