在我的Codeigniter控制器中有以下私有函数,用于验证文件上传。
private function avatar_file_validation()
{
$config['upload_path'] = './uploads/avatars/';
$config['allowed_types'] = 'jpg|png';
$config['overwrite'] = TRUE; //overwrite user avatar
$config['max_size'] = '800'; //in KB
$this->load->library('upload', $config);
if (! $this->upload->do_upload('avatar_upload'))
{
$error_data = array('error' => $this->upload->display_errors());
$this->avatar_view($error_data); //loads view
return FALSE;
}
}
如果上传时发生错误我想停止此功能继续
function upload_avatar()
{
//some code
if($_FILES['entry_upload']['error'] !== 4) //if file added to file field
{
$this->avatar_file_validation(); //if returns FALSE stop code
}
//code continues: adds data to database, redirects
}
然而,即使返回false,该功能仍会继续。它只适用于我在1个函数中使用整个代码但我需要将它们分开,因为我将在多个函数中使用上传验证。我在这里做错了什么?
答案 0 :(得分:2)
表达式return FALSE;
仅适用于函数avatar_file_validation()
。如果您想在上传失败时停止upload_avatar()
中的代码,则应检查avatar_file_validation()
的输出,如果它等于FALSE
,也要从该函数返回。
例如:
function upload_avatar()
{
//some code
if($_FILES['entry_upload']['error'] !== 4) //if file added to file field
{
if(!$this->avatar_file_validation()) //if returns FALSE stop code
return FALSE;
}
//code continues: adds data to database, redirects
}
答案 1 :(得分:2)
function upload_avatar()
{
//some code
if(!$_FILES['entry_upload']['error'] !== 4) //if file added to file field
{
if($this->avatar_file_validation()){
return FALSE;
}
}
//code continues: adds data to database, redirects
}