我想检查用户是否在我的textarea中添加了某些内容,或者是否添加了图像。我怎么能在codeigniter中做到这一点?
我的情况是,他可以仅发布文字和图片或文字或仅发布图片,但其中任何一个都不能为空。
但是当我尝试它时,它不起作用。即使我添加了图像,我总是会得到2为空的错误。
变量:
textarea = body
file = image_upload
if ($_POST) {
if (empty($_POST['body']) == true && !isset($_POST['image_upload']))
{
//no message & image
header("location:". $_POST['base_url'] . '?error_post');
}
elseif(empty($_POST['body']) == false && !isset($_POST['image_upload']))
{
//message only
}
elseif (empty($_POST['body']) == true && isset($_POST['image_upload']) == true) {
//image only
$config['upload_path'] = './public/uploads/';
$config['allowed_types'] = 'gif|jpg|png|jpeg';
$config['max_size'] = '100';
$config['max_width'] = '1024';
$config['max_height'] = '768';
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload())
{
$error = array('error' => $this->upload->display_errors());
//$this->load->view('upload_form', $error);
var_dump($error);
die();
}
else
{
$data = array('upload_data' => $this->upload->data());
//$this->load->view('upload_success', $data);
var_dump($data);
die();
}
}
else{
//both message & image
var_dump($_POST);
}
}
答案 0 :(得分:0)
form_validation可以为您提供帮助,https://ellislab.com/codeigniter/user-guide/libraries/form_validation.html
尝试这样的事情:
<?php
$this->form_validation->set_rules('body','body','required');
$config['upload_path'] = './public/uploads/';
$config['allowed_types'] = 'gif|jpg|png|jpeg';
$config['max_size'] = '100';
$config['max_width'] = '1024';
$config['max_height'] = '768';
$this->upload->initialize($config);
$this->load->library('upload', $config);
if($this->form_validation->run())
{
$image_data = $this->upload->data();
$image_name = $image_data['file_name'];
$data = array(
'image_upload'=>$image_name,
'body'=>$this->input->post('body')
);
$this->MyModel->create($data);
redirect('...');
}else{
if(!$this->upload->do_upload('image_upload'))
{
redirect('...');
}
else
{
$image_data = $this->upload->data();
$image_name = $image_data['file_name'];
$data = array(
'image_upload'=>$image_name
);
$this->MyModel->create($data);
redirect('...');
}
}