Qbasicnews.com

Full Version: File uploading with PHP
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Pages: 1 2 3 4
This question will be blatant: How do I create a form and corrosponding php file that will upload the specified file on the form to the server?
I've tried googling it, didn't come up with anything relevant.
Two things you gotta do:

Firstly, you need a form that contains an INPUT TYPE=FILE. This form needs to be of enctype=multipart/form-data.

Secondly, you need a script which actually handles the uploaded file. The file will be uploaded to your server's temporary directory, so you'll need to move it or copy it from there (PHP has a built-in function for this although I don't remember what it's called coz I just copy it). You'll need to learn to use $HTTP_POST_FILES (or $_FILES, i think it's called, on more recent PHP versions) to handle file uploads.

I usually try to avoid giving direct code samples to people, as I feel it hinders the learning process Wink but this is a small snippet I used for a client's website:

Code:
$size = $HTTP_POST_FILES['userfile']['size'];
  if ($HTTP_POST_FILES['userfile'] != '' && $size > 0) {
    copy($HTTP_POST_FILES['userfile']['tmp_name'], "/home/prestige/public_html/upload/incoming.jpg") or die("Couldn't copy the file!");  
  } else {
    die ("There was an error uploading your file. Please try again. If this error persists, contact the system administrator.");
  }
'userfile' was the name of the INPUT TYPE=FILE on the form. Most of this is easy to figure out, actually.

Hope this gets you started in the right direction Big Grin
the manuals at http://php.net explain this, also
this is all assuming uploads are enabled on the server Smile
Rhia: I'm pretty sure they are.
Nexinarus: I'll look at that
Ado: Alright - but will the form create the "browse" button? Take a look at http://qbnz.com/pages/uploads/upload.php and tell me if that is what the form will create.
Hmm, ok I tested it.
upload.html:
Code:
<html>
<body>
<form action="upload.php" method="post">
File: <input type="file" name="fname"><br>
<input type="submit" value="submit">
</form>
</body>
</html>
And in upload.php:
Code:
<?  $size = $HTTP_POST_FILES['fname']['size'];
  if ($HTTP_POST_FILES['fname'] != ''" && $size > 0) {
    copy($HTTP_POST_FILES['fname']['tmp_name'], "/home/incoming.jpg") or die("Couldn't copy the file!");  
  } else {
    die ("There was an error uploading your file. Please try again. If this error persists, contact the system administrator.");
  } ?>
I get a parse error on line 2.
And /home/incoming.jpg is an existing file, CHMODed to 777.
line 2...
Quote:if ($HTTP_POST_FILES['fname'] != ''" && $size > 0) {

Wink
Fixed it.
Now I get the "There was an error uploading your file..." message.
Do you want the code to my uploading thingy? Smile
If possible, thanks. Smile
Pages: 1 2 3 4