Uploading files

Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

Threaded View

I've been trying today to upload a file using a script from a book I've been
learning from.

The script work's fine, except for whe the naem of the file contains an
apostrophe... e.g. "  '  ".

The script is:

$file_dir = "C:\uploaded";

foreach ($_FILES as $file_name => $file_array) {
 print "path: ".$file_array['tmp_name']."<br>\n";
 print "name: ".$file_array['name']."<br>\n";
 print "type: ".$file_array['type']."<br>\n";
 print "size: ".$file_array['size']."<br>\n";

 if (is_uploaded_file($file_array['tmp_name'])) {
   "$file_dir/$file_array[name]") or die ("Couldn't copy");
  print "File was moved!<br><br>";

The output I get when the apsotrophe is added to the file name is:

path: C:\WINDOWS\TEMP\php5D.tmp
name: Robert\'s file.txt
type: text/plain
size: 15

Warning: move_uploaded_file(C:\uploaded/Robert\'s file.txt): failed to open
stream: No such file or directory in C:\Program Files\Apache
Group\Apache2\htdocs\php\Hour 9\listing9.14.php on line 21

Warning: move_uploaded_file(): Unable to move 'C:\WINDOWS\TEMP\php5D.tmp' to
'C:\Documents and Settings\Robert\My Documents\uploaded/Robert\'s file.txt'
in C:\Program Files\Apache Group\Apache2\htdocs\php\Hour 9\listing9.14.php
on line 21
Couldn't copy


Is the error because of the forward slash or because of the \'  in the part
"C:\uploaded/Robert\'s file.txt"



Re: Uploading files

Quoted text here. Click to load it

\ is the direcory seperator in DOS like systems. It can't be used in
filenames. On unix like filesystems it's /. You are trying to create the
file "'s file.txt" in de directory Robert in the upload dir.

Get rid of the \ and it should work, it's probably generated by the evil
magic_quotes setting.  This is an other fine example that the addslashes
function shouldn't be executed automatically on all data, only use it if
you know it is the solution for a problem...

urlencode of htmlentities would be a better escaping mechanism in this

BTW Either use \ (not the extra \) or /, not both!


  Daniel Tryba

Re: Uploading files


Quoted text here. Click to load it

This is a classic gotcha.

Good practice (usually) is to strip any non alpha-numeric characters
from the filename (other than full stops, hyphens and underscores).

Have a quick look at the PHP str_replace function. There are replace
functions that accept arrays too (if that's of interest).


Jonathan Beckett (jonbeckett@pluggedout.com)
working on : http://www.pluggedout.com/penpals

Site Timeline