building an image uploading / resizing script - php

I'd like to learn how to build my own basic script to upload/resize and rename an image.
Right now I'm using dropzone.js for the client-side code, but I'm struggling for the server-side.
Here is what my upload.php script looks like right now (from a dropzone tutorial):
<?php
$ds = DIRECTORY_SEPARATOR;
$storeFolder = 'user/avatar';
if (!empty($_FILES)) {
$tempFile = $_FILES['file']['tmp_name'];
$targetPath = $_SERVER['DOCUMENT_ROOT'] . $ds. $storeFolder . $ds;
$targetFile = $targetPath. $_FILES['file']['name'];
move_uploaded_file($tempFile,$targetFile);
}
?>
It's working fine, the image gets uploaded where I want, exept I don't understand how it works, and that may be problem for the next steps of my script.
What is $_FILES['file']['tmp_name'] exactly ? Why is it not directly $_FILES['file']['name'] ?
How does move_uploaded_file($tempFile,$targetFile); ? Why does it need $tempFile ?
What's the difference between $_FILES['file'] and $_FILES['image'] ?
Last question, what is the best approach now to set-up a basic resizing function ? My goal is to resize the image to 150*150px no matter its original size.
Hopefully I can get some help to figure out all this,
Thanks !

From what I understand, this is a Linux security thing. Linux uploads the file to a temporary folder, and only after it's done can it move the file from where it's uploaded to where you're wanting it to go. That's why you have to do the multiple steps.
As for resizing an image, I don't think you can do this directly. I think you have to use imagecopyresized().
http://php.net/manual/en/function.imagecopyresized.php

Related

Switch/select default directory as store folder

Since I'm using dropzone.js to store images to a directory I would like to know if there is a possibilty within PHP or other to first SELECT the destination or store folder before the file is dropped. Normally, there is a default path to the folder defined in PHP such as:
// upload.inc.php
<?php
include("../inc/config.inc.php");
$ds = DIRECTORY_SEPARATOR;
$storeFolder = '../../gallery/samples';
if (!empty($_FILES)) {
$tempFile = $_FILES['file']['tmp_name'];
$targetPath = dirname( __FILE__ ) . $ds. $storeFolder . $ds;
$targetFile = $targetPath. $_FILES['file']['name'];
move_uploaded_file($tempFile,$targetFile);
}
?>
Now, the store folder is predefined. What I have in mind is to first move the file into the dropzone field and then secondly select, either by Jquery, html or somehow, the folder to which the file is dropped off to. I don't want to change the path manually constantly on the upload script. How can I establish this? JStree for instance looks pretty well to have it done, idk.
Assuming you have a name stored in JavaScript that you want to use as the folder to store the uploads, you'll need to create a hidden HTML form element that gets populated with JavaScript:
HTML:
<input type="hidden" id="storefolder" name="storefolder">
JS:
var storefolder = document.getElementById["storefolder"];
storefolder.value = [VARIABLE]; // Whatever changes the folder needs to pass through here
PHP:
$storeFolder = $_POST["storefolder"];
Now your JavaScript variable will become your PHP variable, without the user ever seeing it outputted in the form. Note that you could also make the input field visible (with type=text), and simply use its value to pass directly through to the PHP if need be, bypassing the need for any JavaScript.
Hope this helps!

File upload Not Working with PHP

So I have a form that allows a user to upload files. When they submit the file, I can get the file information such as name and tmp_name, yet the actually upload doesn't work. I don't get any PHP errors either. Below is my code, I think I just need another pair of eyes on it, as it was working a few days ago.
//Get the file name
$target_Dir = "temp/";
$tempName = $_FILES['file']['tmp_name'];
$target_file = $target_Dir . basename($_FILES["file"]["name"]);
$filename = pathinfo($target_file, PATHINFO_FILENAME);
//Get the password
$password = $_POST['password'];
//Store if the user wants the certificate to remain password protected
$passProtect = $_POST['passProtect'];
//upload the file to the server
move_uploaded_file($tempName, $target_file);
I need the file name without the extension for a later point in my code, in case you're wondering why I'm storing the file name without the extension.
I think you just did this mistake
$fileExtension = pathinfo($target_file, PATHINFO_FILENAME);
Try using this insted of that Code then only you will get the file name not the extention.
I had an unlink() further down in my script for some reason that I can't remember. It deleted the file that the user would upload right away.
Thanks for the extra set of eyes guys.

can i use the function md5_file to name files when upload without having conflict with names?

