我有代码工作,上传文件,同时检查扩展是否允许,并且它在大小限制内,但我需要重命名已上传的文件(如果已存在)。我已经阅读了其他几篇帖子,但我无法确切地知道我需要将建议的代码放到我当前的代码中。非常感谢您的帮助!
<form action="" method="POST" enctype="multipart/form-data">
<input type="file" name="image"/>
<input type="submit" value="Upload" />
</form>
<?php
if (isset ($_FILES['image'])) {
$errors = array();
$allowed_ext = array('pdf','jpg');
$file_name = $_FILES['image']['name'];
$file_ext = strtolower(end(explode('.', $file_name)));
$file_size = $_FILES['image']['size'];
$file_tmp = $_FILES['image']['tmp_name'];
if (in_array($file_ext, $allowed_ext) === false ) {
$errors[] = '<li>Extension not allowed.</li>';
}
if ($file_size > 2097152) {
$errors[] = '<li>File size must be 2mb or less.</li>';
}
if ()
if (empty($errors)) {
if (move_uploaded_file($file_tmp, 'images/'.$file_name)) {
echo '<li>File uploaded sucessfully.</li>';
echo '<li>File located at: http://' . $_SERVER[HTTP_HOST] . '/image-upload/images/' . $file_name . '</li>';
}
} else {
foreach ($errors as $error) {
echo $error, '<br />';
}
}
}
?>
答案 0 :(得分:0)
似乎move_uploaded_file
的第二个参数不正确。
$targetPath = $_SERVER['DOCUMENT_ROOT'] . '/image-upload/images/' . $file_name;
move_uploaded_file($file_tmp, $targetPath);
您可以回复$targetPath
以检查它是否正确。
答案 1 :(得分:0)
只需将此代码替换为空白if()
即可if (file_exists('images/'.$file_name))
{
$file_name = time().$_FILES['image']['name']; //This will rename file with current time stamp which will always unique.
}
但我强烈建议您始终重命名您的文件,以避免直接访问或损害。