通过表单上传文件

时间:2014-11-27 14:46:04

标签: php codeigniter

我想让我的用户选择上传csv文件并用它填充数据库表。

<?php echo validation_errors(); ?>

<?php echo form_open_multipart('funding/create') ?>

<input type="hidden" name="MAX_FILE_SIZE" value="100000" /> Choose a file to upload: <input name="uploadedfile" type="file" /><br />

    <input type="submit" name="submit" value="Create Funding Record" />

我在资助控制器中的职能:

public function create()
{
    $this->load->helper('form');
    $this->load->library('form_validation');

    $uploaded = false;

    $target_path  =  "";
    $target_path  =  $target_path  .  basename($_FILES['uploadedfile']['name']);
    if (move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
        $uploaded = true;
    } 



    if (!$uploaded)
    {

        $this->load->view('funding/create');

    }
    else
    {
        //$this->funding_model->insert_funding();
        $this->load->view('funding/success');
    }
}

(目前,我只进入了我想要检查文件已上传的阶段。但是,CI返回:

A PHP Error was encountered

Severity: Notice

Message: Undefined index: uploadedfile

Filename: controllers/funding.php

Line Number: 30

我用我制作的模拟非ci形式测试了代码并且它工作了......有什么想法吗? :/我认为$ _FILE是一个全局的php参数。

2 个答案:

答案 0 :(得分:0)

我对CI不太常见,但您应该使用form_open_multipart代替form_open来添加上传文件所需的multipart属性。

答案 1 :(得分:0)

不要访问$_FILES。我认为CI出于安全原因禁用它们。您需要使用他们的上传类(它也可以为您提供安全性,例如XSS过滤)。文档在这里:https://ellislab.com/codeigniter/user-guide/libraries/file_uploading.html

基本上使用这个(来自他们的文档,我自己添加了一些评论):

//Choose the upload path of your server here, 
//make sure it is chmodded to 777 otherwise it will never work
$config['upload_path'] = './uploads/'; 
$config['allowed_types'] = 'csv'; //Only allow csv
$config['max_size'] = '100000'; //Also check this server side!!!

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

//Add the file input form name here
if ( ! $this->upload->do_upload('uploadedfile')) 
{
    $this->load->view('funding/create'); 
}
else
{
    $data = array('upload_data' => $this->upload->data());
    //$data contains filename etc. Update DB here.
    $this->load->view('funding/success');
}

请注意,您的代码非常不安全(例如,不检查扩展名)。恶意用户只需将PHP文件上传到您的服务器然后执行它,可能会破坏您的服务器/网站/数据库/等。您必须进行安全检查!