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.
Related
I have two .php files. All html and php, no SQL and will not be needing/using it. One is the login page, the other is the destination. When I put in the log in details I have set, I can't get to the destination. As you can see, session_start(); is clearly at the top. I even put it right on the same line as the opening php tag and no difference was made. Here's the code for both pages:
Login:
<?php
session_start();
$username="testu";
$password="testp";
$_SESSION['logged_in']=false;
if (isset($_SESSION['logged_in']) && $_SESSION['logged_in'] == true) {
header("Location: dest.php");
exit;
}
if (isset($_POST['user']) && isset($_POST['pass'])) {
if ($_POST['user'] == $username && $_POST['pass'] == $password) {
$_SESSION['logged_in'] = true;
header("Location: dest.php");
exit;
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>A title</title>
</head>
<body>
<form action="dest.php" method="post" style="font- family:calibri;position:absolute;top:40%;left:35%;">
Username: <input type="text" name="user"/><br><br>
Password: <input type="password" name="pass" style="position:relative;left:5px;"/><br><br><br>
<input type="submit" value="Submit" style="position:relative;left:115px;"/>
</form>
</body>
</html>
Destination:
(php tag here)
session_start();
if (!isset($_SESSION['logged_in']) || $_SESSION['logged_in'] == false) {
header("Location: login.php");
exit;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>A title</title>
</head>
<body>
Log out
</body>
</html>
I noticed that when I commented out the php code on the destination file, I could access the dest.php. Issue is, I could access is with any login details, or none at all. It's either nothing works, or anything works. How can I get the details I have set to work? I feel the issue is in the login page script. Many thanks in advance to anyone who can help me resolve this.
Note: I had to repost this because my last question was marked as a duplicate of something completely irrelevant to my issue, thank you.
#Sean beat me to it, nice job :-)
If you remove the action="dest.php" it should work. Right now you are sending the form to a page that does not check the values of the username and password, thus the session variable is not set.
<form method="post">
Username: <input type="text" name="user"/>
....
</form>
action="dest.php"
You must make sure code below is in the file dest.php, and delete it from login.php.
<?php
session_start();
$username="testu";
$password="testp";
$_SESSION['logged_in']=false;
if (isset($_SESSION['logged_in']) && $_SESSION['logged_in'] == true) {
header("Location: dest.php");
exit;
}
if (isset($_POST['user']) && isset($_POST['pass'])) {
if ($_POST['user'] == $username && $_POST['pass'] == $password) {
$_SESSION['logged_in'] = true;
header("Location: dest.php");
exit;
}
}
?>
I tried some solution from internet, I put session_start(); at first line, also try by using #ob_start(); Any other solution???
My code is here:
<?php
session_start();
require_once('page.inc');
?>
<!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>site 1</title>
<meta name="keywords" content="universe, blog theme, black, website template, templatemo" />
<meta name="description" content="About Universe, Our Company, free website template" />
<link href="templatemo_style.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="js/jquery-1.6.3.min.js" ></script>
</head>
<body>
<?php
if(!isset($_SESSION['loggedinuser']))
{
if (isset($_POST['Signin']))
{
$username=$_REQUEST['username'];
if($username=='a')
$_SESSION['loggedinuser']=$username;
else
echo " the username or password you entered do not matchted ! ";
}
else
{
?>
<form method="post" action="index.php" >
<input type="text" name="username" id="username" >
<input name="Signin" type="submit" value="Signin" />
</form>
<?
}
}
else
//something else
?>
</body>
</html>
here the error is:
Warning: session_start(): Cannot send session cookie - headers already sent by (output started at /usr/local/apache2/htdocs/jasi/medu_quiz_22111_bl/index.php:1) in /usr/local/apache2/htdocs/jasi/medu_quiz_22111_bl/index.php on line 2
Warning: session_start(): Cannot send session cache limiter - headers already sent (output started at /usr/local/apache2/htdocs/jasi/medu_quiz_22111_bl/index.php:1) in /usr/local/apache2/htdocs/jasi/medu_quiz_22111_bl/index.php on line 2
Check whitespaces before <?php, ensure that the <?php is the first character, not tabbed or spaced.
I have tried your code and all works fine, I copied pasted it as is and the form is showing normal
even submitted the form twice once with the correct value and form disappeared and once with the wrong value and the message that it is a wrong value
if you have placed some white space before :
<?php
session_start();
....
?>
That might produce an error, nothing should come before the session_start() part, maybe you have note created the page: page.inc and that is doing the damage
This is the new code I tried, and these are step you can take:
I have checked it with opera, yes at first it was not showing, but with a heavy refresh it did show, try to do a no caching mechanism, by maybe sending it to page with a random id, this will clear the cache, the problem is not session in opera, the session is working, it is in caching,
Refresh your opera and you will, I took the address and copied it into another tab on opera, and the session showed, This is the complete copy on my version:
<?php
session_start();
require_once('page.inc');
?>
........
<?php
if(!isset($_SESSION['loggedinuser']))
{
if (isset($_POST['Signin']))
{
$username=$_REQUEST['username'];
if($username=='a')
$_SESSION['loggedinuser']=$username;
else
echo " the username or password you entered do not matchted ! ";
}
else
{
?>
<form method="post" action="index.php" >
......
</form>
<?
}
}
else if(isset($_SESSION['loggedinuser']))
{
$ses = $_SESSION['loggedinuser'];
echo "LINE 47 session is $ses ";
}
else
{
$ses2 = $_SESSION['loggedinuser'];
echo "LINE 51 session is $ses2 ";
}
?>
</body>
</html>
This produces:
Line 2 included a page LINE 47 session is a 56
page.inc
<?php
echo " Line 2 included a page ";
?>
So I'm trying to make a secure homepage that checks if you're logged in by getting the text that the user entered on the login page and checking they are correct (so you can't just do www.website.com/home.php to bypass login)
<body onload="OpenPhp()">
<form name="GetLogin" action="GetIfLoggedIn.php">
</body>
The script is :
<script>
function OpenPhp(){
document.GetLogin.submit();
}
</script>
the php script should include the username and password vars from the login script and re-check them
<?php include "Login.php";
if($Username === "*****" and $Password === "******"){
// Return To Page
}else{
//Go Back To Login Page
}
?>
But the include statement makes the home page inaccessible. Every time I go to the home page it just sends me back to the index.html page.
Are there any better ways to secure a web page? If so please tell me or explain why this doesn't work,
For securing a webpage i encourage you to work with sessions.
You use one script (lets call it login.php) to allow the user to login. If the login is correct you store the username as a session variable.
In your secured pages you just check if the username is set in the session.
In all your scripts you need to execute session_start(); to make the $_SESSION superglobal variable available.
For logging out you can just destroy the users session using session_destroy();
Examples:
login.php:
session_start();
function isValidLogin($username_, $password_)
{
if($username_=='sam' && $password_=='secret')
return true;
return false;
}
if(isValidLogin($username, password))
{
$_SESSION['username']=$username;
}
your_secured_page.php:
session_start();
if(isset($_SESSION['username'))
{
// display page
}
else
{
// redirect to login.php
}
logout.php
session_destroy();
Another tutorial i found:
http://www.formget.com/login-form-in-php/
You Might Wanna Use This.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Fetch Array Trick</title>
</head>
<body>
<?php
$con = mysqli_connect("localhost","root","","lesson") or die("Connection Not Established");
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
$username = $_POST['username'];
$password = $_POST['password'];
$get=array("0"=>$username,"username"=>$username,'1'=>$password,"password"=>$password);
//Created an array above that matches username and password.
$lol = mysqli_query($con,"Select username,password from users");
while($pre= mysqli_fetch_array($lol)){
//Now we check if, while in the loop, any tuple matches
if (($get == $pre)){
echo '<h1><font color=green>Found</font></h1>';
//Use JavaScript To Redirect or clear headers to use header("location: dashboard.php");
exit;
}
}
echo '<h1><font color=red>Not Found</font></h1>';
}
?>
<form action="" method="post">
<p><label for="u">Username</label><input type="text" name="username" id="u"></p>
<p><label for="password">Password</label><input type="password" name="password" id="password"></p>
<p><input type="submit" name="submit" value="Login" id="submit"></p>
</form>
</body>
</html>
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 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.