I am running into this problem with codeigniter, where it loads the index() page perfectly, but when it comes to any other function, it just throw me an 404 error. Here is a skeleton code :
<?php if( ! defined('BASEPATH')) exit('No direct script access alloowed');
Class User extends CI_Controller{
var $err;
public function construct(){
parent::_construct();
session_start();
$this->load->database();
$this->load->model('User_Model');
}
public function index(){
if(isset($this->session->userdata['userID'])){
$this->welcome();
}else{
$this->load->view('banner','Login');
if(isset($this->err)){
$data["error"] = $this->err;
$this->load->view('login',$data);
}else{
$this->load->view('login');
}
$this->load->view('footer');
}
}
public function test(){
echo "Hello World";
}
public function welcome(){
$this->load->view('test');
}
public function register(){
$this->load->view('banner','Login');
if(isset($this->err)){
$data["error"] = $this->err;
$this->load->view('register',$data);
}else{
$this->load->view('register');
}
$this->load->view('footer');
}
public function registration(){
//registration ops
}
public function login(){
//login ops
}
}
?>
So, when I am trying to navigate to www.example.com/index.php/user , it runs perfect, but when I try to let it run register, or do a login operation, it just throws an 404 error. Is there any solution to this?
Here is a html code generated using with index():
<!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>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<link href="http://localhost/baseball/css/login.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div>
<p><img src="http://thumbs.dreamstime.com/z/cartoon-baseball-player-vector-illustration-30999087.jpg" height="250" alt=""/>Baseball Card Shop</p>
<hr />
<p class="loginInfo">
Shopping Cart
</p>
<hr/>
</div>
<div class="central_login">
<div class="main">
<form action="http://localhost/baseball/index.php/user/login" method="post" accept-charset="utf-8"> <div class="left">
<p>
<label for="login"> Login: </label>
<input type="text" name="login" id="login" pattern="^[a-zA-Z0-9]+$" required/>
</p>
<p>
<label for="pwd">Password: </label>
<input type="password" name="pwd" id="pwd" required/>
</p>
<p><label id='pwdErr'></label>
<input type="submit" value="Log in" id="create-account" class="button"/>
</p>
</div>
</form> <div class="right">
<form action="http://localhost/baseball/index.php/user/register" method="post" accept-charset="utf-8"> <p>Not our customer, worry not ! Register here, it is free!</p>
<input type="submit" value="Register HERE!" id="register" class="button"/>
</form> </div>
</div>
</div>
<footer>
<p>CSC309 Assignment</p>
<p>Baseball Web Application</p>
</footer>
</body>
</html>
Thanks a bunch!
You need to change your .htaccess. The following .htaccess will help you:
RewriteEngine on
RewriteCond $1 !^(index\.php|resources|robots\.txt)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L,QSA]
And need to change the following configure in config.php:
$config['index_page'] = '';
$config['uri_protocol'] = 'AUTO';
There are a couple of things that are drawing attention in your code:
First, the use of var key word. It was used to declare class members in php4.
It is deprecated in php5 and greater version.
It will work. But raise a warning and is a bad practice.
Second. From the code you have posted, I believe, you have not auto loaded Session library.
Change the session_start() code in your constructor to :
$this->library->load('session');
Third thing I noted is this line of code:
$this->load->view('banner','Login');
The view functions of the loader class takes parameters in the below format.
$this->load->view('file_name', $data, true/false);
The syntax that you are might not be correct.
If you are planning to load banner and login file, you should do this:
$this->load->view('banner');
$this->load->view('Login');
On a side note, using native php sessions and CI sessions might be confusing and also may raise conflict in some situations.
Related
This question already has answers here:
How to rewrite the images path according to the written rules of the url?
(1 answer)
JS and CSS Rendering Issues After .htaccess File URL Rewrite Rule
(1 answer)
Closed 2 months ago.
I am a newbie when it comes to MVC in PHP and I have encountered a problem with using my controllers. When I try to load a page (e.g. SignUp). When I specify my URL as localhost/MyProject/public/signup, everything works just fine. But when I try to specify the method I want to use as localhost/MyProject/public/signup/index (while the default method in App.php is index too), it breaks. Both css and js doesn't load into the page and all I see is just html document. Any ideas why that happens? The only solution I could come up with is to use absolute paths like> https://localhost/MyProject/public/css/styles.css but it just seems like there should be an easier or more elegant solution. I tried both my original css/styles.css and /css/styles.css but neither of them fixed my problem. So my final question is, whether there is an elegant alternative or using the absolute path is my only solution.
My App.php class:
class App
{
protected $controller = 'signin';
protected $method = 'index';
protected $params = [];
public function __construct() {
$url = $this->parseUrl();
if (isset($url[0]) && file_exists('../app/controllers/' . $url[0] . '.php')) {
$this->controller = $url[0];
unset($url[0]);
}
require_once '../app/controllers/' . $this->controller . '.php';
$this->controller = new $this->controller;
if (isset($url[1]) && method_exists($this->controller, $url[1])) {
$this->method = $url[1];
unset($url[1]);
}
$this->params = $url ? array_values($url) : [];
call_user_func_array([$this->controller, $this->method], $this->params);
}
public function parseUrl() {
if (isset($_GET['url'])) {
return explode('/', filter_var(rtrim($_GET['url'], '/'), FILTER_SANITIZE_URL));
} else {
return [];
}
}
}
My SignUp.php controller:
class SignUp extends Controller
{
public function index()
{
$this->view('signup');
}
}
My signup.php view:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Habit Journal</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="css/signInUp.css">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Mukta&display=swap" rel="stylesheet">
</head>
<body>
<div class="page-container">
<main class="login-container">
<div class="login-top">
<img src="img/logoZwa2.png" alt="Logo">
Habit Journal
</div>
<div class="login-text">
Sign up to use Habit Journal.
</div>
<form method="post">
<label for="email">E-mail</label>
<input id="email" name="email" type="email" required>
<label for="password">Password</label>
<input id="password" name="password" type="password" required>
<label for="password_check">Retype password</label>
<input id="password_check" name="password" type="password" required>
<input id="submit" type="submit" value="Sign Up" disabled>
</form>
</main>
<div class="login-redirect">
Login
</div>
<script>
document.getElementById("submit").disabled = true;
</script>
<script src="js/signInUpValidation.js"></script>
</div>
</body>
</html>
My file structure
.htacces file:
Options -MultiViews
RewriteEngine On
RewriteBase /MyProject/public/
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.+)$ index.php?url=$1 [QSA,L]
I tried to relocate both JS and CSS files to various locations without any change, look into the console and other developer tools in browser but I just found out, that both JS and CSS didn't even load, when I specified the method.
When I try to send my form with the base_url() method (so I click on the submit button), instead of the result of my request, I have a 403 error on the other page (forbidden acces), on the page generated by my controller.
I use a Wampp Server, the version 3.1.8 of CodeIgniter. I've also add url in the autoload file.
I have .htacess file with that :
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L]
View page :
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form method="post" action="<? echo base_url();?>form_validation">
<label> Name </label>
<input type="text" name="name" />
<input type="submit" name="submit" value="submit" />
</form>
</body>
</html>
Can you help me ? Thanks a lot
Hope this will help you :
NOTE : Assuming that default controller is welcome in route.php if not replace welcome with yours
In controller : you have method form_validation and you give in form action only validation :
public function form_validation()
{
echo 'OK';
}
Your form view is just like this :
REPLACE :
/* note missing php error in action*/
<form method="post" action="<? echo base_url();?>form_validation">
With :
/*add controller name also in action,
assuming your default controller is Welcome*/
<form method="post" action="<?php echo base_url('welcome/form_validation');?>">
View should be like this :
<form method="post" action="<?php echo base_url('welcome/form_validation');?>">
<label> Name </label>
<input type="text" name="name" />
<input type="submit" name="submit" value="submit" />
</form>
route.php should be like this :
$route['default_controller'] = 'welcome';
$route['404_override'] = '';
$route['translate_uri_dashes'] = FALSE;
NOTE ALSO : .htaccess should be in project folder , in your case CI folder
Code for myform.php
<html>
<head>
<title>My form</title>
</head>
<body>
<form action="success" method="post">
<h5>Username</h5>
<input type="text" name="username" value="" size="50" />
<!--
<h5>Password</h5>
<input type="password" name="password" value="" size="50" />
<h5>Confirm Password </h5>
<input type="password" name="passconf" value="" size="50" />-->
<h5>Email Address </h5>
<input type="email" name="email" value="" size="50" />
<div><input type="submit" value="submit" /></div>
</form>
</body>
</html>
controller script 1
<?php
class Form extends CI_Controller{
public function __construct(){
parent::__construct();
$this->load->library('session');
$this->load->helper('url');
}
public function index(){
$this->load->view('myform');
}
public function success(){
$_SESSION['username']=$_POST['username'];
$_SESSION['email']=$_POST['email'];
redirect('form/home');
}
public function home(){
$this->load->view('test_home');
}
}
?>
controller script 2
<?php
class Form extends CI_Controller{
public function __construct(){
parent::__construct();
$this->load->library('session');
$this->load->helper('url');
}
public function index(){
$this->load->view('myform');
}
public function success(){
$_SESSION['username']=$_POST['username'];
$_SESSION['email']=$_POST['email'];
echo $_SESSION['username'];
echo $_SESSION['email'];
redirect('form/home');
}
public function home(){
$this->load->view('test_home');
}
}
?>
The question is when I use controller 1, the script work as intended and redirects me to form/home. However, when I use controller 2 I get this error
A PHP Error was encountered
Severity: Warning
Message: Cannot modify header information - headers already sent by (output started at /usr/local/apache2/htdocs/parth/application/controllers/Form.php:15)
Filename: helpers/url_helper.php
Line Number: 564
Backtrace:
File: /usr/local/apache2/htdocs/parth/application/controllers/Form.php
Line: 18
Function: redirect
File: /usr/local/apache2/htdocs/parth/index.php
Line: 292
Function: require_once
why is the code behaving this way? Thank you for your time.
Its because, you have echoed two strings in second case.
Comment out this:
//echo $_SESSION['username'];
//echo $_SESSION['email'];
Redirection is not happening due to this.
In CodeIgniter, redirection uses PHP's header("Location...") construct.
This requires that your current script is not outputting anything on screen.
Not even a space (that is why CodeIgniter recommends you should not end up your PHP files with ?> as spaces can remain there.
redirect() uses PHPs
header() function. If you have output before any header you get this error.
This is your Output:
echo $_SESSION['username'];
echo $_SESSION['email'];
redirect('form/home');
Commented out, or delete it, cause while redirecting you dont need it.
Kind regards
I am trying to create a login form using CodeIgniter in PHP. I have implemented the functionality, working okay, however I cannot manage to style my for with a custom stylesheet.
Here is the code I have for the login view:
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset="UTF-8" />
<title>
DTI Manager
</title>
<link rel="stylesheet" type="text/css" href="/DTIManager/assets/css/style.css" />
</head>
<body>
<div id="wrapper">
<?php echo validation_errors();?>
<?php $attributes = array('class' => 'LoginController', 'id' => 'login-form');
echo form_open('LoginController/checkLogin', $attributes);?>
<form name="login-form" class="login-form" action="" method="post">
<div class="header">
<h1>Autentificare</h1>
<span>Pentru a accesa informatii despre comenzi transporturi trebuie sa fiti autentificat.</span>
</div>
<div class="content">
<input name="username" type="text" class="input username" placeholder="Utilizator" />
<div class="user-icon"></div>
<input name="password" type="password" class="input password" placeholder="Parola" />
<div class="pass-icon"></div>
</div>
<div class="footer">
<input type="submit" name="submit" value="Login" class="button"/>
</div>
</form>
</div>
<div class="gradient"></div>
</body>
</html>
And this is my LoginController class:
class LoginController extends CI_Controller {
function __construct() {
parent::__construct();
}
public function index() {
$this->load->view('login');
}
public function checkLogin() {
$this->form_validation->set_rules('username', 'Utilizator', 'required');
$this->form_validation->set_rules('password', 'Parola', 'required|callback_verifyUser');
if ($this->form_validation->run() == false) {
$this->load->view('login');
} else {
redirect('HomeController/index');
}
}
public function verifyUser() {
$name = $this->input->post('username');
$pass = $this->input->post('password');
$this->load->model('LoginModel');
if ($this->LoginModel->login($name, $pass)) {
return true;
} else {
$this->form_validation->set_message('verifyUser', 'Incorrect Email or Password. Please try again.');
return false;
}
}
}
I tried adding the attribute to the form_open function the ID of my form but it wasn't successful, the buttons and fields are still not styled accordingly.
Any hints are highly appreciated.
Try echoing the base_url() in front of your linked css files.
<link rel="stylesheet" type="text/css" href="<?php echo base_url();?>DTIManager/assets/css/style.css" />
Of course, if you use an .htaccess you should ignore the folder that has the assets in your project with a proper rewrite rule.
RewriteCond $1 !^(index\.php|DTIManager|assets|robots\.txt|error\.html)
I have created a simple register/login system and it (I think) works well so far.
Now I want to implement some of it's functions to my site.
controllers/main.php:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Main extends CI_Controller
{
public function index()
{
$this->home();
}
public function home()
{
$this->load->view('home.php');
}
}
views/home.php:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Home</title>
</head>
<body>
<div id="container">
<?php if ($this->session->userdata('is_logged_in')): ?>
logged in as: <?php echo $this->session->userdata('username'); ?></br>
Logout
<?php else: ?>
not logged in</br></br>
<?php echo form_open('login'); ?>
<?php echo form_error('username'); ?>
<input type="text" name="username" placeholder="Login" />
</br>
<?php echo form_error('password'); ?>
<input type="password" name="password" placeholder="Password" />
</br></br>
<div><input type="submit" value="Sign in" /></div>
<?php echo form_error('login_validation'); ?>
</form>
<?php endif ?>
</div>
</body>
</html>
Is this the right way of doing things in CI?
For controller part instead of using the home(), you can directly load the view in index() because internally you are navigating from index to home() without any specific reason.
Also the loading view doesn't require ".php" extension in your file and you can do like this:
$this->load->view('home');
Where home.php is the file located inside application/views/
For showing the error messages, you can use another optimal way by defining the validation rules(in array fromat) inside config/form_validation.php and just require below code to show all messages instead one by one
<?php echo validation_errors()?>