I have an upload script, and to fix the upload for several things, I want to md5 encrypt the files name. Here is the top of the php script I am using.
$target_dir = "file_dir/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
I attempted to use the md5() method like this
md5($target_dir . basename($_FILES["fileToUpload"]["name"]));
which did not work. Just came back as an error.
If you guys need more code in this script to help me, please tell me in the comments and i'll make a dummy copy of my script. Thank's in advance :D
You are trying to use basename on a path which doesn't exist: $_FILES["fileToUpload"]["name"]. This is just the filename and not the path in the server.
You can just use this for unique filename:
md5($target_dir . '/' . $_FILES["fileToUpload"]["name"])
Clearly you will need to make sure that filename is always unique. If that's not an option then you could also use and this is much more likely to be unique:
md5($target_dir . '/' . $_FILES["fileToUpload"]["tmp_name"])
If you want to make sure that its always unique then this will work:
md5($target_dir . '/' . $_FILES["fileToUpload"]["tmp_name"] . time())
Several options. It just depends what you want to do with them.
Late answer but hope it helps you.
You are trying to encrypt the directory along with the file. This must be causing the error.
You should encrypt just the file and add the file extension:
$file_ext = strrchr($_FILES["fileToUpload"]["name"], '.');
$target_file = md5(basename($_FILES["fileToUpload"]["name"])).$file_ext;
And then pass it to move move_uploaded_file
move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_dir.$target_file)
Related
I am using php code to upload an image, in my images.php file I have a directory which looks like the first line in the block of code below. I realise this won't work for a mac (I am working off a windows). This is obviously a problem as if I am working off a mac I will have to change this line of code each time I swap between computers. Is there anyway to automatically update it. I researched PATH_SEPARATOR but I have no idea how to incorporate into my code.
$target_dir = "..\\img\\uploads\\";
$imageFileType = strtolower(pathinfo($_FILES["fileToUpload"]
["name"],PATHINFO_EXTENSION));
$target_file = $target_dir . uniqid() . '.' . $imageFileType ;
$user_id = $_SESSION['userId'];
If anyone has any ideas, please let me know. Thank you in advance
Yep You can use DIRECTORY_SEPARATOR which is a PHP predefined constant which is going to provide the right directory separator either a backslash or a forward slash based on the operating system .
You can do something like this:
$ds = DIRECTORY_SEPARATOR;
$target_dir = ".." . $ds . "img" . $ds . "uploads" . $ds;
for more information check out PHP predefined constants
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.
I'm trying to create some sort of "selfie" uploader on mobile phones. Now it's working great it's just that when i test the upload file on my iPhone all the photo's will be named image.jpeg so they keep overwriting each other. Now what i want to do is rename the file to let's say image1.jpeg and the next image2.jpeg before it gets uploaded to the server.
My current code:
<?php
if (isset($_FILES['myFile'])) {
move_uploaded_file($_FILES['myFile']['tmp_name'], "uploads/" . $_FILES['myFile'] ['name']);
echo 'successful';
}
?>
I tried this code to give my image a filename value of image plus a random number between 1 and 99999 but this wasn't a succes.
<?php
if (isset($_FILES['myFile'])) {
$temp = explode(".",$_FILES["myFile"]["name"]);
$newfilename = rand(1,99999) . '.' .end($temp);
move_uploaded_file($_FILES["myFile"]["tmp_name"], "uploads/" . $newfilename;
echo 'successful';
}
?>
Any pointers will be appreciated.
this wasn't a succes.
Not a descriptive way to describe your error. Please include PHP errors or investigate them yourself so you (or we) can figure out what problems you're having with your code. Some editors will even tell you where your parsing errors are. You can also use a PHP linter.
The error lies in this line:
move_uploaded_file($_FILES["myFile"]["tmp_name"], "uploads/" . $newfilename;
The move_uploaded_file function is missing a closing bracket, so you must put it back in:
move_uploaded_file($_FILES["myFile"]["tmp_name"], "uploads/" . $newfilename);
I'd also recommend a better random filename generator. Try something like this instead:
$newfilename = sha1(uniqid(mt_rand(), true)) . '.' .end($temp);
It will create a hash that has a much lower likelihood of collisions (read: 1 in 2160.)
Best of luck!
I think your approach is not quite correct.
Renaming the file at client end assumes that each client will have a unique file naming convention. However, in practice this would be impossible, if not very difficult to implement.
You can however, much more easily change the file naming convention on the server.
<?php
if (isset($_FILES['myFile'])) {
$userid = 1; // User id loaded from database or some other way to identify user
$temp = explode(".",$_FILES["myFile"]["name"]);
// Create a distinct name for the file
$newfilename = $userid . '.' . date_timestamp_get() '.' .end($temp);
move_uploaded_file($_FILES["myFile"]["tmp_name"], "uploads/" . $newfilename);
echo 'successful';
}
?>
The above code, rather than using a random number generator, ensure a unique key based on the user's id, and the current timestamp, along with the filename. Other variations such as GUID could also be used.
1.Hi, I have a internal use only file upload script that uploads the files to a directory. When I upload something from my computer with a spcace in the name i.e example 1.zip it uploads with a space in the name thus killing the link in a email. Is it possible to make apache remove the space when its uploaded or make it a underscore?
The second problem I am having is how would I parse this to make the link an email link with the url of the file as the body of the email amd the email addy anything?
if (move_uploaded_file($_FILES['file']['tmp_name'], $uploaddir . $_FILES['file']['name'])) {
// uploaded file was moved and renamed succesfuly. Display a message.
echo "Link: " . "http://example.org/" . $_FILES["file"]["name"];
You just need to urlencode() your file name and everything is fine:
echo "Link: http://example.org/" . urlencode($_FILES["file"]["name"]);
But if you want to remove the spaces for another reason, you can use str_replace():
$replaced_name = str_replace(' ', '_', $_FILES["file"]["name"]);
rename($uploaddir . '/' . $_FILES['file']['name'], $uploaddir . '/' . $replaced_name);
# You should urlencode() it nonetheless:
echo "Link: http://example.org/" . urlencode($replaced_name);
Try:
$filename = $_FILES['file']['name'];
$filename = preg_replace("/[^a-zA-Z0-9]/", "", $filename);
//then
if (move_uploaded_file($_FILES['file']['tmp_name'], $uploaddir . $filename)) {
// uploaded file was moved and renamed succesfuly. Display a message.
echo "Link: " . "http://example.org/" . $filename;
As a side note : with the code you are using, what is happening if two files with the same name are uploaded ? If you don't do a check (like "is there a file that already has that name in $uploaddir ?") the second file will replace the first one.
That might not be something you want... is it ?
If not, to solve that (potential) problem, one solution is to always rename uploaded files, with names you control. (A simple counter would probably to the trick)
Another thing is : $_FILES["file"]["name"] is sent by the client, and, as such, can probably be forged to contains whatever someone would want. If it contains something like "../../index.php" (or something like this - you get the idea), this could allow someone to put any file they want on your server.
To prevent this from happening, you shoud be sure the file name/path used as destination of move_uploaded_file does not contain anything "dangerous". A solution could be to use basename. (see, for instance, example #2 on POST method uploads)
You might also want to check the mimetype of the uploaded file, so you don't get executables, for instance -- and you should make sure files uploaded are not executable by the webserver.
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!