I am using the following code to upload a file in PHP for my website. I’ll post the code first and then ask my question.
upload.php:
<html>
<form action="upload_process.php" method="post" enctype="multipart/form-data">
<label for="file">Select picture to upload:</label>
<input type="file" name="image" id="image" />
<br />
<input type="submit" name="submit" value="Submit" />
</form>
</html>
upload_process.php
<?php
function error ($error, $location, $seconds = 1)
{
header ("Refresh: $seconds; URL = \"$location\"");
echo $error;
exit;
}
$max_file_size = 1000000;
$current_directory = str_replace(basename($_SERVER['PHP_SELF']) , '' , $_SERVER['PHP_SELF']);
$uploaded_directory = $_SERVER ['DOCUMENT_ROOT'] . $current_directory . 'files/';
$upload_form = 'http://' . $_SERVER['HTTP_HOST'] . $current_directory . 'upload.php';
$upload_success = 'http://' . $_SERVER['HTTP_HOST'] . $current_directory . 'view_posters.php';
$fieldname = 'image';
$errors = array (1 => "Max file size exceeded", 2 => "Max file size exceeded", 3 => "Upload incomplete", 4 => "No file attached");
isset ($_POST['submit']) or error ("Redirecting to upload form", $upload_form);
($_FILES[$fieldname]['error'] == 0) or error ($errors[$_FILES[$fieldname]['error']], $upload_form);
@is_uploaded_file($_FILES[$fieldname]['tmp_name']) or error ("Not an HTTP upload", $upload_form);
@getimagesize($_FILES[$fieldname]['tmp_name']) or error ("Please upload only images", $upload_form);
if (file_exists($upload_filename = $uploaded_directory . $_FILES[$fieldname]['name']))
{
error ("File exists", $upload_form);
}
$uploadedfile = $_FILES[$fieldname]['tmp_name'];
$src = imagecreatefromjpeg($uploadedfile);
list($width,$height)=getimagesize($uploadedfile);
$newwidth = 500;
$newheight = 500;
$tmp=imagecreatetruecolor ($newwidth, $newheight);
imagecopyresampled ($tmp, $src, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
imagejpeg ($tmp, "files/" . $_FILES[$fieldname]['name'], 100);
imagedestroy($src);
imagedestroy($tmp);
header ("Location: " . $upload_success);
?>
Now, for my question, if the file name doesn’t have a space, it gets resized and uploaded correctly. But, if there is a space, weird things happen. For example, if the name of the file is “this image.jpg” after upload, it gets resized and saved onto the server as “this.jpg image.jpg”. Can you please tell me why this is happening.
And, $upload_success is a landing page which just says “Upload successful”.
Well presumably you wouldn’t want the files saving with spaces anyway. So you should be checking and correcting this as part of the upload validation.
That will replace spaces with underscores.