InsaneProgrammer
Programmer
I'm new to PHP and have inherited a site that has a page for file uploading. The site doesn't work. Before jumping in and trying to fix it I thought I'd look at some examples and try to create a simple page first. My example consists of 2 pages (upload.php, upload.html). The code for both is below. After I choose the text file I want to upload I get a message saying that the file could not be moved.
Any help would be appreciated.
InsaneProgrammer.com
Code:
--upload.php--
<html>
<head>
<title>Uploading...</title>
</head>
<body>
<h1>Uploading file...</h1>
<?php
// $userfile is where file went on webserver
$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 e.g. image/gif
$userfile_type = $HTTP_POST_FILES['userfile']['type'];
// $userfile_error is any error encountered
$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;
}
// does the file have the right MIME type?
if ($userfile_type != 'text/plain')
{
echo 'Problem: file is not plain text';
exit;
}
// put the file where we'd like it
$upfile = '../test2/'.$userfile_name;
if (is_uploaded_file($userfile))
{
if (!move_uploaded_file($userfile, $upfile))
{
[b][COLOR=red]echo 'Problem: Could not move file to destination directory';[/color][/b]
exit;
}
}
else
{
echo 'Problem: Possible file upload attack. Filename: '.$userfile_name;
exit;
}
echo 'File uploaded successfully<br /><br />';
// reformat the file contents
$fp = fopen($upfile, 'r');
$contents = fread ($fp, filesize ($upfile));
fclose ($fp);
$contents = strip_tags($contents);
$fp = fopen($upfile, 'w');
fwrite($fp, $contents);
fclose($fp);
// show what was uploaded
echo 'Preview of uploaded file contents:<br /><hr />';
echo $contents;
echo '<br /><hr />';
?>
</body>
</html>
--upload.html--
<html>
<head>
<title>Administration - upload new files</title>
</head>
<body>
<h1>Upload new files</h1>
<form enctype="multipart/form-data" action="upload.php" method="post">
<input type="hidden" name="MAX_FILE_SIZE" value="1000000">
Upload this file: <input name="userfile" type="file">
<input type="submit" value="Send File">
</form>
</body>
</html>
InsaneProgrammer.com