0

次のコードを使用して、自分のWebサイト用に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.jpgimage.jpg」としてサーバーに保存されます。なぜこれが起こっているのか教えてください。

また、$ upload_successは、「アップロードが成功しました」とだけ表示されるランディングページです。

4

1 に答える 1

3

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.

imagejpeg($tmp, "files/".str_replace(' ', '_', $_FILES[$fieldname]['name']), 100)

That will replace spaces with underscores.

于 2012-07-15T09:08:08.443 に答える