Reputation: 27
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.
Upvotes: 1
Views: 444
Reputation: 592
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
Upvotes: 0
Reputation: 23948
Its because, you have echo
ed 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.
Upvotes: 1