I'm having a problem with my school project. I've asked both my teacher and classmates for help but none of them doesn't know what to do.
I've made a browser based game, and obviously it needs to have users. And this is where the problem is.
When i log in and proceed to the authenticate page, it extracts info from POST just fine, but when i insert the info into SESSION in authenticate and then go to the homepage index, it refuses to get the SESSION information and i just get an error.
NOTE, design2.php doesnt have anything to do with the log in process.
Here's the code:
Login.php
<?php
include_once'design2.php';
?>
<div id="center">
<form method="POST" action="authenticate.php">
User Name <input id="input" type="text" name="player" size="21">
Password <input id="input" type="password" name="password" size="21">
<br>
<input type="submit" value="Login" name="submit">
<br><br>Not Registered? <a id='underlinelink' href='register.php'>Register</a>
Authenticate.php
<?php
include_once 'connect.php';
?>
<div id="center">
<?php
if (isset($_POST['submit']))
{
$player=$_POST['player'];
$password=$_POST['password'];
$player=strip_tags($player);
$password=strip_tags($password);
$password=md5($password);
$query = "select name, password from players where name='$player' and password='$password'";
$result = mysql_query($query) or die("Could not query players");
$result2 = mysql_fetch_array($result);
if ($result2)
{
$_SESSION['player'] = $player;
echo "<big>Logged in successfully<br>";
echo "<A id='underlinelink' href='index.php'>Continue</a></big>";
}
else
{
echo "<big>Wrong username or password.<A id='underlinelink' href='login.php'>Try Again</a></big>";
}
}
?>
</div>
Design.php (This is on every single webpage on my site)
<?php
include_once 'connect.php';
?>
<link href="stilark.css" rel="stylesheet" type="css" />
<?php
session_start();
if(isset($_SESSION['player']))
$player = $_SESSION['player'];
else
echo "could not logg in, <a href='login.php'>Go back</a>";
exit;
$playerinfo="SELECT * from players where name='$player'";
$playerinfo2=mysql_query($playerinfo) or die("could not get player stats!");
$playerinfo3=mysql_fetch_array($playerinfo2);
?>
Please help, i really need to get this done before its due.
You need to create or resume the session before you write into it. So in your Authenticate.php where you do $_SESSION['player'] = $player;, create a session first exactly as you do it in your other files. Something like that
Authenticate.php
<?php
session_start();
include_once 'connect.php';
?>
<div id="center">
<?php
// Rest of your code
// ...
if ($result2)
{
$_SESSION['player'] = $player;
// and so on...
Also, as #DamienLegros noted in his answer, you should always have the session_start() statement as early as possible in your code, i.e. as one of the first statements, so you make sure no output has been made before it's started. Otherwise you'll start getting errors stating that headers has already been sent.
Your session_start() must be BEFORE any output
<?php
session_start();
include_once 'connect.php';
?>
<link href="stilark.css" rel="stylesheet" type="css" />
<?php
session_start();
include_once 'connect.php';
?>
<div id="center">
<?php
if (isset($_POST['submit']))
...
...
...
note: add session_start(); at the top of your Authenticate.php page
Related
I am currently in the process of developing a browser based game in php to test myself, and unfortunately I am having trouble with sessions. The pages seem to all just go blank if i set session include in the header, but then it doesn't redirect to membersarea.php when a user logs in using the form (form works i think). I may be doing all this wrong
header.php
<?php
include 'inc/conf.php';
?>
<!DOCTYPE html>
<head>
<title>Mineshaft Online | Free to play Browser MMORPG</title>
<link rel="stylesheet" href="style/style.css">
</head>
<body>
<?php
if(isset($_SESSION['username'])) {
?>
<div class="navigation">
<ul>
<li>Dashboard</li>
<li>Mineshaft</li>
<li>Smeltery</li>
<li>Blacksmith</li>
<li>Settings</li>
<li>Logout</li>
</ul>
</div>
<?php
} else {
?>
<div class="navigation">
<ul>
<li>Home</li>
<li>Login</li>
<li>Register</li>
</ul>
</div>
<?php
}
?>
<div class="main-content">
and here is the login.php
<?php
include 'inc/conf.php';
include 'header.php';
if(isset($_POST['submit'])){
// Escape special characters in a string
$username = mysqli_real_escape_string($conn, $_POST['username']);
$password = mysqli_real_escape_string($conn, $_POST['password']);
// If username and password are not empty
if ($username != "" && $password != ""){
// Query database to find user with matching username and password
$query = "select count(*) as cntUser from users where username='".$username."' and password='".$password."'";
$result = mysqli_query($conn, $query); // Store query result
$row = mysqli_fetch_array($result); // Fetch row as associative array
$count = $row['cntUser']; // Get number of rows
if($count > 0){
$_SESSION['username'] = $username;
header('location: membersarea.php');
} else {
echo "Error! Invalid username and password.";
}
}
}
?>
<form method="post" action="">
<div id="div_login">
<h1>Login</h1>
<div>
<input type="text" class="textbox" id="username" name="username" placeholder="Username" />
</div>
<div>
<input type="password" class="textbox" id="password" name="password" placeholder="Password"/>
</div>
<div>
<input type="submit" value="Submit" name="submit" id="submit" />
</div>
</div>
</form>
Here is the 'inc/session.php' file
<?php
session_start();
if(!isset($_SESSION["username"])) {
header("Location: login.php");
exit();
}
?>
It sounds like the inc/session.php file isn't included at any point in your project. If you want to use sessions, all the scripts using them must start with the session_start() function, and that, before you start to write any html in your page.
That being said, I'm tempted to assume that you've made a little mistake, writing 'inc/session.php' instead of 'inc/config.php' file, which is indeed loaded in your scripts.
I see two things that you should check:
In your 'login.php' file, you include the 'inc/config.php' as well as the 'header.php' file (which already includes 'inc/config.php'). That might be a problem, because you will then start your sessions two times.
In your 'inc/config.php' file (again, assuming that this is the 'inc/session.php' that you wrote), you start the sessions, and immediately say "if the session 'username' doesn't exist, then we redirect to login.php", which would be a problem if you don't have your 'username' session created before... this would do a redirection loop and your web browser should stop and display a message explaining so.
Other than that, make sure that your server has the sessions activated, you could write a simple script (with nothing else in the file, to keep it simple) like this:
<?php session_start(); $_SESSION['test'] = 'it works!'; ?>
Run the script once, then change the same file to:
<?php session_start(); if(isset($_SESSION['test'])) { echo $_SESSION['test']; } else { echo 'The SESSION test has not been set'; } ?>
And see what your script say.
I hope you are doing great,
I'm making this website with login accounts apparently, I have registered my users in a local database and in a server database. My HTML/PHP code doesn't show any errors when I run it.I have checked my DB connection. it's correct. The website allows me to sign in with any user and password. It doesn't seem to validate my entered data properly. Although I checked my SQL command.
I wonder if you could help me with this guys. You are the best! :)
thanks in advance, Cheers
here is a useful piece of my code:
My header - Header.php:
<html>
<?php
/* static $called = FALSE;
if (!$called)
{*/
session_start();
/*$called = true;
}*/
include_once 'debugging.php';
?>
<head>
<link href="style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div >
<dt id="navbar1" class ="navbar">
Home
Upload Videos
</dt>
</div>
<?php
if (isset($_SESSION['logged'])) {
echo '<div class="right navbar" id = "navbar2">
Log out
<p class = "right">/</p>
Edit Account
<img src="http://www.extremetech.com/wp-content/uploads/2013/11/emp-blast.jpg?type=square"
height="42" width="42" class = "right"/>
</div>';
} else {
echo '<div class="right navbar" id = "navbar2">
Login
<p class = "right">/</p>
Sign Up
</div>';
}
?>
Progress - Feedback:
Ok guys, I tried what you told me to do. It started to make me sign in automatically. Probably the session['logged'] variable declaration is considered to be true. I set it to be true only if the user login from the login page. but it is not functioning in that way.
Here is my login page code:
<?php
include_once 'Header.php';
?>
<div id="container">
<br>
<?php
/*
if($_DEBUG)
{
ini_set('display_errors', 1);
ini_set('log_errors', 1);
ini_set('error_log', dirname(__FILE__) . '/error_log.txt');
error_reporting(E_ALL);
}
$page_title = 'Login';/* */
//in this page we do things slightly differently - the code for validation
and displaying messages is done
//before we display the form
echo '<div id = "div_1"><h1>Login</h1>';
//display the form
echo '<div id="div_2"><div id="div_2">
<form action="index.php" method="post">
<label>UserName<br>
<span class="small">enter your username</span>
</label>
<input type="text" name="UserName" value=""/>
<label><br>Password<br>
<span class="small">enter your password</span>
</label>
<input type="password" name="Password" />
<button type="submit" name="submit" value="Login" />Log in</button>
<input type ="hidden" name="submitted" value="TRUE">
</form>
</div>
</div>';
if (isset($_POST['submitted'])) {
//require_once is similar to 'include' but ensures the code is not
copied multiple times
require_once('LoginFunctions.php');
//list() is a way of assigning multiple values at the same time
//checkLogin() function returns an array so list here assigns the
values in the array to $check and $data
list($check, $data) = checkLogin($_POST['UserName'],
$_POST['Password']);
if ($check) {
setcookie('FName', $data['FName'], time()+ 900 ) ; //cookie
expires after 15 mins
setcookie('LName', $data['LName'], time() + 900 ) ;
//
//use session variables instead of cookies
//these variables should now be available to all pages in the
application as long as the users session exists
$_SESSION['FName'] = $data['FName'];
$_SESSION['LName'] = $data['LName'];
$_SESSION['UserName'] = $data['UserName'];
//to enable $_SESSION array to be populated we always need to call
start_session() - this is done in header.php
//print_r is will print out the contents of an array
print_r($_SESSION);
//
//Redirect to another page
$url = absolute_url('Index.php'); //function defined in
Loginfunctions.php to give absolute path for required page
$_SESSION['logged'] = TRUE;
//this version of the header function is used to redirect to
another page
header("Location: $url");//since we have entered correct login
details we are now being directed to the home page
exit();
} else {
$errors = $data;
}
}
//create a sopace between the button and the error messages
//echo'<div class="spacer"></div>';
if (!empty($errors)) {
echo '<br/> <p class="error">The following errors occurred: <br
/>';
//foreach is a simplified version of the 'for' loop
foreach ($errors as $err) {
echo "$err <br />";
}
echo '</p>';
}
//this is the end of the <div> that contains the form
echo '</div>';
/* */
?>
</div>
<?php
include 'Footer.php';
?>
See the notes section of the session_start documentation. Revise your code as follows:
<?php
// Start the session before ANY output.
// Start the session always - there's little / no value to only starting sometimes.
session_start(); ?>
<html>
<?php
/* static $called = FALSE;
if (!$called)
{*/
/*$called = true;
}*/
include_once 'debugging.php';
?>
<head>
session_start must run before any output is sent to the browser. Additionally, there's no value in having it in an if statement, so keep it simple and put it where it runs consistently before any output.
I'm a student and I'm making a quiz using php and mysql, my problem is I'm trying to echo a name on the results page but it doesn't work.
My first page is an index page where I create a form which gets the users name which I send to my quiz.php page.
<form method="post" action="quiz.php">
<img src="pictures/indeximage.jpg" alt="horrormovies" width="1024" height="640">
<p>
Please Enter Your Name
<br>
<input type="text" name="name">
</p>
<input type="submit" name="submit" value="Start">
</form>
on my quiz.php page i put make a variable and put it in a session
<?php
//start session
session_start();
$var_name=$_REQUEST['name'];
$_SESSION['ses_name']=$var_name;
?>
On my results page I have this
<?php
session_start();
$var_name=$_SESSION['ses_name'];
?>
<p>
Thank you for taking the quiz <?php echo $var_name; ?>.
</p>
Use isset for assign value in session variable. for good practice.
if(isset($_POST['submit']))
{
//start session
session_start();
$var_name=$_REQUEST['name'];
$_SESSION['ses_name']=$var_name;
}
quiz.php
session_start();
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
$_SESSION['ses_name']=$_REQUEST['name'];
}
Try this code :-
results page
<?php
//start session
session_start();
if(!empty($_SESSION['ses_name']))
{
?>
<p>Thank you for taking the quiz <?php echo $_SESSION['ses_name']; ?>.</p>
<?php
}
else{
echo 'session not set ';die;
}
?>
So I have this form that asks for user and password:
<?php
$emmagatzemarSessions="/u/alum/u1920477/public_html/tmp";
ini_set('session.save_path',$emmagatzemarSessions);
session_start();
include 'vars.php';
?>
<html>
<h1>Identificacio</h1>
<h3>Introdueix el teu usuari i contrasenya per entrar a oracle</h3>
<hr>
<form action="menu.php" method="post">
Usuari:
<input type="text"
name="user" />
Contrasenya:
<input
type="password"
name="pass" />
<input type="submit"/>
</form>
<hr>
<?php
$_SESSION["user"] = $_POST["user"];
$_SESSION["pass"] = $_POST["pass"];
?>
</html>
However, in the next file, 'menu.php' it says I couldn't acces the database. The user and password I'm inserting are correct. Here is the code to connect that I'm using:
#!/usr/bin/php-cgi
<?php
$emmagatzemarSessions="/u/alum/u1920477/public_html/tmp";
ini_set('session.save_path',$emmagatzemarSessions);
session_start();
include 'vars.php';
$conn = oci_connect($_SESSION["user"], $_SESSION["pass"], 'oracleps');
echo("username is: " . $_SESSION["user"]);
if (!$conn) {
echo "<p>No hem pogut connectar amb la BD.</p>";
?>
<html>
<br><br><br>
<div id="tornar">
<li>Tornar a l'inici</li>
</div>
<?php
die;
}
?>
<head>
<title>MenĂº empresa</title>
</head>
<body>
<div id="menu">
<h1>MenĂº</h1>
</div>
<div id="alta">
<ul>
<li>Donar d'alta un client</li>
<li>Consultar vehicles disponibles</li>
<li>Llogar un vehicle</li>
<li>Retornar un vehicle llogat</li>
<li>Veure revisions</li>
</ul>
</div>
<br><br><br>
<div id="tornar">
<li>Tornar a l'inici</li>
</div>
</body>
</html>
I have looked for similar questions, asked my collegues who are doing the same thing but I can't find out why this isn't working!
It would be amazing if I could get some help from you guys!
Thanks a lot.
Edited with the full code of both files. Ignore the 4 first lines. I hope you guys can help me because I have no clue what I'm doing wrong!
This line of code should be at the top of every php page where you want to track session:
session_start();
You should also always check if variables are really sent from the form, like this:
if(isset($_SESSION['username']))
{
// do something
}
If you are sure that your logic for connecting to the database is ok, you should log the data you receive from the form, to check if it is correct:
error_log("username is: " . $_POST["username"]);
Start a session on every page that can only be accessed by a user and if it is not set redirect the user
session_start(); //start session
if (!isset($_SESSION['user'])) {
redirect_user();
}
function redirect_user() { //redirect user to home page
$url = BASE_URL . 'index.php'; // Define the URL.
ob_end_clean(); // Delete the buffer.
header("Location: $url");
exit(); #quit
}
This question already has answers here:
How do I make a redirect in PHP?
(34 answers)
Closed 6 months ago.
I'm building a website which includes a login page. I need to redirect the user to their profile page once they've logged in successfully, but I don't know how to do that in PHP (It's my first site).
I've searched the internet and have been told that the header() function should do the trick, but it will only work if I haven't outputted any information before using it.
That's the problem. I've outputted a bunch of information (Including the HTML to build the login page itself).
So how do I redirect the user from one page to the next?
What options do I have? Also, what is the best practice in these instances?
EDIT: Here's my entire login.php page:
<?php
session_start();
echo "<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8'>
<title>Sprout</title>
<link rel='stylesheet' href='stylesheet.css' type='text/css'>
</head>
<body>
<div class='box'>
<form action='login.php' method='post'>
Name<br /> <input type='text' name='username' class='form'/><br />
Password<br /> <input type='password' name='password' class='form'/>
<input type='submit' value='Login' class='button' />
</form>
</div>
</body>
</html>";
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
$username = $_POST["username"];
$password = $_POST["password"];
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "root";
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die ("Error connecting to database");
$dbname = "database";
mysql_select_db($dbname);
$query = "SELECT username FROM users WHERE username = '$username' AND password = '$password'";
$result = mysql_query($query) or die ("Failed Query of " . $query);
while($row = mysql_fetch_assoc($result))
{
$_SESSION["user"] = $username;
}
}
?>
You could use a function similar to:
function redirect($url) {
header('Location: '.$url);
die();
}
Worth noting, you should them with a die() or exit() function to prevent further code execution.
Note that it just makes no sense to output large chunks of HTML if you are going to redirect. Therefore you have to move the form handling code above all HTML. As a side effect it will mitigate the notorious "Headers already sent" error.
Here's a more detailed guide than any of the other answers have mentioned: http://www.exchangecore.com/blog/how-redirect-using-php/
This guide includes reasons for using die() / exit() functions in your redirects, as well as when to use ob_flush() vs ob_start(), and some potential errors that the others answers have left out at this point.
You can conditionally redirect to some page within a php file....
if (ConditionToRedirect){
//You need to redirect
header("Location: http://www.yourwebsite.com/user.php");
exit();
}
else{
// do something
}
That's the problem. I've outputted a bunch of information (including the HTML to build the login page itself). So how do I redirect the user from one page to the next?
This means your application design is pretty broken. You shouldn't be doing output while your business logic is running. Go an use a template engine (like Smarty) or quickfix it by using output buffering).
Another option (not a good one though!) would be outputting JavaScript to redirect:
<script type="text/javascript">location.href = 'newurl';</script>
header won't work for all
Use below simple code
<?php
echo "<script> location.href='new_url'; </script>";
exit;
?>
Assuming you're using cookies for login, just call it after your setcookie call -- after all, you must be calling that one before any output too.
Anyway in general you could check for the presence of your form's submit button name at the beginning of the script, do your logic, and then output stuff:
if(isset($_POST['mySubmit'])) {
// the form was submitted
// ...
// perform your logic
// redirect if login was successful
header('Location: /somewhere');
}
// output your stuff here
You could use ob_start(); before you send any output. This will tell to PHP to keep all the output in a buffer until the script execution ends, so you still can change the header.
Usually I don't use output buffering, for simple projects I keep all the logic on the first part of my script, then I output all HTML.
The simplest approach is that your script validates the form-posted login data "on top" of the script before any output.
If the login is valid you'll redirect using the "header" function.
Even if you use "ob_start()" it sometimes happens that you miss a single whitespace which results in output. But you will see a statement in your error logs then.
<?php
ob_start();
if (FORMPOST) {
if (POSTED_DATA_VALID) {
header("Location: https://www.yoursite.com/profile/");
ob_end_flush();
exit;
}
}
/** YOUR LOGINBOX OUTPUT, ERROR MESSAGES ... **/
ob_end_flush();
?>
firstly create index.php page and just copy paste below code :-
<form name="frmUser" class="well login-form" id="form" method="post" action="login_check.php" onSubmit="return FormValidation()">
<legend>
<icon class="icon-circles"></icon>Restricted Area<icon class="icon-circles-reverse"></icon>
</legend>
<div class="control-group">
<label class="control-label" for="inputPassword">Username</label>
<div class="controls">
<div class="input-prepend">
<span class="add-on"><icon class="icon-user icon-cream"></icon> </span>
<input class="input" type="text" name="username" id="username" placeholder="Username" />
</div>
</div>
</div>
<div class="control-group">
<label class="control-label" for="inputPassword">Password</label>
<div class="controls">
<div class="input-prepend">
<span class="add-on"><icon class="icon-password icon-cream"></icon>
</span> <input class="input" type="password" name="password" id="password" value="" placeholder="Password" />
</div>
</div>
</div>
<div class="control-group signin">
<div class="controls ">
<input type="submit" class="btn btn-block" value="Submit" />
<div class="clearfix">
<span class="icon-forgot"></span>forgot password
</div>
</div>
</div>
</form>
/*------------------after that ----------------------*/
create a login_check.php and just copy paste this below code :-
<?php
session_start();
include('conn.php');
<?php
/* Redirect browser */
header("location:index.php");
/* Make sure that code below does not get executed when we redirect. */
exit;
?>
<?php
if(count($_POST)>0)
{
$result = mysql_query("SELECT * FROM admin WHERE username='".$_POST["username"]."' and password = '".$_POST["password"]."'");
$row = mysql_fetch_array($result);
if(is_array($row))
{
$_SESSION["user_id"] = $row[user_id];
$_SESSION["username"] = $row[username];
$session_register["user_id"] = $row[user_id];
$session_register["username"] = $row[username];
}
else
{
$_SESSION['msg']="Invalid Username or Password";
header("location:index.php");
}
}
if(isset($_SESSION["user_id"]))
{
header("Location:dashboard.php");
}
?>
/*-----------------------after that ----------------------*/
create a dashboard.php and copy paste this code in starting of dashboard.php
<?php
session_start();
include('conn.php');
include('check_session.php');
?>
/*-----------------------after that-----------------*/
create a check_session.php which check your session and copy paste this code :-
<?php
if($_SESSION["user_name"])
{
?>
Welcome <?php echo $_SESSION["user_name"]; ?>. Click here to Logout.
<?php
}
else
{
header("location:index.php");
}
?>
if you have any query so let me know on my mail id farjicompany#gmail.com
Although not secure, (no offense or anything), just stick the header function after you set the session variable
while($row = mysql_fetch_assoc($result))
{
$_SESSION["user"] = $username;
}
header('Location: /profile.php');
On click BUTTON action
if(isset($_POST['save_btn']))
{
//write some of your code here, if necessary
echo'<script> window.location="B.php"; </script> ';
}
----------
<?php
echo '<div style="text-align:center;padding-top:200px;">Go New Page</div>';
$gourl='http://stackoverflow.com';
echo '<META HTTP-EQUIV="Refresh" Content="2; URL='.$gourl.'">';
exit;
?>
----------
Just like you used echo to print a webpage. You could use also do the same with redirecting.
print("<script type=\"text/javascript\">location.href=\"urlHere\"</script>")
<?php
include("config.php");
$id=$_GET['id'];
include("config.php");
if($insert = mysqli_query($con,"update consumer_closeconnection set close_status='Pending' where id="$id" "))
{
?>
<script>
window.location.href='ConsumerCloseConnection.php';
</script>
<?php
}
else
{
?>
<script>
window.location.href='ConsumerCloseConnection.php';
</script>
<?php
}
?>