如果 $config['base_url'] 不为空且 $config['index_page'] 为空,则在 Codeigniter 中上传文件时出现问题



我在代码点火器示例中介绍了如何上传文件,如https://www.codeigniter.com/userguide3/libraries/file_uploading.html而且效果很好。

// Default values in config.php      
$config['base_url'] = '';
$config['index_page'] = 'index.php';

然而,在我根据自己的需要编辑了config.php之后,我无法使其工作。

// My desired values in config.php
$config['base_url'] = 'http://'.$_SERVER['HTTP_HOST'].'/sample';
$config['index_page'] = '';

我的.htaccess看起来是这样的(我实际上不知道这意味着什么(:

RewriteEngine On
RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} ^www. [NC]
RewriteCond %{HTTP_HOST} ^(?:www.)?(.+)$ [NC]
RewriteRule ^ https://%1%{REQUEST_URI} [L,NE,R=301]
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^ index.php [L]
</IfModule> 

当我用empty($_FILES['userfile']['name'])检查时,它显示为空,并错误地显示

您没有选择要上载的文件。

upload_form.php

<html>
<head>
<title>Upload Form</title>
</head>
<body>
<?php echo $error;?>
<?php echo form_open_multipart('upload/do_upload');?>
<input type="file" name="userfile" size="20" />
<br /><br />
<input type="submit" value="upload" />
</form>
</body>
</html>

控制器

<?php
class Upload extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->helper(array('form', 'url'));
}
public function index() {
$this->load->view('upload_form', array('error' => ' ' ));
}
public function do_upload() {
$config['upload_path']          = './uploads/';
$config['allowed_types']        = 'gif|jpg|png';
$config['max_size']             = 100;
$config['max_width']            = 1024;
$config['max_height']           = 768;
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload('userfile')) {
$error = array('error' => $this->upload->display_errors());
$this->load->view('upload_form', $error);
} else {
$data = array('upload_data' => $this->upload->data());
$this->load->view('upload_success', $data);
}
}
}
?>

在config.php中,我应该如何调用要上传的带有首选值的文件?

试试这个:

替换此代码:

// My desired values in config.php
$config['base_url'] = 'http://'.$_SERVER['HTTP_HOST'].'/sample';
$config['index_page'] = '';

使用此:

// My desired values in config.php
$http = 'http' . ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') ? 
's' : '') . '://';
$newurl = str_replace("index.php", "", $_SERVER['SCRIPT_NAME']);
$config['base_url']    = "$http" . $_SERVER['SERVER_NAME'] . "" . $newurl;
$config['index_page'] = '';

相关内容

最新更新