Hi Everyone,
I'm trying to upload images through a HTML form and then a PHP script to the file system on my server. The images go up OK but when I try to display them I get a corrupted mess of gobbledegook. If any one could point me in the right direction it would be much appreciated. Code is below:
HTML Form:
<html>
<head>
<title>Image Upload</title>
</head>
<body>
<h1>Upload your image here<</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>
Upload Script:
<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'];
$userfile_name = "1234.jpg";
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 != 'image/jpeg')
{
echo 'Problem: file is not a valid image file';
exit;
}
// put the file where I'd like it
$upfile = './uploads/'.$userfile_name;
// is_uploaded_file and move_uploaded_file added at version 4.0.3
if (is_uploaded_file($userfile))
{
if (!move_uploaded_file($userfile, $upfile))
{
echo 'Problem: Could not move file to destination directory';
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);
?>
</body>
</html>
Image Upload in PHP
Moderator: General Moderators
-
Illusionist
- Forum Regular
- Posts: 903
- Joined: Mon Jan 12, 2004 9:32 pm
I'm not sure why you have to "reformat the comments" and use:
I don't recall ever having to use that function when handling file uploads. I would suggest checking google for an upload tutorial
Code: Select all
$contents = strip_tags($contents);