Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/258.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 在Codeigniter 3中上载时,如何显示不允许的文件类型错误消息?_Php_Validation_Codeigniter 3 - Fatal编程技术网

Php 在Codeigniter 3中上载时,如何显示不允许的文件类型错误消息?

Php 在Codeigniter 3中上载时,如何显示不允许的文件类型错误消息?,php,validation,codeigniter-3,Php,Validation,Codeigniter 3,我正在使用Codeigniter 3.1.8和Bootstrap 4开发一个基本的 当然,这些帖子都有主要的图像。如果用户没有上传图像,则会有一个默认图像,但如果上传图像,则只允许3种类型:jpg、jpeg和png 为了在用户试图上传其他文件格式时警告用户,我在Posts控制器中这样做: // Upload image $config['upload_path'] = './assets/img/posts'; $config['allowed_types'] = 'jpg|jpeg|png';

我正在使用Codeigniter 3.1.8Bootstrap 4开发一个基本的

当然,这些帖子都有主要的图像。如果用户没有上传图像,则会有一个默认图像,但如果上传图像,则只允许3种类型:jpg、jpeg和png

为了在用户试图上传其他文件格式时警告用户,我在Posts控制器中这样做:

// Upload image
$config['upload_path'] = './assets/img/posts';
$config['allowed_types'] = 'jpg|jpeg|png';
$config['max_size'] = '2048';

$this->load->library('upload', $config);

if(!$this->upload->do_upload()){

    $data['uerrors'] = $this->upload->display_errors();

    if ($data['uerrors']) {
        $this->load->view('partials/header', $data);
        $this->load->view('dashboard/create-post');
        $this->load->view('partials/footer');
    } else {
        $post_image = 'default.jpg';
    }

} else {
    $data = array('upload_data' => $this->upload->data());
    $post_image = $_FILES['userfile']['name'];
}
我认为:

<?php foreach ($uerrors as $uerror): ?>
  <span><?php echo $uerror; ?></span>
<?php endforeach; ?>
<?php if(isset($upload_errors)){
   foreach ($upload_errors as $upload_error) {
    echo $upload_error;
   }
 }?>

我的错误在哪里?

此错误告诉您变量不存在或未初始化。看看这个代码

$data['uerrors'] = $this->upload->display_errors();

