【问题标题】:what is an alternative to exit(); without breaking pageexit() 的替代方法是什么;不分页
【发布时间】:2014-08-31 17:03:38
【问题描述】:

例如,现在当我使用die()exit() 终止脚本时,我的页面看起来已经损坏了一半,因为页面的html 的底部无法加载,因为它是使用include() 函数引入的。

那么有没有办法告诉 PHP “除了网页加载的其余部分,不允许执行任何其他命令”?

我正在使用它作为图片上传脚本。

前台:

但是当我上传了错误的文件类型或根本没有文件时,它会破坏我的网页,因为我设置了 exit();

我能做些什么来解决这个问题?这是我的代码,你会注意到 exit();'s

if (isset($_POST['submit']))
{
    $file_uniq_id = uniqid();

    // Access the $_FILES global variable for this specific file being uploaded
    // and create local PHP variables from the $_FILES array of information

    $fileName = $_FILES["uploaded_file"]["name"]; // The file name
    $fileTmpLoc = $_FILES["uploaded_file"]["tmp_name"]; // File in the PHP tmp folder
    $fileType = $_FILES["uploaded_file"]["type"]; // The type of file it is
    $fileSize = $_FILES["uploaded_file"]["size"]; // File size in bytes
    $fileErrorMsg = $_FILES["uploaded_file"]["error"]; // 0 for false... and 1 for true
    $kaboom = explode(".", $fileName); // Split file name into an array using the dot
    $fileExt = end($kaboom); // Now target the last array element to get the file extension

    // START PHP Image Upload Error Handling --------------------------------------------------

    if (!$fileTmpLoc)
    { // if file not chosen
        echo "ERROR: Please browse for a file before clicking the upload button.";
        exit();
    }
    else
    if ($fileSize > 5242880)
    { // if file size is larger than 5 Megabytes
        echo "ERROR: Your file was larger than 5 Megabytes in size.";
        unlink($fileTmpLoc); // Remove the uploaded file from the PHP temp folder
        exit();
    }
    else
    if (!preg_match("/.(gif|jpg|png)$/i", $fileName))
    {

        // This condition is only if you wish to allow uploading of specific file types

        echo "ERROR: Your image was not .gif, .jpg, or .png.";
        unlink($fileTmpLoc); // Remove the uploaded file from the PHP temp folder
        exit();
    }
    else
    if ($fileErrorMsg == 1)
    { // if file upload error key is equal to 1
        echo "ERROR: An error occured while processing the file. Try again.";
        exit();
    }

    // END PHP Image Upload Error Handling ----------------------------------------------------
    // Place it into your "uploads" folder mow using the move_uploaded_file() function

    $moveResult = move_uploaded_file($fileTmpLoc, "uploads/$fileName");

    // Check to make sure the move result is true before continuing

    if ($moveResult != true)
    {
        echo "ERROR: File not uploaded. Try again.";
        unlink($fileTmpLoc); // Remove the uploaded file from the PHP temp folder
        exit();
    }

    // unlink($fileTmpLoc); // Remove the uploaded file from the PHP temp folder
    // ---------- Include Adams Universal Image Resizing Function --------

    include_once ("libs/ak_php_img_lib_1.0.php");

    $target_file = "uploads/$fileName";
    $resized_file = "uploads/" . $file_uniq_id . "." . $fileExt;
    $resized_file_final = $file_uniq_id . "." . $fileExt;
    mysql_query("UPDATE users SET profile_image = '$resized_file_final' WHERE id = '$id' ");
    $wmax = 128;
    $hmax = 128;
    ak_img_resize($target_file, $resized_file, $wmax, $hmax, $fileExt);
    unlink($target_file);

    // ----------- End Adams Universal Image Resizing Function -----------
    // Display things to the page so you can see what is happening for testing purposes

    echo "The file named <strong>$fileName</strong> uploaded successfuly.<br /><br />";
    echo "It is <strong>$fileSize</strong> bytes in size.<br /><br />";
    echo "It is an <strong>$fileType</strong> type of file.<br /><br />";
    echo "The file extension is <strong>$fileExt</strong><br /><br />";
    echo "The Error Message output for this upload is: <strong>$fileErrorMsg</strong><br /><br />";
    echo "The new name for the file is: <strong>$resized_file_final</strong>";
}

【问题讨论】:

  • 不要在函数内部回显。将您的业务逻辑与您的表示层 (html) 分开
  • @Fred -ii- 这是什么意思...?
  • @BrianCherdak 你是什么意思?我想你可能已经看到了我对 Rakesh 的评论的评论;不用担心,一切都很好。现在,您可以尝试使用return; 看看它是否适合您,虽然不是 100% 确定它会起作用,但请尝试一下。
  • 我仍然有问题,我尝试了 break(); @matthew5025
  • 不要让 PHP 来弥补糟糕的编码。不要回显错误消息,将它们放在变量中。然后在代码的底部,你对图像做了所有聪明的事情,对错误消息变量进行测试,如果有错误就输出错误,否则做聪明的事情并输出图像信息

标签: php upload exit-code


【解决方案1】:

