View Full Version : PHP How To Let Users Upload Files


PunkGo
10-12-2003, 11:14 PM
ok guys...im going to tell you all how to let users or admins, admins preferably, upload files from there computer, to your server.
ok, lets start with basic HTML..lets call it file.html
--BEGIN file.html--
<html>
<head>
<title>PunkGo Rocks!</title>
</head>
<body>
<form enctype="multipart/form-data" action="upload.php" method="post">
<input type="hidden" name="MAX_FILE_SIZE" value="100000">
<input type="file" name="userfile">
<input type="submit" name="submit" value="Upload">
</form>
</body>
</html>
--END file.html--

ok, let me break it down to u...
the enctype="multipart/form-data" tells upload.php thatit will still have regular form data but a file is coming, thats basically it...then the
<input type="hidden" name="MAX_FILE_SIZE" value="100000">

this sets the maximum file size that the user can upload...so ur server isnt set back by half its bandwidth...the value is the maximum size the file can be...i set it to 100,000 bytes, or 100 KB
the

<input type="file" name="userfile">

is where they click and get the file i believe... then theres the submit button...ok now to upload.php ...where the magic happens!

--BEGIN upload.php--

<?php

// $userfile is where file went
$userfile = $HTTP_POST_FILES['userfile']['tmp_name'];
// $userfile_name is original file name
$userfile_name = $HTTP_POST_FILES['userfile']['name'];
// $userfile_size is size in bytes
$userfile_size = $HTTP_POST_FILES['userfile']['size'];
// $userfile_type is mime type like a pic, gif or jpg stuff like that
$userfile_type = $HTTP_POST_FILES['userfile']['type'];
// $userfile_error is any error that happened
$userfile_error = $HTTP_POST_FILES['userfile']['error'];

if ($userfile_error > 0) {
echo 'Problem: ';
switch ($userfile_error)
{ case 1:
echo 'File exceeded upload_max_filesize';
break;
case 2:
echo 'File exceeded max_file_size';
break;
case 3:
echo 'File only partially uploaded';
break;
case 4:
echo 'No file uploaded';
break;
}
exit;
}

// put the file where we'd like it
$upfile = 'uploads/'.$userfile_name;

// is_uploaded_file and move_uploaded_file
if (is_uploaded_file($userfile))
{
if (!move_uploaded_file($userfile, $upfile))
{
echo Couldn't not move file to destination directory';
exit;
}
} else {
echo Possible file upload attack. Name: '.$userfile_name;
exit;
}
echo 'File uploaded successfully</font><br /><br />';

// show what was uploaded
echo 'Preview of uploaded file contents:</font><br /><hr />';
//I set it where when u uploaded a file you can see it
echo '<img src="/uploads/'.$userfile_name.'">';
echo '<br /><hr />';
?>



kk, so all the variables are described there and explains it....
btw u gotta chmod the folder ur uploading it to, to: 777 so it is able to copy it...ok, thx, bye!