php 简单的 Codeigniter 表单验证

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12832491/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 04:18:46  来源:igfitidea点击:

Simple Codeigniter form validation

phpcodeigniter

提问by Cignitor

I am having some problem in my login form like this

我在登录表单中遇到了这样的问题

enter image description here

在此处输入图片说明

I want to display an individually error beside of each field

我想在每个字段旁边显示一个单独的错误

here is the controller

这是控制器

function index()
{      
        $this->form_validation->set_rules('username','Username','trim|required|exact_length[4]|xss_clean');
        $this->form_validation->set_rules('password','Password','trim|required|min_length[4]|max_length[40]|xss_clean|callback_login');
        $this->form_validation->set_rules('jabatan','Jabatan','trim|required|xss_clean');

        if($this->form_validation->run() == false)
        {
            $this->load->view('login');
        }
        else
        {
            $this->load->view('welcome_message');
        }

}

function login()
{
    $username = $this->input->post('username');
    $password = $this->input->post('password');
    $jabatan = $this->input->post('jabatan');

    $value = $this->m_login->login($username,$password,$jabatan);

    if($value)
    {
        return true;
    }
    else
    {
        $this->form_validation->set_message('login', 'password salah');
        //delete redirect() and showing blank white screen
        return false;

    }

I made the <?php echo form_error(); ?>beside each field

<?php echo form_error(); ?>在每个领域的旁边

<?php echo form_open('c_login/login'); ?>
            <table>
                <tr>
                    <td>Username</td>
                    <td><?php $inusername=array('name' => 'username', 'class' => 'GUI'); echo form_input($inusername); ?></td>
                    <td class="error"><?php echo form_error('username'); ?></td>
                </tr>

                <tr>
                    <td>Password</td>
                    <td><?php $inpassword=array('name' => 'password', 'class' => 'GUI', 'type' =>'password'); echo form_input($inpassword); ?></td>
                    <td class="error"><?php echo form_error('password'); echo $this->session->flashdata('login'); ?></td>
                </tr>

                <tr>
                    <td>Jabatan</td>
                    <td><?php $injabatan=array('keuangan' => 'keuangan', 'admin' => 'admin', 'hd' => 'head divisi', 'direktur' => 'direktur'); echo form_dropdown('jabatan',$injabatan,'keuangan','class = "gui"'); ?></td>
                    <td class="error"><?php echo form_error('jabatan'); ?></td>
                </tr>

                 <tr>
                    <td></td>
                    <td><?php $insubmit=array('name' =>'login','class' =>'button','value' => 'Login'); echo form_submit($insubmit); echo nbs(); $inreset=array('name' =>'reset','class' =>'button','value' => 'Hapus'); echo form_reset($inreset); ?></td>
                    <td class="error"><?php echo form_error(); ?></td>
                </tr>
            </table>
            <?php echo form_close(); ?>

How come the form_error()function is not echoing anything when I click login with the usernameand passwordfield left blank?

当我单击登录时,为什么该form_error()功能没有echo任何内容,username并且 和password字段留空?

采纳答案by umefarooq

you know problem in your validation you're checking validation in index method of your class not in login method of your class and in your form you have given action to ci_login/login method which is redirecting if login is failed and its clearing form validation validate your fields on login method also and put all error message in session and display, i have made some changes in script have look here on this link Code modified

您知道验证中的问题 您正在检查类的 index 方法中的验证,而不是类的登录方法,并且在表单中,您已对 ci_login/login 方法执行操作,如果登录失败则重定向,其清除表单验证验证您的登录方法字段也将所有错误消息放在会话和显示中,我对脚本进行了一些更改,请查看此链接代码修改

for this changes you have to use url helper

对于此更改,您必须使用 url helper

function index()
{
    $this->form_validation->set_rules('username','Username','trim|required|exact_length[4]|xss_clean');
    $this->form_validation->set_rules('password','Password','trim|required|min_length[4]|max_length[40]|xss_clean|callback_login');
    $this->form_validation->set_rules('jabatan','Jabatan','trim|required|xss_clean');

    if($this->form_validation->run() == false)
    {
        $this->load->view('login');
    }
    else
    {
        //to check if the validation run correctly
        //$this->load->view('welcome_message');

        $username = $this->input->post('username');
        $password = $this->input->post('password');
        $jabatan = $this->input->post('jabatan');

        $value = $this->m_login->login($username,$password,$jabatan);

        if($value)
        {
            redirect('welcome_message');
            //return true;
        }
        else
        {
            $this->form_validation->set_message('login', 'password salah');
            redirect('c_login',$login); //i want to pass $login into login form, then print
            return false;               //them as a form_error

        }
    }

}


<?php echo form_open(uri_string()); ?>
<table>
    <tr>
        <td>Username</td>
        <td><?php $inusername=array('name' => 'username', 'class' => 'GUI'); echo form_input($inusername); ?></td>
        <td class="error"><?php echo form_error('username'); ?></td>
    </tr>

    <tr>
        <td>Password</td>
        <td><?php $inpassword=array('name' => 'password', 'class' => 'GUI', 'type' =>'password'); echo form_input($inpassword); ?></td>
        <td class="error"><?php echo form_error('password'); echo $this->session->flashdata('login'); ?></td>
    </tr>

    <tr>
        <td>Jabatan</td>
        <td><?php $injabatan=array('keuangan' => 'keuangan', 'admin' => 'admin', 'hd' => 'head divisi', 'direktur' => 'direktur'); echo form_dropdown('jabatan',$injabatan,'keuangan','class = "gui"'); ?></td>
        <td class="error"><?php echo form_error('jabatan'); ?></td>
    </tr>

     <tr>
        <td></td>
        <td><?php $insubmit=array('name' =>'login','class' =>'button','value' => 'Login'); echo form_submit($insubmit); echo nbs(); $inreset=array('name' =>'reset','class' =>'button','value' => 'Hapus'); echo form_reset($inreset); ?></td>
        <td class="error"><?php echo form_error(); ?></td>
    </tr>
</table>
<?php echo form_close(); ?>

回答by Jordan Arseno

indexwill not execute when logindoes.

index不会在执行时login执行。

If appears that maybe you think the set_rules()functions will execute when you submit the form. They won't. The form will submit to 'c_login/login', which is the login()function inside your c_logincontroller.

如果出现,也许您认为这些set_rules()功能会在您提交表单时执行。他们不会。表单将提交到'c_login/login',这是login()您的c_login控制器中的函数。

You need to move your form validation logic into login(), and have index()just echo the view for the first time.

您需要将表单验证逻辑移到 中login(),并且index()第一次回显视图。

Your Controller

您的控制器

function index(){      
    $this->load->view('login');
}

function login(){
    $this->form_validation->set_rules('username','Username','trim|required|exact_length[4]|xss_clean');
    $this->form_validation->set_rules('password','Password','required|xss_clean|correct');
    $this->form_validation->set_rules('jabatan','Jabatan','trim|required|xss_clean');

    if($this->form_validation->run() == false){
        //your validation messages will be taken care of.
        $this->load->view('login');
    }
    else{
        $p = $this->input->post();
        if($this->m_login->login($p['username'],$p['password'],$p['jabatan'])){
            //redirect() user to logged in area.
        }
        else{
            $this->form_validation->set_message('login', 'password salah');
            $this->load->view('login');
        }
    }
}

Also, you shouldn't be trimming passwords. The space character is a perfectly valid suffix or prefix in a password. I've removed trimfor you. I've also removed the min_lengthand max_length. This is something you'd want to enforce on a signup page, are you sure it really adds any value on a login page?

此外,您不应该修剪密码。空格字符是密码中完全有效的后缀或前缀。我已经trim为你删除了。我还删除了min_lengthmax_length。这是您想要在注册页面上强制执行的内容,您确定它真的在登录页面上增加了任何价值吗?

回答by Laurence

You need to supply form_error() with the field:

您需要提供 form_error() 字段:

<?php echo form_error('username'); ?>

See more details here

在此处查看更多详细信息

回答by Kemal Fadillah

It looks to me that you have a big misunderstanding on how these things work. First of all, you don't need that redirect()call in login(). The redirect()functions will redirect the user to another page, and since neither CodeIgniter nor PHP keep an object between page requests, you'd lose everything (e.g. The form validation object and its error messages).

在我看来,您对这些事情的运作方式有很大的误解。首先,您不需要redirect()调用 in login()。这些redirect()函数会将用户重定向到另一个页面,并且由于 CodeIgniter 和 PHP 都没有在页面请求之间保留一个对象,因此您将丢失所有内容(例如表单验证对象及其错误消息)。

Also, you might want to prefix that login()method with an underscore (_), so that no one can access it through an HTTP request.

此外,您可能希望login()使用下划线 ( _)作为该方法的前缀,以便没有人可以通过 HTTP 请求访问它。

You should probably submit the form to the index()method instead of login(). Then, make sure you only run the validation on a POSTrequest.

您可能应该将表单提交给index()方法而不是login(). 然后,确保您只对POST请求运行验证。

function index()
{
    if ($_POST)
    {
        // run validation here
    }

    // ...
}

回答by Rishi Patel

**Simple form validation, image upload and captcha using codeigniter libraries**
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Login extends CI_Controller {

    public function __construct()
    {
        parent::__construct();
        $this->load->model('Loginmodel');

    }
    public function index()
    {
        $config = array(
            'img_path'      => 'uploadss/',
            'img_url'       => base_url().'uploadss/',
            'font_path'     => base_url().'system/fonts/texb.ttf',
            'img_width'     => '200',
            'img_height'    => 90,
            'word_length'   => 3,
            'font_size'     => 25
        );
        $captcha = create_captcha($config);

        // Unset previous captcha and set new captcha word
        $this->session->unset_userdata('captchaCode');
        $this->session->set_userdata('captchaCode', $captcha['word']);

        // Pass captcha image to view
        $fetch['captchaImg'] = $captcha['image'];

        $fetch['data'] = $this->Loginmodel->alldata();
        $this->load->view('login',$fetch);
    }

    public function loginerror()
    {
        $this->form_validation->set_rules('fname','first name','required|alpha');
        $this->form_validation->set_rules('lname','last name', 'required');
        $this->form_validation->set_rules('mobile', 'Mobile', 'required|numeric');
        $this->form_validation->set_rules('email', 'Email', 'trim|required|valid_email');
        $this->form_validation->set_rules('password', 'Password', 'required');
        $this->form_validation->set_rules('companyname', 'Companyname', 'required');
        $this->form_validation->set_rules('designation', 'Designation', 'required');
        $this->form_validation->set_rules('companysize', 'Companysize', 'required|numeric');

        if($this->form_validation->run())
        {
            $inputCaptcha = $this->input->post('captcha');
            $sessCaptcha = $this->session->userdata('captchaCode');
            if($inputCaptcha === $sessCaptcha)
            {
                echo 'Captcha code matched.';

                    $fname = $this->input->post('fname');
                    $lname = $this->input->post('lname');
                    $mobile = $this->input->post('mobile');
                    $email = $this->input->post('email');
                    $password = $this->input->post('password');
                    $companyname = $this->input->post('companyname');
                    $designation = $this->input->post('designation');
                    $companysize = $this->input->post('companysize');

                    $checkmobile = $this->Loginmodel->checkmobile($mobile,$email);

                    if($checkmobile)
                    {
                        $this->session->set_flashdata("danger","Mobile Number or Email exist.....");
                        return redirect('Login/index'); 
                    }
                    else
                    {
                        $insertdata = $this->Loginmodel->insert($fname,$lname,$mobile,$email,$password,$companyname,$designation,$companysize);
                        $this->session->set_flashdata("success","Record Inserted");
                        return redirect('Home/indexhome');
                    }   
                // }
                // else
                // {
                //  $this->session->set_flashdata("danger","Please fill all the values properly");
                //  $this->index();
                // }
            }
            else
            {
                echo 'Captcha code does not match, please try again.';
                $this->index();
            }
        }
        else
        {
            $this->session->set_flashdata("danger","Please fill all the values properly");
            $this->index();
        }
    }

    public function refresh(){
        // Captcha configuration
        $config = array(
            'img_path'      => 'uploadss/',
            'img_url'       => base_url().'uploadss/',
            'font_path'     => base_url().'system/fonts/texb.ttf',
            'img_width'     => '200',
            'img_height'    => 90,
            'word_length'   => 3,
            'font_size'     => 25
        );
        $captcha = create_captcha($config);

        $this->session->unset_userdata('captchaCode');
        $this->session->set_userdata('captchaCode',$captcha['word']);

        echo $captcha['image'];
    }

    public function upload($id)
    {
        if(!empty($_FILES['imagename']['name']))
        {
                $config['upload_path'] = 'uploadss/';
                $config['allowed_types'] = 'jpg|jpeg|png|gif';
                $config['file_name'] = $_FILES['imagename']['name'];

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

                if($this->upload->do_upload('imagename'))
                {
                    $uploadData = $this->upload->data();
                    $imagename = $uploadData['file_name'];
                }
                else
                {
                    echo "not upload";
                }
        }
        else
        {
            echo "error";
        }
        $this->load->view('uploadimage');
    }

    public function uploadimageerror()
    {
        if(!empty($_FILES['imagename']['name']))
        {
                $config['upload_path'] = 'uploadss/';
                $config['allowed_types'] = 'jpg|jpeg|png|gif';
                $config['file_name'] = $_FILES['imagename']['name'];

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

                if($this->upload->do_upload('imagename'))
                {
                    $uploadData = $this->upload->data();
                    $imagename = $uploadData['file_name'];
                }
                else
                {
                    echo "not upload";
                }
        }
        else
        {
            echo "error";
        }
    }

    public function deletedata($id)
    {
        $dele = $this->Loginmodel->delete($id);
        return redirect('Login/index');
    }
}
?>