all the idea i need to be sure that the file doesn't saved more than one time and don't lose any file because if tow files get the same (md5) the second file will not saved
(my goal don't save the same file Twice on hard disk)
In other words,
if one user upload image and after that another user upload the same image i need to don't save the the second image because it's already exist in the hard disk all of this because
i need to save space on my hard disk
this is my code it works fine
$targetFolder = '/test/uploadify/uploads'; // Relative to the root
$tempFile = $_FILES['Filedata']['tmp_name'];
$targetPath = $_SERVER['DOCUMENT_ROOT'] . $targetFolder;
$myhash = md5_file($_FILES['Filedata']['tmp_name']);
$temp = explode(".", $_FILES['Filedata']['name']);
$extension = end($temp);
$targetFile = rtrim($targetPath,'/') . '/' .$myhash.'.'.$extension;
if(file_exists($targetFile)){
echo 'exist';
}
// Validate the file type
$fileTypes = array('jpg','jpeg','gif','png'); // File extensions
$fileParts = pathinfo($_FILES['Filedata']['name']);
if (in_array($fileParts['extension'],$fileTypes)) {
move_uploaded_file($tempFile,$targetFile);
}
else {
echo 'Invalid file type.';
}
thanks for all of you
Well, of course you can do this, in fact this is the way I use to avoid file duplications (and I mean not having two files wit the same content and not just silly name collision).
If you are worried about collisions, then you might take a look at sha1_file:
http://es1.php.net/manual/en/function.sha1-file.php
What are the chances that two messages have the same MD5 digest and the same SHA1 digest?
I've been using the md5 approach the way you are suggesting here for image galleries and it works just fine.
Another thing to take care about is the time it takes to calculate the hash, the more complex the hash, the more time it needs, but I'm talking about processing really big batches.
If I understand your question correctly your goal is just to generate unique file names. If so, there is no point in reinventing the wheel - every hash function with fixed output length is going to have collisions - just use built in tempnam function.
Manual states:
Creates a file with a unique filename, with access permission set to 0600, in the specified directory. If the directory does not exist, tempnam() may generate a file in the system's temporary directory, and return the full path to that file, including its name.
Following should work well enough:
$targetDirectory = $_SERVER['DOCUMENT_ROOT'] . '/test/uploadify/uploads';
$uploadedFile = $_FILES['Filedata']['tmp_name'];
$targetFile = tempnam($targetDirectory, '');
move_uploaded_file($uploadedFile, $targetFile);
You could always add the systems current time in milliseconds to the filename. That plus the md5, would have a very unlikely chance of returning the same values.
It's very small, but the chance is there. You can read more here and here
I suggest you add a salt to the end of the filename to make it practically impossible for files to conflict(You should put the salt in a different md5 function though)
$salt = md5(round(microtime(true) * 1000));
$hash = md5_file($_FILES['Filedata']['tmp_name']);
$targetFile = rtrim($targetPath,'/') . '/' .$hash.$salt.'.'.$extension;
You should then insert the filename in a database so you can access it later.

Interpret Code - Non PHP Programmer

What is this code doing?
<?php
if (!empty($_FILES)) {
$tempFile = $_FILES['Filedata']['tmp_name'];
$targetPath = $_SERVER['DOCUMENT_ROOT'] . $_REQUEST['folder'] . '/';
$targetFile = str_replace('//','/',$targetPath) . $_FILES['Filedata']['name'];
move_uploaded_file($tempFile,$targetFile);
echo str_replace($_SERVER['DOCUMENT_ROOT'],'',$targetFile);
}
?>
It is basically uploading a file and echoing the target file's name.
There should also be something like an HTML form to send the file to this script.
It accepts an user uploaded file, and puts it in your webroot in a folder, specified by the user. Then it outputs the path of the uploaded file.
This code is to upload a file in the destination directory. Is there anything else do you want to understand.
This will upload the file in the path you have in variable $_REQUEST['folder']
Storing files uploaded (possibly via HTML form) onto server.
It's accepting a file posted by a HTML form and uploading it to a certain directory within a server. After that it's displaying the location of the file on screen (in the browser).

Uploadify - files not showing up

I'm trying to use Uploadify (a jQuery plugin) with my CakePHP app. Locally (WampServer), it works great, but when I try it on my live server (Dreamhost), the files don't show up. I've properly chmod'ed the folders, checked the paths, etc, and I can't make any sense of why it isn't working. Here's upload.php:
if (!empty($_FILES)) {
$tempFile = $_FILES['Filedata']['tmp_name'];
$targetPath = $_SERVER['DOCUMENT_ROOT'] . "/app/webroot/posts/temp/";
$targetFile = str_replace('//','/',$targetPath) . $_FILES['Filedata']['name'];
$targetFile = str_replace(".", "_" . mt_rand(10000000,99999999) . ".", $targetFile);
move_uploaded_file($tempFile,$targetFile);
}
echo "1";
This script is definitely being run, but I've looked in the specified folder (and all over the filesystem), and the uploaded file(s) just aren't showing up! It's driving me crazy--hopefully someone has the answer to this. Please let me know if I should post any more code, and I will.
You could change $targetPath so it is relative to the document rather than the exact server path. I had a similar problem a while ago.
Turns out, it was this line:
$targetFile = str_replace(".", "_" . mt_rand(10000000,99999999) . ".", $targetFile);
This line was meant to append a random series of numbers to the filename to avoid collisions. However, as you can see, it's operating on the whole path, not just the filename. Well, my domain name is in my path (i.e. mydomain.com), and thus was getting changes to mydomain_12314123402.com, which obviously is a path that doesn't exist.
Man, I feel like an idiot!

Categories