我使用以下代码为我的网站上传PHP文件。我先发布代码,然后问我的问题。
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);
?>
现在,对于我的问题,如果文件名没有空格,则会调整大小并正确上传。但是,如果有空间,就会发生奇怪的事情。例如,如果上传后文件的名称为“this image.jpg”,则会调整大小并将其保存到服务器上“this.jpg image.jpg”。你能告诉我为什么会这样吗。
而且,$ upload_success是一个登陆页面,上面写着“上传成功”。
答案 0 :(得分:3)
原则上你可能不希望文件保存为空格。因此,您应该在上传验证过程中检查并更正此问题。
imagejpeg($tmp, "files/".str_replace(' ', '_', $_FILES[$fieldname]['name']), 100)
这将用下划线替换空格。