Hello,

I am following this tutorial: http://www.codefactorycr.com/login-with-codeigniter-php.html

It works when I copy it exactly as it is. Now, I only wonder why eventhough I try to imitate it and modify it a little bit to match my system, I wonder why it still does not work ?

views/admin/login_view.php

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <html xmlns="http://www.w3.org/1999/xhtml">
     <head>
       <title>Simple Login with CodeIgniter</title>
     </head>
     <body>
       <h1>Simple Login with CodeIgniter</h1>
       <?php echo validation_errors(); ?>
       <?php echo form_open('verifylogin'); ?>
         <label for="username">Username:</label>
         <input type="text" size="20" id="username" name="username"/>
         <br/>
         <label for="password">Password:</label>
         <input type="password" size="20" id="password" name="password"/>
         <br/>
         <input type="submit" value="Login"/>
       </form>
     </body>
    </html>

controllers/admin/verifylogin.php

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class VerifyLogin extends CI_Controller {

     function __construct()
     {
       parent::__construct();
       $this->load->model('user','',TRUE);
     }

     function index()
     {
       //This method will have the credentials validation
       $this->load->library('form_validation');

       $this->form_validation->set_rules('username', 'Username', 'trim|required|xss_clean');
       $this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean|callback_check_database');

       if($this->form_validation->run() == FALSE)
       {
         //Field validation failed.  User redirected to login page
         $this->load->view('admin/login_view');
       }
       else
       {
         //Go to private area
         redirect('home', 'refresh');
       }

     }

     function check_database($password)
     {
       //Field validation succeeded.  Validate against database
       $username = $this->input->post('username');

       //query the database
       $result = $this->user->login($username, $password);

     if($result)
       {
         $sess_array = array();
         foreach($result as $row)
         {
           $sess_array = array(
             'id' => $row->id,
             'username' => $row->username
           );
           $this->session->set_userdata('logged_in', $sess_array);
         }
         return TRUE;
       }
       else
       {
         $this->form_validation->set_message('check_database', 'Invalid username or password');
         return false;
       }
     }
    }

?>

controllers/admin/home.php

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

    session_start(); //we need to call PHP's session object to access it through CI

    class Home extends CI_Controller {

     function __construct()
     {
       parent::__construct();
     }

     function index()
     {
       if($this->session->userdata('logged_in'))
       {
         $session_data = $this->session->userdata('logged_in');
         $data['username'] = $session_data['username'];
         $this->load->view('admin/admin', $data);
       }
       else
       {
         //If no session, redirect to login page
         redirect('login', 'refresh');
       }
     }

     function logout()
     {
       $this->session->unset_userdata('logged_in');
       session_destroy();
       redirect('home', 'refresh');
     }

    }

?>

controllers/admin/login.php

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

    class Login extends CI_Controller {

    function __construct()
       {
       parent::__construct();
       }

     function index()
       {
       $this->load->helper(array('form'));
       $this->load->view('admin/login_view');
       }

    }

?>

routes.php

/* admin login*/

$route['admin/login_view'] = 'admin/login';
$route['admin/admin'] = 'admin/home';

/* admin cms */

$route['admin/options_view'] = 'admin/site';

database: indonusaci
table: users
id, username, password

This is what happen: after I login with the correct username and password,

http://localhost/IndonusaCI/index.php/admin/login

Then I start to move to another front page with this url:

http://localhost/IndonusaCI/index.php?verifylogin

I wonder why what appears is different from the tutorial, in the tutorial is directed to home after login, in this case, I would like to be directed to admin page after login which views/admin/admin.php

I tried the tutorial, works fine for me. Regarding your code:

<?php echo form_open('verifylogin'); ?>

Should be:

<?php echo form_open('admin/verifylogin'); ?>

Then into controllers/admin/verifylogin.php you have to change the redirect from home to /admin/home, so at line 27:

redirect('/admin/home', 'refresh');

the same applies to the other controllers redirects as example in /admin/home.php.

