如果名称已经存在,php检查上传文件

时间:2014-11-17 21:36:05

标签: php

<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES['fileToUpload']['name']);
$uploadOk = 1;
$FileType = pathinfo($target_file,PATHINFO_EXTENSION);

// Check if file already exists
if (file_exists($target_file)) {
echo "Sorry, $target_file already exists.";
$uploadOk = 0; 
}

//check file size
if ($uploadFile_size > 1) {
echo nl2br("sorry, exceeded file size
\r\n check your file size.
\r\n Error Code: ");
var_dump($_FILES['file']['error']); 
$uploadOk = 0;
}

// check if there is error
if ($uploadOk == 0) {
echo nl2br("sorry, no files are uploaded
\r\n check the file and try again
\r\n Error Code: ");
var_dump($_FILES['file']['error']); 

// if no error
} else { 
if (move_uploaded_file($_FILES["uploadFile"]["tmp_name"], $target_dir)) {
    echo "your ". basename( $_FILES["uploadFile"]["name"]). " file is successfully uploaded.";
    echo nl2br("\r\n thank you.");
    echo nl2br("\r\n you may close the window.");       
} 
else {
    echo  nl2br("-file upload fail- \r\n Error Code: ");
    var_dump($_FILES['file']['error']); 
    echo nl2br("\r\n \r\n please, check your file one more time.");
}
}
?>

嗨,上面是我的php脚本的一部分,$ target_file假设将一个被选中的文件引用到服务器上,但它保持引用“uploads /”目录。

由于$ target_file指的是“uploads /”,无论我选择上传哪个文件,它都会产生错误,表明该文件已存在于服务器上。

该脚本与w3school网页完全相同,我使用Chrome浏览器检查脚本是否正常工作。

有人可以帮我解决这个简单的错误吗?如果可以在选择上传的文件之后引用$ target_file,我的问题最有可能得到解决。

谢谢。

1 个答案:

答案 0 :(得分:0)

我一直在为自己搜索和学习以解决错误,我决定从头开始编写我的脚本,新脚本的工作与编码完美一样。

但是,我仍然不知道上面的脚本有什么问题。 如果以后有人从原始脚本中捕获任何错误,请随时评论我。

这是我新创建的用于上传的php脚本。

P.S。感谢那些试图帮助我找出错误的人。

<?php
$my_folder = "uploads/";
$uploadOk = 1;
$FileType = pathinfo($target_file,PATHINFO_EXTENSION);

// Check if file already exists
if (file_exists($my_folder . $_FILES['file']['name'])) {
echo 'Sorry,' . $_FILES['file']['name'] . 'already exists.';
$uploadOk = 0; 
}

//check file size
if ($_FILES['file']['size'] > 100000000) {
echo 'Sorry, your file exceeded upload size limit.  Please check your file size and try again'; 
$uploadOk = 0;
}

// check if there is error
if ($uploadOk == 0) {
echo 'NO FILES ARE UPLOADED'; 
} 
else { 
if (move_uploaded_file($_FILES['file']['tmp_name'], $my_folder . $_FILES['file']['name'])) {
    echo 'Received file' . $_FILES['file']['name'] . ' with size ' . $_FILES['file']['size'];
} else {
    echo 'Upload failed!';

    var_dump($_FILES['file']['error']);
}
}

?>