Handling file uploads

Hi there,

I quick question about file uploads.

It’s the first time I’ve tried to do this and I’m wondering whether this isn’t working because I’m using an apache server locally.

I’ve just made a simple form to upload a file to the directory ‘uploads’:


<form id="upload" action="" method="post" enctype="multipart/form-data">
  <div>
    <label for="upload">Select file to upload: </label>
    <input type="file" id="upload" name="upload" />
  </div>
  <div>
    <input type="hidden" name="action" value="upload" />
    <input type="submit" value="Submit" />
  </div>
</form>
<p><?php echo $result; ?></p>

Here’s the controller script:


if(isset($_POST['action']))
{
  if(move_uploaded_file($_FILES["file"]["tmp_name"], "upload/" . $_FILES["file"]["name"]))
  {
  	$result = 'File uploaded successfully';
  } else
  {
    $result = 'No dice';
  }
}

include 'uploads.html.php';

move_uploaded_file keeps returning false… Can anyone shed any light on this?

Cheers,
Mike

Does the uploads directory have the correct permissions? It needs to be writable by the web server.

Erm, yeah, that’s the thing… Not sure where the upload directory is. Like I said, i’m testing this locally on apache.

Is there any debug info I can echo to gimme a clue as to what’s goin on?

Use:


<?php
// Prints human-readable information about a variable
print_r($_FILES);

Error Messages Explained

Well, according to your script you are uploading to uploads/file-name. This means that apache is looking for a folder called ‘uploads’ in the same folder of your php script. So… you need to make sure that:

  1. There is a folder called ‘uploads’ in the folder that this script is run from
  2. That the uploads folder is writable by apache. If this is a local server then you can set the permissions to 777 but never use 777 on a live server.

As a side note, you should really change the uploads folder to a different location and use a path relative to where the script is stored e.g. …/uploads

Hope this helps

Yeah, thanks, that’s great.

So, just to get started, i created a folder called uploads in the folder that contains the php script, set its permissions to 777 and submitted the form again. No dice.

So I set permissions on the folder that contains the php script to 777 as well. No dice.

So I set the permissions of localhost directory to 777. Still no dice.

Not sure what else to try…

D’oh. Loud slap to forehead

I had $_FILES[‘file’] instead of $_FILES[‘upload’] in my controller script. That’ll teach me to copy and paste.

Thanks for your help with this mrwooster. :smiley: