未选择图像文件时无法停止处理表单


Not able to stop processing form when image file has not been chosen

我有一个表格,我用它来提交带有图像的新帖子。如果用户没有选择要上传的图像,我不希望帖子继续向服务器和数据库提交数据。目前,我尝试的一切都是让代码继续处理表单。

这是我的一些代码:

//check if the submit button has been clicked
        if( isset( $_POST['submit'] ) ){
            //validate the title and description
            $title = validate_title($_POST['title']);
            $desc = validate_desc($_POST['desc']);
            //Get other posted variables
            $cat = $_POST['cat'];
            $year = $_POST['year'];
            if($title && $desc != false){
                //check if an image has been submitted
                if( $_FILES['files']['name'] != ""){...

我也尝试使用以下方法,但是当没有选择文件时,两者都不会停止代码:

if( $_FILES['files']['error'] == UPLOAD_ERR_OK){...
if( $_FILES['files']['name'] != UPLOAD_ERR_NO_FILE){...

看起来你的文件输入名称是files[],在这种情况下,$_FILES["files"]["name"] 将是一个数组,以检查用户是否提供了上传图像尝试,

foreach ($_FILES['files']["error"] as $index => $error){
    if ($error == UPLOAD_ERR_NO_FILE){
        //no file was uploaded in $index`th file input 
    }
    else{
        //other checks and process $_FILES['files']['tmp_name'][$index]
    }
}

你应该看看bool is_uploaded_file ( string $filename ) .

例如,其中user_file是文件上传的子数组:

<?php
if (is_uploaded_file($_FILES['userfile']['tmp_name']))
{
   // Success, file uploaded
}
else
{
   // Error, no file, invalid file, etc.
}
?>

如果您希望用户在未选择任何图像时无法发送任何请求,则可以通过 java 脚本客户端进行。当表单提交即将开始时,用户将收到错误。但请记住,用户可以轻松完成此验证。没有办法在客户端做到这一点,它是可靠的。最好在服务器端检查它,因为其他人已经回答了。

我认为

,这是处理所有上传文件的最佳过程,例如:

    // allowed extensions
$extensions = array('.png', '.gif', '.jpg', '.jpeg','.PNG', '.GIF', '.JPG', '.JPEG');
        if((!empty($_FILES["files"])) && ($_FILES['files']['error'] == 0)) {
            // check extension
            $extension = strrchr($_FILES['files']['name'], '.');
            if (!in_array($extension, $extensions)) {
                echo 'wrong file format, alowed only .png , .gif, .jpg, .jpeg';
            } else {
                // get file size
                $filesize = $_FILES['files']['size'];
                // check filesize
                if($filesize > $maxlimit){ 
                    echo "File size is too big.";
                } else if($filesize < 1){ 
                    echo "File size is empty.";
                } else {
                    // temporary file
                    $uploadedfile = $_FILES['files']['tmp_name'];
                }
            }
        }