试试这个,想法是你必须完成整个脚本,这样你才能添加页脚,这样页面看起来就完整了。因此,不要在找到错误时回显错误然后退出脚本,而是将它们保存在变量中。然后,一旦您到达脚本的主要部分,即图像已加载并且您想要调整它的大小,您决定是否有错误仅输出错误而不进行图像调整大小。如果没有发现错误,那么您就可以修改图像并且不要输出任何错误消息。

if (isset($_POST['submit']))
{
    $file_uniq_id = uniqid();

    // Access the $_FILES global variable for this specific file being uploaded
    // and create local PHP variables from the $_FILES array of information

    $fileName = $_FILES["uploaded_file"]["name"]; // The file name
    $fileTmpLoc = $_FILES["uploaded_file"]["tmp_name"]; // File in the PHP tmp folder
    $fileType = $_FILES["uploaded_file"]["type"]; // The type of file it is
    $fileSize = $_FILES["uploaded_file"]["size"]; // File size in bytes
    $fileErrorMsg = $_FILES["uploaded_file"]["error"]; // 0 for false... and 1 for true
    $kaboom = explode(".", $fileName); // Split file name into an array using the dot
    $fileExt = end($kaboom); // Now target the last array element to get the file extension

    // START PHP Image Upload Error Handling 

    $Err = NULL;

    if (!$fileTmpLoc)
    { // if file not chosen
        $Err = "ERROR: Please browse for a file before clicking the upload button.";
    }
    else
    if ($fileSize > 5242880)
    { // if file size is larger than 5 Megabytes
        $Err = "ERROR: Your file was larger than 5 Megabytes in size.";
        unlink($fileTmpLoc); // Remove the uploaded file from the PHP temp folder
    }
    else
    if (!preg_match("/.(gif|jpg|png)$/i", $fileName))
    {
        // This condition is only if you wish to allow uploading of specific file types

        $Err = "ERROR: Your image was not .gif, .jpg, or .png.";
        unlink($fileTmpLoc); // Remove the uploaded file from the PHP temp folder
    }
    else
    if ($fileErrorMsg == 1)
    { // if file upload error key is equal to 1
        $Err = "ERROR: An error occured while processing the file. Try again.";
    }

    // END PHP Image Upload Error Handling 
    // Place it into your "uploads" folder mow using the move_uploaded_file() function

    $moveResult = move_uploaded_file($fileTmpLoc, "uploads/$fileName");

    // Check to make sure the move result is true before continuing

    if ($moveResult != true) {
        $Err = "ERROR: File not uploaded. Try again.";
        // not needed PHP is supposed to do this
        // unlink($fileTmpLoc);
    }

    // ---------- Include Adams Universal Image Resizing Function --------

    if ( ! isset( $Err ) ) {    

        include_once ("libs/ak_php_img_lib_1.0.php");

        $target_file = "uploads/$fileName";
        $resized_file = "uploads/" . $file_uniq_id . "." . $fileExt;
        $resized_file_final = $file_uniq_id . "." . $fileExt;
        mysql_query("UPDATE users 
                     SET profile_image = '$resized_file_final' 
                     WHERE id = '$id' ");
        $wmax = 128;
        $hmax = 128;
        ak_img_resize($target_file, $resized_file, $wmax, $hmax, $fileExt);
        unlink($target_file);

        // ----------- End Adams Universal Image Resizing Function -----------
        // Display things to the page so you can see what is happening for testing purposes

        // as we had to process error in this if we better test again
        echo "The file named <strong>$fileName</strong> uploaded successfuly.<br /><br />";
        echo "It is <strong>$fileSize</strong> bytes in size.<br /><br />";
        echo "It is an <strong>$fileType</strong> type of file.<br /><br />";
        echo "The file extension is <strong>$fileExt</strong><br /><br />";
        echo "The Error Message output for this upload is: <strong>$fileErrorMsg</strong><br /><br />";
        echo "The new name for the file is: <strong>$resized_file_final</strong>";

    } else {
       echo $Err;
    }
}

【讨论】:

    【解决方案2】:

    通常functions 用于将代码组合在一起。然后,您可以使用 return; 语句中途停止函数。函数使代码保持有序和可重用。下一步是将相关函数放入类中,然后将生成输出(回显语句)和逻辑的代码分离到不同的类中,但这是一个新的范式供您掌握(查看面向对象编程 - OOP。这很难,但如果你想进步,这真的很重要)。

    作为将代码分组为函数的示例,可以将 if 语句中的代码放入 uploadFile 函数中,如下所示:

    <?php
    
    function uploadFile($id, $file) {
        $file_uniq_id = uniqid();
    
        // Access the $_FILES global variable for this specific file being uploaded
        // and create local PHP variables from the $_FILES array of information
    
        $fileName = $file["name"]; // The file name
        $fileTmpLoc = $file["tmp_name"]; // File in the PHP tmp folder
        $fileType = $file["type"]; // The type of file it is
        $fileSize = $file["size"]; // File size in bytes
        $fileErrorMsg = $file["error"]; // 0 for false... and 1 for true
        $kaboom = explode(".", $fileName); // Split file name into an array using the dot
        $fileExt = end($kaboom); // Now target the last array element to get the file extension
    
        // START PHP Image Upload Error Handling --------------------------------------------------
    
        if (!$fileTmpLoc)
        { // if file not chosen
            echo "ERROR: Please browse for a file before clicking the upload button.";
            return;
        }
        else
        if ($fileSize > 5242880)
        { // if file size is larger than 5 Megabytes
            echo "ERROR: Your file was larger than 5 Megabytes in size.";
            unlink($fileTmpLoc); // Remove the uploaded file from the PHP temp folder
            return;
        }
        else
        if (!preg_match("/.(gif|jpg|png)$/i", $fileName))
        {
    
            // This condition is only if you wish to allow uploading of specific file types
    
            echo "ERROR: Your image was not .gif, .jpg, or .png.";
            unlink($fileTmpLoc); // Remove the uploaded file from the PHP temp folder
            return;
        }
        else
        if ($fileErrorMsg == 1)
        { // if file upload error key is equal to 1
            echo "ERROR: An error occured while processing the file. Try again.";
            return;
        }
    
        // END PHP Image Upload Error Handling ----------------------------------------------------
        // Place it into your "uploads" folder mow using the move_uploaded_file() function
    
        $moveResult = move_uploaded_file($fileTmpLoc, "uploads/$fileName");
    
        // Check to make sure the move result is true before continuing
    
        if ($moveResult != true)
        {
            echo "ERROR: File not uploaded. Try again.";
            unlink($fileTmpLoc); // Remove the uploaded file from the PHP temp folder
            return;
        }
    
        // unlink($fileTmpLoc); // Remove the uploaded file from the PHP temp folder
        // ---------- Include Adams Universal Image Resizing Function --------
    
        include_once ("libs/ak_php_img_lib_1.0.php");
    
        $target_file = "uploads/$fileName";
        $resized_file = "uploads/" . $file_uniq_id . "." . $fileExt;
        $resized_file_final = $file_uniq_id . "." . $fileExt;
        mysql_query("UPDATE users SET profile_image = '$resized_file_final' WHERE id = '$id' ");
        $wmax = 128;
        $hmax = 128;
        ak_img_resize($target_file, $resized_file, $wmax, $hmax, $fileExt);
        unlink($target_file);
    
        // ----------- End Adams Universal Image Resizing Function -----------
        // Display things to the page so you can see what is happening for testing purposes
    
        echo "The file named <strong>$fileName</strong> uploaded successfuly.<br /><br />";
        echo "It is <strong>$fileSize</strong> bytes in size.<br /><br />";
        echo "It is an <strong>$fileType</strong> type of file.<br /><br />";
        echo "The file extension is <strong>$fileExt</strong><br /><br />";
        echo "The Error Message output for this upload is: <strong>$fileErrorMsg</strong><br /><br />";
        echo "The new name for the file is: <strong>$resized_file_final</strong>";
    }
    
    if (isset($_POST['submit']))
    {
        uploadFile($id, $_FILES["uploaded_file"]);
    }
    

    虽然这还远不是组织良好的代码,但它通过将 exit() 替换为 return; 来解决您的问题。

    【讨论】:

    • 这似乎工作得很好,但是一个小错误,一个变量没有设置 $id 但它是,上面$id = $_GET['id']; $id = stripslashes($id); $id = mysql_real_escape_string($id); // GET id is set and not empty and is numeric if (isset($id) &amp;&amp; !empty($id) &amp;&amp; is_numeric($id)) { $id = intval($_GET['id']); } // Else take value from session, if not empty and is numeric elseif (isset($_SESSION['id']) &amp;&amp; !empty($_SESSION['id']) &amp;&amp; is_numeric($_SESSION['id'])) { $id = intval($_SESSION['id']); }
    • 查看更新版本。我将 $id 作为参数添加到函数中,并在函数调用中传递您在上面代码中设置的原始 $id。
    • 谢谢,还有一件小事,我设置它只能上传某些类型的文件,但是当我尝试上传 pdf 文件时,这是不允许的,它会尝试处理它并给我警告错误Warning: move_uploaded_file(/tmp/phpSsaO6r) [function.move-uploaded-file]: failed to open stream: No such file or directory in /home/u315295673/public_html/new/profile_pic.php on line 285 Warning: move_uploaded_file() [function.move-uploaded-file]: Unable to move '/tmp/phpSsaO6r' to 'uploads/pics.pdf' in /home/u315295673/public_html/new/profile_pic.php on line 285
    • 我以为我有 if 语句可以自动显示错误,如果它不是 gif、png 或 jpg。,它们是如何得到的?
    • 我尝试将其从 if (!preg_match("/.(gif|jpg|png)$/i", $fileName)) { 更改为 if (($fileName == "image/gif") || ($fileName == "image/jpeg") || ($fileName == "image/png" )) {,但现在它似乎允许任何文件。
    猜你喜欢
    • 2021-01-07
    • 1970-01-01
    • 2022-11-13
    • 2015-01-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多