if ($data['uerrors']) {

我认为您可能有一个
$uerrors
变量(未在代码中显示)未初始化。请注意,我不相信
数组
索引
'uerrors'
会在上面的块中给您带来麻烦,因为首先您定义了它,其次,如果您引用了一个不存在的
数组
项,然后,您将收到与问题中引用的错误消息不同的错误消息。

您的问题有点模糊。无论如何,变量
$uerrors
将设置的唯一条件是
create()
方法将执行的时间,我相信该方法将在POST请求时执行。此外,您没有提到这是视图的哪一部分:

<?php foreach ($uerrors as $uerror): ?>
  <span><?php echo $uerror; ?> </span>
<?php endforeach; ?>

您的上传代码看起来不错,但您需要更新以下更改

  • 将数据传递到
    'dashboard/create post'
    视图,就像传递到
    'partials/header'
    视图一样。您的
    'dashboard/create post'
    视图未收到任何上载错误消息,因此它表示
    'Undefined variable:uerrors'
    。所以,你的上传代码应该是这样的-
  • 正如前面所说,“display_errors()”返回字符串,而不是数组,您不必遍历错误。只需在您的
    “仪表板/创建帖子”
    视图中回显即可
  • 为方便起见,请使用不同的方法执行上载任务,以便您也可以在更新方法中重复使用此方法。举例来说-

    private function uploadFile(){
        if ($_FILES['userfile']['name'] === '') {
            return array(
                'status' => TRUE,
                'message' => 'No file selected.',
                'file_name' => 'default.jpg'
            );
        }
    
        // Upload image
        $config['upload_path'] = './assets/img/posts';
        $config['allowed_types'] = 'jpg|jpeg|png';
        $config['max_size'] = '2048';
    
        $this->load->library('upload', $config);
    
        if(!$this->upload->do_upload('userfile')){
            return array(
                'status' => FALSE,
                'message' => $this->upload->display_errors('<p class="text-danger ">', '</p>'),
                'file_name' => ''
            );
        }else{
            return array(
                'status' => TRUE,
                'message' => 'File uploaded successfully',
                'file_name' => $this->upload->data('file_name')
            );
        }
    }
    

    我认为所有这些都应该工作。

    您需要将$data['uerrors']初始化为null,因为您正在前端使用它

    $data['uerrors'] = '';
    
    或者检查前端上的值是否不为空

    前端,您可以通过以下方式执行此操作:

    <?php  if (isset($uerrors) && $uerrors != '') {
                foreach ($uerrors as $uerror) {
                    echo '<span>' . $uerror . '</span>';
                }
            } ?>
    

    你还可以在

    上找到有用的帖子我在这里学到了三件事

    1) 没有像前面提到的那样将$data传递到正确的视图

    2) 视图上应为数组而不是字符串,即数据类型错误

    3) 最后,函数do_upload()需要参数字符串$field。这是丢失的,这就是为什么您只有“无上载选择”错误。如果设置了这个参数,codeigniter会抛出错误的文件类型错误。我这样做是为了测试

    依我看

    <form action="http://localhost:8000/welcome/create" method="post" enctype="multipart/form-data">
              <input type="file" name="lname" ><br>
              <input type="submit" value="Submit">
            </form>
    

    上载错误的文件类型以测试此错误。您可能需要额外的长度来检测实际上载文件的文件类型。

    通过以下方式修改
    create()
    ,我已成功显示上载错误(如果尝试上载,则使用默认图像):

    public function create() {
    
        // Only logged in users can create posts
        if (!$this->session->userdata('is_logged_in')) {
            redirect('login');
        }
    
        $data = $this->get_data();
        $data['tagline'] = "Add New Post";
    
        if ($data['categories']) {
            foreach ($data['categories'] as &$category) {
                $category->posts_count = $this->Posts_model->count_posts_in_category($category->id);
            }
        }
    
        $this->form_validation->set_rules('title', 'Title', 'required');
        $this->form_validation->set_rules('desc', 'Short description', 'required');
        $this->form_validation->set_rules('body', 'Body', 'required');
        $this->form_validation->set_error_delimiters('<p class="error-message">', '</p>');
    
        if($this->form_validation->run() === FALSE){
            $this->load->view('partials/header', $data);
            $this->load->view('dashboard/create-post');
            $this->load->view('partials/footer');
        } else {
            // Create slug (from title)
            $slug = url_title(convert_accented_characters($this->input->post('title')), 'dash', TRUE);
            $slugcount = $this->Posts_model->slug_count($slug, null);
            if ($slugcount > 0) {
                $slug = $slug."-".$slugcount;
            }
    
            // Upload image
            $config['upload_path'] = './assets/img/posts';
            $config['allowed_types'] = 'jpg|jpeg|png';
            $config['max_size'] = '2048';
    
            $this->load->library('upload', $config);
    
            if(!$this->upload->do_upload()){
    
                $errors = array('error' => $this->upload->display_errors());
    
                // Display upload validation errors 
                // only if a file is uploaded and there are errors
                if (empty($_FILES['userfile']['name'])) {
                    $errors = [];
                }
    
                if (empty($errors)) {
                    $post_image = 'default.jpg';
                } else {
                    $data['upload_errors'] = $errors;
                }
    
            } else {
                $data = array('upload_data' => $this->upload->data());
                $post_image = $_FILES['userfile']['name'];
            }
    
            if (empty($errors)) {
                $this->Posts_model->create_post($post_image, $slug);
                $this->session->set_flashdata('post_created', 'Your post has been created');
                redirect('/');
            } else {
                $this->load->view('partials/header', $data);
                $this->load->view('dashboard/create-post');
                $this->load->view('partials/footer');
            }
        }
    }
    

    我知道,但我确实将它传递给了
    $data
    ,那么为什么会出现错误?我发布了整个
    create()
    方法。@RazvanZamfir它在哪一行崩溃?是不是
    if($data['uerrors')){
    请查看整个控制器,也许这会澄清问题。感谢您的帮助。:)此外,我还检查了视图,没有找到任何foreach循环,以便验证。是正确的文件还是另一个文件?我没有将该部分推送到GitHub,它会引发错误。:)我需要的是一种方法,告诉用户她/他试图加载错误的文件类型(例如PDF),并非没有上载文件。如果没有上载文件,则存在默认图像(请参见
    $config['allowed_types']='jpg|jpeg|png';
    ).CodeIgniter不提供任何自定义上载错误消息的选项。相反,您可以执行以下操作-1.告诉用户在创建帖子页面中支持上载哪些文件类型。2.在文件输入中使用
    accept
    属性。在选择文件时,它将仅显示接受的文件类型。有关详细信息,请检查
    W3Schools
    属性用法。我已经更新了
    uploadFile()
    方法。请用更新的方法替换代码。我自己提供了一个答案,它对
    create()
    方法非常有效。但是
    update()给我带来了很大的困难
    。请看一看。谢谢!:)这对我来说很有用。检查变量是否为null是解决方案。
    $data['uerrors'] = '';
    
    <?php  if (isset($uerrors) && $uerrors != '') {
                foreach ($uerrors as $uerror) {
                    echo '<span>' . $uerror . '</span>';
                }
            } ?>
    
     $data = array();
            // Upload image
            $config['upload_path'] = './assets/img/posts';
            $config['allowed_types'] = 'jpg|jpeg|png';
            $config['max_size'] = '2048';
    
            $this->load->library('upload', $config);
    
            /*You need to initialize  $data['uerrors'] as null because you are using it on front end*/
            $data['uerrors'] = '';
            if (!$this->upload->do_upload('FilePath')) {
                $data['uerrors'] = $this->upload->display_errors();
                $this->load->view('partials/header', $data);
                $this->load->view('dashboard/create-post');
                $this->load->view('partials/footer');
            } else {
                if (isset($_POST{'your_file'})) {
                    /*'check your images here that you are receiving from front end'*/
                } else {
                    /*If there is no image, then default image is*/
                    $post_image = 'default.jpg';
                }
                $data = array('upload_data' => $this->upload->data());
                $post_image = $_FILES['userfile']['name'];
            }
    
    <form action="http://localhost:8000/welcome/create" method="post" enctype="multipart/form-data">
              <input type="file" name="lname" ><br>
              <input type="submit" value="Submit">
            </form>
    
    if(!$this->upload->do_upload("lname")){
    
    public function create() {
    
        // Only logged in users can create posts
        if (!$this->session->userdata('is_logged_in')) {
            redirect('login');
        }
    
        $data = $this->get_data();
        $data['tagline'] = "Add New Post";
    
        if ($data['categories']) {
            foreach ($data['categories'] as &$category) {
                $category->posts_count = $this->Posts_model->count_posts_in_category($category->id);
            }
        }
    
        $this->form_validation->set_rules('title', 'Title', 'required');
        $this->form_validation->set_rules('desc', 'Short description', 'required');
        $this->form_validation->set_rules('body', 'Body', 'required');
        $this->form_validation->set_error_delimiters('<p class="error-message">', '</p>');
    
        if($this->form_validation->run() === FALSE){
            $this->load->view('partials/header', $data);
            $this->load->view('dashboard/create-post');
            $this->load->view('partials/footer');
        } else {
            // Create slug (from title)
            $slug = url_title(convert_accented_characters($this->input->post('title')), 'dash', TRUE);
            $slugcount = $this->Posts_model->slug_count($slug, null);
            if ($slugcount > 0) {
                $slug = $slug."-".$slugcount;
            }
    
            // Upload image
            $config['upload_path'] = './assets/img/posts';
            $config['allowed_types'] = 'jpg|jpeg|png';
            $config['max_size'] = '2048';
    
            $this->load->library('upload', $config);
    
            if(!$this->upload->do_upload()){
    
                $errors = array('error' => $this->upload->display_errors());
    
                // Display upload validation errors 
                // only if a file is uploaded and there are errors
                if (empty($_FILES['userfile']['name'])) {
                    $errors = [];
                }
    
                if (empty($errors)) {
                    $post_image = 'default.jpg';
                } else {
                    $data['upload_errors'] = $errors;
                }
    
            } else {
                $data = array('upload_data' => $this->upload->data());
                $post_image = $_FILES['userfile']['name'];
            }
    
            if (empty($errors)) {
                $this->Posts_model->create_post($post_image, $slug);
                $this->session->set_flashdata('post_created', 'Your post has been created');
                redirect('/');
            } else {
                $this->load->view('partials/header', $data);
                $this->load->view('dashboard/create-post');
                $this->load->view('partials/footer');
            }
        }
    }
    
    <?php if(isset($upload_errors)){
       foreach ($upload_errors as $upload_error) {
        echo $upload_error;
       }
     }?>