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.
Related
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.
I have been working on a little PHP script that dynamically creates & saves images in a folder tmp (which already exists!) from a base64 string. This is my save.php file.
// get base-64 string from form
$filteredData = substr($_POST['img_val'], strpos($_POST['img_val'], ",")+1);
// decode string
$unencodedData = base64_decode($filteredData);
// create unique filename
$a = uniqid();
// name, location and file extension
$compfile = '/tmp/' . $a . '.png';
// save image
file_put_contents($compfile, $unencodedData);
// print image
echo '<img src="' . $compfile . '" />';
Strangely enough: It will neither create nor render the image on the page, because of the /tmp/ in my $compfile variable. When I remove it, everything works like a charm and the image is being created in the same folder.
Unfortunately, I really want the image to be created in the /tmp/ folder. Before $compfile was a randomly generated filename, and instead was called /tmp/img.png I was able to save to create an image by the name img.png and save it to the tmp.
What am I missing here?
(Thank you for your time.)
Since I guess this was the solution I'll post it as answer.
I think you want "tmp/" . $a . ".png" instead of "/tmp/" . $a . ".png". It's good practice to just always use absolute paths, so: __DIR__ . "/tmp/" . $a . ".png". This takes away any confusion.
I am trying to copy a uploaded file which is in my directory called "upload" and is called image (5).jpg to my other directory called "images". This is my code.
<?php
copy(upload/image (5).jpg, images/);
?>
Am I doing this right?
First your image file name is awful, please do not use spaces in file names. Also do not use brackets in file name. Some systems like google app engine would easily mark that as invalid file name and ignore it.
Then adjust a little your line of code to look like this:
$old_file = 'upload/image_5.jpg';
$new_file = 'images/image_5.jpg';
$copied = copy(old_file, $new_file);
if ($copied) {
print "file " . $old_file . " is copied to " . $new_file;
} else {
print "error";
}
If you encounter an error maybe paths to files are not configured right. You do not have a write permission on that specific directory etc.
I am able to upload a zip file and compress it, now i need the filename alone... but when i try to reach the name i get along with zip.
asas.text = "upload/" +fileRef.name + "/" +as.text;
Also How can i point the current viewing URL before the upload path.. something if
http://www.yahoo.com/upload/filename/ If the file is viewed from yahoo domain
Use the basename function.
$fileName = basename('/path/to/file.zip'); // $fileName == 'file.zip';
I think you're asking for the server name? Using your example above:
echo $_SERVER['SERVER_NAME']; // prints "www.yahoo.com"
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!