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.
Related
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..
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 have a php file with a form to login.
I have other php file index.php, and i want that when i do login i go to this page: index.php.
So i have this code:
<?php
if(($login) and ($pass))
{
?>
<!DOCTYPE html PUBLIC "-//W2C//DD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml2-transitional.dsd">
<html xmlns="http://www.w3.org/1312/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
<h1>Header</h1>
<p> </p>
<p> </p>
<h1>Heeloo</h1>
<p> </p>
<p> </p>
<p> </p>
<h1>Footer</h1>
<p> </p>
</body>
</html>
<?php
}
else
{
echo "you didnt login";
}
?>
I have other php file to validate the login, i have this code:
<?php
if(($_POST['user'] == "john") && ($_POST['password'] == "123"))
{
setcookie("login",$_POST['user']);
setcookie("pass",$_POST['password']);
header("Location: index.php");
exit;
}
else
echo "you dont have permission";
?>
I got this error:
Notice: Undefined variable: login in C:\xampp\htdocs\sites\cookie\index.php on line 2
I think its because im using $login and $pass variables in index.php file and because these variables are from the other file is not recognizing.
Anyone know how to solve this?
Thanks
You set both $login and $pass as cookies. You have to read them in the index.php script, since they're not read back to your code automatically.
But instead of that, it's much better to use sessions. First, check if the login and password are ok. The result of this will be $_SESSION['auth'] being set to true or false. Of course, 'auth' is a suggestion, change it to the identifier you prefer:
// Initialize session control.
session_start();
// Check username and password. The function CheckCredentials() represents
// your logic on checking if they are ok.
if(CheckCredentials($login, $pass))
$_SESSION['auth'] = true;
else
$_SESSION['auth'] = false;
Then in your index.php script use session_start() again (that will enable the session data to be "seen" by current script) and modify your initial if:
session_start();
if($_SESSION['auth'])
{
This is more complicated in real code, but this is the general idea.
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";
}
This was my last attempt that I tried as a last effort:
index.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 content="text/html; charset=utf-8" http-equiv="Content-Type" />
<title>Customer Login</title>
<link href="stylesheet.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div class="wrapper">
<div class="login">
<form name="loginForm" action="loginCheck.php" method="post">
<?php require("protect/serverInfo.php"); ?>
Email: <input type="text" name="Email" maxlength="35" /><br />
Password: <input type="text" name="Password" maxlength="4" /><br />
<input type="submit" name ="submit"/>
</form>
</div>
</div>
</body>
</html>
loginCheck.php
<?php
session_start();
$_SESSION['email'] = $_POST['Email'];
$_SESSION['password'] = $_POST['Password'];
require("protect/serverInfo.php");
$myusername=$_POST[Email];
$mypassword=$_POST[Password];
$result = mysql_query("SELECT * FROM Customers WHERE Email='$myusername' AND Password=$mypassword");
$count=mysql_num_rows($result);
if($count==1){
header('Location: customer.php');
exit();
}
else{
header('Location: index.php');
exit();
}
?>
customer.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 content="text/html; charset=utf-8" http-equiv="Content-Type" />
<title>Untitled 1</title>
<link href="stylesheet.css" rel="stylesheet" type="text/css" />
<?php
session_start();
$myusername = $_SESSION['email'];
$mypassword = $_SESSION['password'];
?>
</head>
<body>
<?php
echo"success";
?>
</body>
</html>
I just need a very simple way to have a form post, the post info to be checked if correct then redirect if correct and pass the post data with it. I have been trying to use sessions and redirects but it doesn't to work quite right. What is the easiest way to accomplish this. At the moment I have been using PHP to check the login info from a MySQL database.
You need to use "session_start()" before you do anything else on the page.
Other few things, I avoid storing passwords on a page.. it just seems like a security issue.
Your login form should generate $_SESSION data based on the mysql information returned from the queury, not the form information that the user submited. You need to check against your customers database, to make sure they are an actual customer.
Also, avoid using the "header()" function, especially when working with sessions. I typically have a "redirect" function in php that does something like this...
function redirect($url) {
echo "<script type='text'/javascript'>window.location='" . $url . "';</script>";
}