douxuanma4357 2015-02-25 11:39
浏览 36
已采纳

如果输入为空,如何阻止一行代码运行

I have this line of code, and i would like it to not run when "beg_img" is empty, i got the code from w3schools and changed minior things, im pretty new to this, but i guess i have to use some kind og if/else isset?

<?php
$target_dir = "../../img/images/";
$target_file = $target_dir . basename($_FILES["beg_img"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
    $check = getimagesize($_FILES["beg_img"]["tmp_name"]);
    if($check !== false) {
        echo "File is an image - " . $check["mime"] . ".";
        $uploadOk = 1;
    } else {
        echo "File is not an image.";
        $uploadOk = 0;
    }
}

// Check if file already exists
if (file_exists($target_file)) {
    echo "Sorry, file already exists.";
    $uploadOk = 0;
}
// Check file size
if ($_FILES["beg_img"]["size"] > 500000) {
    echo "Sorry, your file is too large.";
    $uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg") {
    echo "Sorry, only JPG, JPEG & PNG files are allowed.";
    $uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
    echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
    if (move_uploaded_file($_FILES["beg_img"]["tmp_name"], $target_file)) {
        echo "The file ". basename( $_FILES["beg_img"]["name"]). " has been uploaded.";
    } else {
        echo "Sorry, there was an error uploading your file.";
    }
}

$beg_i_img = basename($_FILES["beg_img"]["name"]);

?>
  • 写回答

4条回答 默认 最新

  • douguanyan9928 2015-02-25 11:44
    关注

    Or you can try this at the beggining of your script:

    // If no file was uploaded
    if($_FILES['beg_img']['error'] == 4){
        return;
    }
    

    And it's better to validate some things like the one you want at the beggining of your script than wrap all your code with an if, because one more wrap, then another and another...if we can avoid it, the code will be better :)

    You should check return and maybe continue, will help you in your scritps :)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 如何在3D高斯飞溅的渲染的场景中获得一个可控的旋转物体
  • ¥88 实在没有想法,需要个思路
  • ¥15 MATLAB报错输入参数太多
  • ¥15 python中合并修改日期相同的CSV文件并按照修改日期的名字命名文件
  • ¥15 有赏,i卡绘世画不出
  • ¥15 如何用stata画出文献中常见的安慰剂检验图
  • ¥15 c语言链表结构体数据插入
  • ¥40 使用MATLAB解答线性代数问题
  • ¥15 COCOS的问题COCOS的问题
  • ¥15 FPGA-SRIO初始化失败