在PHP中使用die函数来停止执行代码但保持在同一页面上

时间:2015-05-05 14:52:17

标签: php

我有一个表单,用户可以插入图像,它有验证,我使用die来停止执行其余的代码。这很好用,但是当用户点击提交时,它会将它们转到空白页面,而不是显示在表单上的错误,以允许它们输入信息。

以下是我正在使用的一些PHP代码:

//If the error number is greater than 0, there's an error.
if($_FILES['file_upload']['error'] > 0){
$uploadErr = "An error ocurred when uploading.";
die;

}

//Check if the file type is allowed.
if($_FILES['file_upload']['type'] != "jpg" && $_FILES['file_upload']['type'] != "png" && $_FILES['file_upload']['type'] != "jpeg" && $_FILES['file_upload']['type'] != "gif") { 
$uploadErr = "Unsupported file type, only jpg, png or gif allowed";
die;

}

//check the file size does not exceed the limit
if($_FILES['file_upload']['size'] > 500000){
$uploadErr = "File uploaded exceeds maximum upload size.";
die;

}

//Check that the file doesn't already exist (based on name).
if(file_exists('img/' . $_FILES['file_upload']['name'])){
$uploadErr = "File with that name already exists.";
die;

}

//check file is an actual image
if(!getimagesize($_FILES['file_upload']['tmp_name'])){
 $uploadErr = "Please ensure you are uploading an image.";
 die;

}

1 个答案:

答案 0 :(得分:1)

如果要显示错误消息,请将$uploadErr传递给die()

die($uploadErr);