After the login I get this error:

Unable to load the requested file: admin/admin.php

Which is the view file: standing at the example it should be home_view.php, so this error is probably limited to my test and fixing this it works all fine.

Just remove the session_start() at the beginning of controllers/admin/home.php because you don't need it, since here we are using the CI session library. And you can remove all the PHP closing tags at the end of the controllers, if you want to use it, then be sure to remove all the spaces after that tag, otherwise you can get errors, ref.: http://ellislab.com/codeigniter%20/user-guide/general/styleguide.html#php_closing_tag

Going back to you, can you show your .htaccess contents?

That is the .htaccess of the application directory, which is not responsible for the rewrite of the url. In the root of the server you should have an .htaccess file, the basic contents of this file should be at least these:

<Files .htaccess>
order allow,deny
deny from all
</Files>

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)$ index.php/$1 [L]
</IfModule>

This will allow your application to use rewritten links as in your form_open('/admin/verifylogin') otherwise you have to write:

form_open('/index.php/admin/verifylogin')

Also, in the config file /application/config/config.php change this:

$config['index_page'] = 'index.php';

To:

$config['index_page'] = '';

Because, as you can read in the file comments:

If you are using mod_rewrite to remove the page set this variable so that it is blank.

I think this should help to solve your problem. Let us know.

Can you be more precise? The edit regards the .htaccess in the root of the server or in that in the application directory? If the answer is the former then post the contents of the .htaccess here and also the contents of the config file.

which .htaccess file do I have to change? if application/.htaccess then I already post the content in my previous post. I have not change the contents of the .htaccess in the root server.

You have to paste my previous instructions into the root .htaccess file, as example:

/
/.htaccess                 <-- edit this file
/index.php
/application/
/system/

Also, you have to remove the index.php from $config['index_page'] as already suggested, and change $config['enable_query_strings'] = TRUE; to FALSE, once you do this the ? will disappear and the link should work fine.

Agree, it doesn't seems correct. But it can be fixed, I think it depends on your setup:

  • IndonusaCI is the DocumentRoot? It's a section of a bigger website? To be sure about the DocumentRoot just place a PHP file in the root of the server with these instructions:

    <?php echo $_SERVER['DOCUMENT_ROOT']; ?>

  • have you set a ServerName in the VirtualHost of the Apache configuration file? Have you edited the hosts file to include the ServerName?

  • what is the value of $config['base_url'] in your config.php file?

Since I do not know your exact setup, I cannot suggest more to fix the issue. The only suggestion I can think is to avoid, for the moment, the rewritten links and to change the redirects by adding the /index.php/ segment:

redirect('/index.php/admin/home')

Or if this is a subfolder to:

redirect('/IndonusaCI/index.php/admin/home')

If this does not help, explain the structure of your application and show your Apache and CodeIgniter config files.

First, if I write :

1)

<?php echo $_SERVER['DOCUMENT_ROOT']; ?>

What should I name the file? and I just place it in the IndonusaCI

2) Have you set a ServerName in the VirtualHost of the Apache configuration file? Have you edited the hosts file to include the ServerName?

How to set a servername in the VirtualHost? How to edit the hosts file to include the ServerName?

3) $config['base_url'] = '';

