Session variables in php not being stored - php

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
}

Related

PHP Session Issue when trying to create a login and register system

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.

Go to HTML page from PHP function

I started PHP recently and I was wondering :
I have a php file which only contains a function called sqlConnect(); which checks that the user isn't yet logged into the MySQL DB, and if so, redirects the user to an html page which is a form for the user to enter the username and password for the DB. After the user has submitted the form, I want to get back to the point where I left (in the function).
One thing you should know too is that the $_SESSION is started in another file which calls this function.
Here's what I tried, yet it didn't work :
connect.php :
<?php
function sqlConnect() {
$_SESSION['CurrentPage'] = "/php/sql/connect.php";
if(!array_key_exists('mysql_username', $_SESSION) && !array_key_exists('mysql_passwd', $_SESSION)) {
echo "<script>window.location='/forms/sql_login.php';</script>";
}
$servername = "localhost";
$username = $_SESSION['mysql_username'];
$passwd = $_SESSION['mysql_passwd'];
$db_name = "ToolDB";
// create connection
$sql_connection = new mysqli($servername, $username, $passwd, $db_name);
// check that it was established
if($sql_connection->connect_error) {
$msg = $sql_connection->connect_error;
echo "<script>alert('Impossible de se connecter à la base de données MySQL : $msg.');</script>";
return NULL;
}
else {
$_SESSION['mysql_username'] = $username;
$_SESSION['mysql_passwd'] = $passwd;
return $sql_connection;
}
}
?>
sql_connection.php :
<?php session_start(); $url = $_SESSION['CurrentPage']; ?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Sound Department - Program Making Tool (form)</title>
<link rel="stylesheet" type="text/css" href="/style/style.css" />
</head>
<body>
<header>
<nav>
<h2 style="margin-left: 10px; font-family: sans-serif;">Sound Department - Program Making Tool (MySQL Login Page)</h2>
</nav>
</header>
<div class="bodyElement">
<form action="<?php echo $url ?>" method="post">
<p>Nom d'utilisateur : <input type="text" name="mysql_username" /></p>
<p>Mot de passe : <input type="password" name="mysql_passwd"/></p>
<p><input type="submit" name="submit" value="Submit" /></p>
</form>
</div>
</body>
</html>
Does anybody know how to achieve that ?
PS : I know I shouldn't store the password in plain text, but the site is running on my local network for now and I thought I was just gonna modify my code to store the password in a more convenient way later.
ob_end_clean();
header("Location: example.com");
exit();
Put this at the end where you want the user to be redirected.
Header() doesn't let you redirect after an output is given, but
ob_end_clean()
allows you to redirect after an output.
You can use the header() function to redirect clients to another page.
<?php
header('Location: <your page>');
exit;
?>

PHP $_SESSION Not checking login status

I've looked through multiple web articles and stackoverflow answers, however I cannot find the bug in my code. Maybe I've been looking at it too long.
Basically I'm just setting up a simple login for a demonstration, yes I know its inject-able and outdated, this doesn't matter. Basically I'm using a login with sessions and then redirecting the user to secure content when they're logged in. I've also created a script that checks for the session variables, to see if the user is logged in or not. Basically, I'm beating a dead horse and I don't know why this isn't working, could someone please help?
index.php:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Welcome, please log in</title>
<link href="../css/admin.css" rel="stylesheet" type="text/css">
</head>
<body>
<?PHP require_once"scripts/mysql_connect.php"; // Establish a database connection ?>
<div id="admin_top">
<div id="admin_logo"></div>
</div>
<div id="admin_login_box">
<H1 style="margin-left: 20px;">Please log in</H1>
<hr><br>
<?PHP
echo "<form method='post' action='checklogin.php' name='loginform'>
<input type='email' name='aEmail' placeholder='Your Email Address' required><br>
<input type='password' name='aPassword' placeholder='Password' required><br><br>
<input type='submit' value='Log In'>
</form>"
?>
</div>
</body>
</html>
checklogin.php:
<!doctype html>
<html>
<head>
<title>Checking login...</title>
<link href="../css/admin.css" rel="stylesheet" type="text/css">
</head>
<body>
<div id="admin_top">
<div id="admin_logo"></div>
</div>
<div id="admin_login_box">
<?php
require_once"scripts/mysql_connect.php";
$aEmail = $_POST['aEmail'];
$aPassword = $_POST['aPassword'];
$md5Password = MD5($aPassword);
$sql = "SQL";
$result = mysql_query($sql);
$row = mysql_fetch_array($result);
$active = $row['active'];
$count = mysql_num_rows($result);
// If result matched, table row must be 1 row.
if($count == 1) {
$_SESSION["login"] = "OK";
$_SESSION["aEmail"] = $aEmail;
echo "<h1>Log in successfull!</h1>
<hr><br />
Your details checked out! Redirecting you now...";
// Wait 1 seconds then redirect to the secure content.
header("Location: http://www.website.com/secure_content.php");
} else {
echo "<h1>Log in unsuccessfull!</h1>
<hr><br />
Sorry. It seems your log in detials were incorrect. Please go back and try again.";
// Wait 2 seconds then redirect back to the log in page.
header("Location: http://www.website.com/index.php");
}
exit;
?>
</div>
</body>
</html>
loginstatus.php:
<?php session_start();
if(!(isset($_SESSION["login"]) && $_SESSION["login"] == "OK")) {
header("Location: http://www.website.com/index.php");
exit;
}
?>
Thanks for any help!
In checklogin.php and index.php you need to start the session. Add the following code before <!doctype html>
Add this code:
<?php session_start(); ?>
You forgot to put that line in this file because you are creating a new session during the checks in the database.
Looks like you haven't started the session in the first place. On the top of your page please write the following code:
<?php session_start(); ?>
Now, secondly, I'd suggest you to write your HTML and PHP separately instead of writing your HTML for the form within the echo.
Also, it's better if you add a name to your submit button.
Let me show a sample below.
<div id="admin_login_box">
<H1 style="margin-left: 20px;">Please log in</H1>
<hr><br>
<form method='POST' action='checklogin.php' name='loginform'>
<input type='email' name='aEmail' placeholder='Your Email Address' required><br>
<input type='password' name='aPassword' placeholder='Password' required><br><br>
<input type='submit' name='submit' value='Log In'>
</form>
Now, in your checklogin.php. you should place an isset condition and see if you're getting any POST request.
Try this:
<?php
require_once"scripts/mysql_connect.php";
if (isset($_POST['submit']) { // Add this condition
$aEmail = $_POST['aEmail'];
$aPassword = $_POST['aPassword'];
$md5Password = MD5($aPassword);
/* Other code */
if($count == 1) {
/* Other code */
} else {
/* Other code */
}
}
Hope this helps.

Can't get variables from SESSION

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

How to redirect to another page using PHP [duplicate]

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
}
?>

Categories