I am trying to redirect to a different page when a value is entered into 'username' on my login form. But a warning appear saying "cannot modify header information - headers already sent by (output started at /Users/Zach/Sites/Project2/proj2Functions.php:10) in /Users/Zach/Sites/Project2/redirect.php on line 3"
I put the code all the way at the top so I thought the redirect would work. What am I doing wrong?
Here is the code for the login:
if (isset($_POST["submit"])) {
$username = trim($_POST["username"]);
$password = trim ($_POST["password"]);
if (has_presence($username)) {
redirect_to("Homepage2.php");
}
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html lang="en">
<head>
<title>Start Collay Login(beginLogin)</title>
</head>
<body>
<?php echo "This is the first login page"; ?>
<form action="beginLogin.php" method="post">
Username: <input type="text" name="username" value=""><br>
Password: <input type="text" name="password" value=""><br>
<input type="submit" name="submit" value="submit">
</form>
</body>
</html>
And here is the code for the redirect file:
<?php
function redirect_to($new_location) {
header("Location: " . $new_location);
exit;
}
?>
The redirect file code should be the first thing to appear on the page so even if there is a blank space or a line break before the <?php then it will not work or you may turn output_buffering on in your php.ini file by assigning it a value (4096) is generally a good value..
Hope this helps,
Take care and Happy coding..
Related
I started studying PHP few weeks ago and I'm a little bit confused with conditional embed HTML between PHP code blocks and setting cookies. What I want to do is a simple code that checks your name, password and e-mail, sets cookie (if they are valid); when you have already logged in, you should see "log out" button. So, my code:
<?php
if (($_POST['name'] == 'admin') and ($_POST['pass'] == 'admin') and ($_POST['mail'] == 'admin#gmail.com')) {
setcookie("Test","Value");
echo "Success!!! <br/>";
}
if ($_POST['logout']) {
setcookie("Test", "", time() - 3600);
echo "Goodbye!";
}
?>
<?php if(isset($_COOKIE['Test'])) :
?>
<input type="submit" value="logout"/><br/>
<?php endif ?>
<?php if(!isset($_COOKIE['Test'])) :
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<form action="" method="POST">
<input type="text" name="name"/><br/>
<input type="text" name="pass"/><br/>
<input type="text" name="mail"/><br/>
<input type="submit" value="go"/><br/>
<?php endif ?>
However, I can't figure out how to make it work properly: when I enter correct username, password and mail, I don't see "logout" button, there's still a form and i need to enter username again to finally see "logout". Second problem, when I press "logout", nothing happens. I guess I can't set the cookie because headers were already sent, but I can't figure out how to rewrite it.
Has per #RowlandShaw stated in the comment, setcookie() will affect only the future requests, not the current one.
Here is your corrected code:
<?php
if($_POST)
{
if(isset($_POST['name']) && isset($_POST['pass']) && isset($_POST['mail']))
{
if (($_POST['name'] == 'admin') and ($_POST['pass'] == 'admin') and ($_POST['mail'] == 'admin#gmail.com')) {
setcookie("Test","Value");
echo "Success!!! <br/>";
echo '<form action="" method="POST">'.
'<input type="submit" value="logout" name="logout"/><br/>'.
'</form>';
}
}
if (isset($_POST['logout'])) {
setcookie("Test", "", time() - 3600);
echo "Goodbye!";
echo '<br/>';
echo 'Login back';
}
}
else
{
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<form action="" method="POST">
<input type="text" name="name"/><br/>
<input type="text" name="pass"/><br/>
<input type="text" name="mail"/><br/>
<input type="submit" value="go"/><br/>
<?php } ?>
You will have to create a link to the same page so the cookie modification are taken into account. Also, you didn't set up a name on your logout button nor did you specify that the logout action is a POST request by adding the <form> tag (it's GET by default) that made $_POST['logout'] never set.
The first page (inputform1test.php)
<?php require_once('Connections/Project.php'); ?>
<?php
if (!isset($_SESSION)) {
session_start();
}
?>
<!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>Input (Test)</title>
</head>
<body>
<form id="form1" name="form1" method="post" action="inputdisplaytest.php">
<p>Name
<input type="text" name="name" id="textfield" />
</p>
<p>Text
<input type="text" name="text" id="textfield2" />
</p>
<p>
<input type="submit" name="button" id="button" value="Submit" />
</p>
</form>
</body>
</html>
Second page(inputdisplaytest.php)
To test if it's working in 2nd page(inputdisplaytest.php)
<?php include('Connections/Project.php'); ?>
<?php
if (!isset($_SESSION)) {
session_start();
}
$_SESSION['name']= $_POST['name'];
$_SESSION['text']= $_POST['text'];
?>
<!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>Display Input (Test)</title>
</head>
<body>
<table width="200" border="0">
<tr>
<td><?php echo $_SESSION['name']?></td>
<td><?php echo $_SESSION['text']?></td>
</tr>
</table>
inputdisplaytest_2.php
</body>
</html>
Third page(inputdisplaytest2.php)
This is the part where I got the error
<?php include('Connections/Project.php'); ?>
<?php
if (!isset($_SESSION)) {
session_start();
}
?>
<!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>Display Input (Test)</title>
</head>
<body>
<table width="200" border="0">
<tr>
<td><?php echo $_SESSION['name']?></td>
<td><?php echo $_SESSION['text']?></td>
</tr>
</table>
<p>inputdisplaytest.php</p>
</body>
</html>
I clicked to see if it's still working on 2nd page. (Which is not working)
I got the undefinex index problem when I go to the hyperlink and "Document Expired" when I clicked back button via browser.
How do I get the session variables back/not expire?
Any help would be appreciated.
You don't need the
if (!isset($_SESSION)) {
session_start();
}
just use session_start() at the beggining of your script. Even before those includes.
You can't print anything before the session_start. Check your logs for errors.
I believe the reason you're finding this error is because you are POSTing the form data. When you POST the form data, it is sent when you hit Submit. Going back to the form will give you the message to reload the form data. If you change it to GET, your form data should stick.
Remove if statements that you're using to check if session is set, because in your case the session_start() is never being executed, since the $_SESSION array is always set by PHP unless you perform unset($_SESSION) which is deprecated, this will unset the whole $_SESSION with unset($_SESSION) as this will disable the registering of session variables through the $_SESSION superglobal array. So:
if(!isset($_SESSION)){
session_start();
}
becomes:
session_start();
this resolves the problem of undefined index error.
To resolve the browser back button error when navigating back to the page processing your form, you have to put:
session_cache_limiter('private_no_expire');
before session_start() on second.php file, this line of code avoid "Page Has Expired" warnings, you can find more explanation here avoid "Page Has Expired" warnings.
Finally, after session_start() on second.php file, add the following code:
if(isset($_POST['button'])){
$_SESSION['name']= $_POST['name'];
$_SESSION['text']= $_POST['text'];
}
to check if the form was submitted or not, if yes, you can process the data and display the page, else you just display the page using the perviously stored data on your session.
I have had issues with this myself, where the session variables are not passed on, and recently came across the answer. I am sorry that I cannot credit the person who answered this in a previous post because I cannot find the post again. Simply put, sometimes, especially on shared hosting, the sessions are not stored in the right place. You can fix this by forcing the sessions to be saved in a particular spot. My solution was:
ini_set('session.save_path',realpath(dirname($_SERVER['DOCUMENT_ROOT']) . '/session'));
My session file is in the domain's root folder.
I then start the session:
session_start();
And then I make sure that the person is signed in:
if(isset($_SESSION["your_variable"])) {
$your_variable = $_SESSION["your_variable"];
//add any other session variables in the same manner
//be sure to rename "your_variable" with the name of your variable
}else{
header('Location: signin.php');
exit;
}
The header redirect at the bottom is where the person is going if they are not signed in or the session variable is not found, so that the session variables are passed to this page. Note the exit, it keeps your code safer. So altogether my first lines of code are:
ini_set('session.save_path',realpath(dirname($_SERVER['DOCUMENT_ROOT']) . `'/session'));`
session_start();
if(isset($_SESSION["your_variable"])) {
$your_variable = $_SESSION["your_variable"];
}else{
header('Location: signin.php');// or wherever your sign in happens to be
exit;
}
I hope this helps.
I'm trying to create a maths quiz page. The first page needs to generate a question shown as a header, that asks the user what two random numbers are multiplied together.
Then depending on the users input, it takes them to a different page.
If they are correct it displays the paragraph "You are correct!".
If they are wrong it displays the paragraph "You are incorrect" and invites the user to try again.
and if they enter a string it displays the paragraph "I don't understand your response" and invites the user to try again.
So far I have the below code, the layout is correct but the header isn't working, and I've attempted to display a new page, but again, they don't load. Anyone know where I'm going wrong?
<?php
$first = Rand(1,10);
$second = Rand(1,10);
echo <h1>"What is " . $first . "times " . $second . "?"</h1>;
if(is_int($_POST['answer']) == 1){
if($_POST['first']*$_POST['second'] == $_POST['answer']){
header("Location: correct.html");
exit();
}
else{
header("Location: incorrect.html");
exit();
}
}
else if(is_string($_POST['answer']) == 1) {
header("Location: response.html");
exit();
}
?>
<!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>Maths Quiz</title>
</head>
<body>
<form method="POST" action="<?php echo $_SERVER['file:///X|/Software Development/PHP_SELF']; ?>">
<p>Answer<br/>
<input type="text" id="answer" name="answer" /></p>
<p></p>
<button type="submit" name="submit" value="send">Submit</button>
<input type="hidden" name="answer" value="<?php echo $answer; ?>"/></p>
</form>
</body>
</html>
You must have the header() code before any output, especially that echo statement.
Apart from sending the headers before you output something, i think your form action is wrong, it should be
action="<?php echo $_SERVER['PHP_SELF']; ?>"
You are sending the POST via FILE protocol, it won't be processed by Web Server/PHP.
And also, you are not POSTing "first" and "second" fields.
I'm working with a .html and a .php. In the default.html the user must enter some info and when the button is clicked the html does a post to the default2.php.
In default2.php the data is checked and if it's correct it redirects the user to another page. The problem I'm having is when the data entered is wrong.
I'm having two issues here:
When the data is wrong I'm redirecting the user to the default.html, because if I don't do that, it will stay in default2.php and default2.php has nothing important for the user to see. I don't know if this is the best way to do this.
When the data entered is wrong, I want an echo message to the user in default.html. But I don't know how to trigger this from default2.php.
How can I solve these two issues?
Thanks...
default.html:
<!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>
<script type="text/javascript">
</script>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>PHP4</title>
<style type="text/css">
body {
background-color: #CCC;
}
</style>
</head>
<body>
<p> </p>
<form id="form1" name="form1" method="post" action="default2.php">
<p>
<label for="textfield1">User Name</label>
<input type="text" name="username" id="username" />
</p>
<p>
<label for="textfield2">Password</label>
<input type="password" name="password" id="password" />
</p>
<p>
<input type="submit" name="button1" id="button1" value="Submit" />
<br />
<br />
<label id="label1">
</label></p>
<p> </p>
</form>
<p> </p>
</body>
</html>
default2.php:
<?php
require 'connection.php';
if (isset($_POST['button1'])) {
$username_v = $_POST['username'];
$password_v = $_POST['password'];
// Then you can prepare a statement and execute it.
$stmt = $dbh->prepare("CALL login(?, ?)");
$stmt->bindParam(1, $username_v, PDO::PARAM_STR);
$stmt->bindParam(2, $password_v, PDO::PARAM_STR);
// call the stored procedure
$stmt->execute();
if ($row = $stmt->fetch(PDO::FETCH_NUM, PDO::FETCH_ORI_NEXT))
{
header("Location: main.php");
}
else
{
header("Location: default.html");
}
}
?>
Just add some parameter to
header("Location: default.html?test=failed");
And in html use Javascript to display something sensible when variable test is set to failed. You can find a tutorial how to get value of url parameter with javascript here.
Hope that helps.
Other than that you can use PHP in your default.html and perhaps even AJAX request to do validation without leaving the page and highlighting validation errors.
Personally, I don't like to expose states like "error" and "invalid" to the user using a query string. In this situation, I would merge the two files in one single PHP file, with the PHP code at the top and the HTML code at the bottom.
The if statement in the PHP code would be:
if ($row = $stmt->fetch(PDO::FETCH_NUM, PDO::FETCH_ORI_NEXT))
{
header("Location: main.php");
exit;
}
else
{
$error = true;
}
And down in the HTML where you want to display the message:
<?php
if( isset( $error ) && $error )
echo 'You have entered the wrong data!';
?>
Ofcourse, in the form element, you would have to remove action="default2.php".
If you prefer separating the logic and the markup, you could change default.html to for example template.php and include it at the end of your controller php file.
I just don't like the idea of an extra page without any content that only acts as a redirector.
If you made default.html a PHP file, you could pass a variable via the URL, this would then allow you check if this variable has been passed using $_GET[]and show the user a message.
So for example, if you forwarded the user to
default.php?error=1
On the default page, you could have a segment of code such as
if (isset($_GET['error'])) {
echo "Show user a message here";
}
I have written a very very very simple!! script in php. header redirection not working.
1- encoding : UTF-8 without BOM
2- with adding ob_start() the problem is countiueing.
What is wrong in my code;
login.php:
<?php session_start();
require_once("funcs.php");
db_connection();
$username = $_POST['username'];
$password = $_POST['pwd'];
$submit = $_POST['login'];
if($submit){
if (!filled_out($_POST)) {
echo "please fill all fields";
}
else{
$query = "SELECT * FROM *** WHERE username ='{$username}' AND password ='{$password}'";
$result = mysql_query($query);
if(mysql_num_rows($result) == 1){
$found_user = mysql_fetch_array($result);
$_SESSION['id'] = $found_user['id'];
$_SESSION['username'] = $found_user['username'];
$_SESSION['password'] = $found_user['password'];
setcookie(session_name(), '', time()+86400, '/');
header("Location: tst.php");
}
else{
echo "incorrect username or password";
}
}
}
?>
<!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>
</head>
<body>
<form id="form1" name="form1" method="post" action="">
<p>
<label for="username">
Username:
</label>
<input type="text" name="username" id="username" />
</p>
<p>
<label for="textfield">
Password
</label>
<input type="password" name="pwd" id="pwd" />
</p>
<p>
<input name="login" type="submit" id="login" value="Log in" />
</p>
</form>
</body>
</html>
<?php
db_disconnect();
?>
and tst.php:
<?php session_start();
require_once("funcs.php");
if (!isset($_SESSION['id'])){
header("Location : login.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>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
<table id="structure">
<tr>
<td id="navigation"> </td>
<td id="page"><?php echo "welcome"."". $_SESSION['username']; ?></td>
</tr>
</table>
</body>
</html>
wthit oppening tst.php directly, header() doesnot redirect to login.php
Try adding die():
header("Location: tst.php");
die();
You should always add a die() because a location header is just a request to the browser to change the page. If you don't die(), the rest of the page will still reach the browser, including possibly sensitive data the user is not meant to see.
Try removing the space after "Location":
header("Location: login.php");
Please heed my comment about formatting your code correctly as it's extremely difficult to spot anything else that may be amiss.
Check for white space before your opening <?php tags. It's hard to tell from your formatting here whether there is any, but the whitespace will be sent before your code executes, preventing headers. Also check for white space after any closing tags in included files. (better practice is to omit closing tags altogether)
old answer
You're using setcookie() which will send headers, then trying to redirect. You cannot redirect once headers have been sent. (sorry, this was incorrect)
I guess the redirect works, but you overwrite the Session-Cookie with an empty value. So the tst.php creates a new empty Session and redirects back to login.php.
Try:
// DELETE this line: setcookie(session_name(), '', time()+86400, '/');
header("Location: tst.php?".SID);
Importent: header+session always need SID for not loosing the session!
Corrected: Thanks to #Pekka.
header is not just a php function. It really modifies a part of http header, so it is impossible to have a part of header, then html data, then another header. To make it work, you should put your header at the beginning of the file, before any html output is done.
The redirection can take a relative or absolute URL. The problem is with the space BEFORE the colon. Try it like this:
header("Location: whatever.php");
As well as the other answers, the Location: header should contain an absolute URL, example header("Location: http://example.com/");
you need to put an exit() or die() after the header function - otherwise the rest of the script will continue to execute.