(That's the value of)

The name of the file is not influent, it can be info.php if you prefer. You can also use phpinfo() instead of the previous:

<?php phpinfo(); ?>

you will get some information about your configuration, including the Apache Environment block, which returns also the value of the DocumentRoot.

To set the VirtualHost and the ServerName you have to edit the config file of Apache, in the below links you can find the instructions to do that:

If you have doubts attach those files to the thread, I'll help to edit them.

Here is part of the phpinfo:

PHP Version 5.4.19

System  Windows NT ACERASPIRE4750 6.1 build 7601 (Windows 7 Ultimate Edition Service Pack 1) i586
Build Date  Aug 21 2013 01:07:08
Compiler    MSVC9 (Visual C++ 2008)
Architecture    x86
Configure Command   cscript /nologo configure.js "--enable-snapshot-build" "--disable-isapi" "--enable-debug-pack" "--without-mssql" "--without-pdo-mssql" "--without-pi3web" "--with-pdo-oci=C:\php-sdk\oracle\instantclient10\sdk,shared" "--with-oci8=C:\php-sdk\oracle\instantclient10\sdk,shared" "--with-oci8-11g=C:\php-sdk\oracle\instantclient11\sdk,shared" "--enable-object-out-dir=../obj/" "--enable-com-dotnet=shared" "--with-mcrypt=static" "--disable-static-analyze" "--with-pgo"
Server API  Apache 2.0 Handler
Virtual Directory Support   enabled
Configuration File (php.ini) Path   C:\Windows
Loaded Configuration File   C:\xampp\php\php.ini
Scan this dir for additional .ini files     (none)
Additional .ini files parsed    (none)
PHP API     20100412
PHP Extension   20100525
Zend Extension  220100525
Zend Extension Build    API220100525,TS,VC9
PHP Extension Build     API20100525,TS,VC9
Debug Build     no
Thread Safety   enabled
Zend Signal Handling    disabled
Zend Memory Manager     enabled
Zend Multibyte Support  provided by mbstring
IPv6 Support    enabled
DTrace Support  disabled
Registered PHP Streams  php, file, glob, data, http, ftp, zip, compress.zlib, compress.bzip2, https, ftps, phar
Registered Stream Socket Transports tcp, udp, ssl, sslv3, sslv2, tls
Registered Stream Filters   convert.iconv.*, mcrypt.*, mdecrypt.*, string.rot13, string.toupper, string.tolower, string.strip_tags, convert.*, consumed, dechunk, zlib.*, bzip2.*

I also have tried to follow the link instruction that you attached exactly as it is. Yet, now I unable to restart apache:

Error: Apache shutdown unexpectedly.

11:28:43 AM [Apache] improper privileges, a crash, or a shutdown by another method.
11:28:43 AM [Apache] Press the Logs button to view error logs and check
11:28:43 AM [Apache] the Windows Event Viewer for more clues
11:28:43 AM [Apache] If you need more help, copy and post this
11:28:43 AM [Apache] entire log window on the forums

Here is the file that I have edited:

apache files

Hi, can you repost the link, it seems daniweb doesn't like it. And what about the DocumentRoot?

The link : www.innovation.web.id/apache

You have to change the values of that configuration to match the directories in which you have your website and in which you want to save the log files. Currently you just pasted the example of the link I gave you in my previous post, and for this reason it does not work.

So, or you edit it or you reset the configuration to the previous state.

But the most important information is to understand if CodeIgniter is in the root or inside a subdirectory. Because in the second case you have to modify or move the rewrite rule in the .htaccess file.

If you want you can create a new directory under C:, for example c:\www\mywebsite and use this for the virtual host configuration:

<VirtualHost *:80>
    ServerAdmin admin@localhost
    DocumentRoot c:/www/mywebsite
    ServerName mywebsite.tld
    <Directory />
        Options Indexes FollowSymLinks MultiViews
        AllowOverride All
        Order allow,deny
        Allow from all
    </Directory>

    ErrorLog ${APACHE_LOG_DIR}/mywebsite_error.log

    # Possible values include: debug, info, notice, warn, error, crit,
    # alert, emerg.
    LogLevel debug

    CustomLog ${APACHE_LOG_DIR}/mywebsite_access.log combined


    <FilesMatch "^.ht">
        order allow,deny
        deny from all
    </FilesMatch>
</VirtualHost>

Once you've done this, edit the hosts file by adding this line to the end of the file:

127.0.0.1 mywebsite.tld

And reload the server. At the end move your website to the directory you've created c:\www\mywebsite and in the config.php of CI set:

$config['base_url']     = "http://mywebsite.tld/";

At this point, from the browser you can access the website and the redirect should automatically point to the correct path.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.