I am having a problem with the $_SESSION function in my php website. I set the function and then try to access it in another page, but it just comes up as blank.
This is the file login.php where I set the $_SESSION
<?php
session_start();
?>
<html>
<?php
$email = $_POST['email'];
$password = $_POST['password'];
$con = mysqli_connect("host","user","pass","db");
if (!$con)
{
die('Could not connect: ' . mysqli_error());
}
if ($email && $password){
$result = mysqli_query($con, "SELECT * FROM users WHERE email='$email'");
$numrows = mysqli_num_rows($result);
if ($numrows != 0){
//username exists
$row = mysqli_fetch_row($result);
if ($password != $row[2]){
print 'Incorrect password<br />';
$error = TRUE;
}
else {
//password is correct
echo "You're in! <a href='member.php'>Click</a> here to enter member page";
$_SESSION['email'] = $email;
}
}
else {
//email not found
print 'Sorry, that email cannot be found.<br />';
$error = TRUE;
}
}
else {
die('Please enter an email and password<br />');
$error = TRUE;
}
if ($error){
print '<a href=index.php>Go Back</a>';
}
?>
</html>
And this is the member.php file.
<?php
session_start();
if (isset($_SESSION['email'])){
$username = $_SESSION['email'];
echo "Your email is ";
echo $username;
}
?>
When I press the link to go the the member.php page via the link, the page is completely blank, presumably suggesting that the $_SESSION['email'] has nothing in it.
Please let me know where I am going wrong, and how to rectify the issue.
Any help would be much appreciated.
If anyone wants to see how the site is actually working, please go here.
Add session_start(); before the HTML in login.php to set it
You need this call at the very top of login.php, not halfway through.
session_start();
Add this to the very top of the login.php page:
<?php
session_start ();
?>
From the PHP documentation:
"Note:
To use cookie-based sessions, session_start() must be called before outputing anything to the browser."
http://us3.php.net/session_start
If that still doesn't work edit this line:
echo "You're in! <a href='member.php'>Click</a> here to enter member page";
to be like this instead:
echo "You're in! <a href='member.php?" . htmlspecialchars(SID) . "'>Click</a> here to enter member page";
http://us3.php.net/manual/en/session.idpassing.php
Z
Related
I've got a problem with my login to administration on website with https protocol. If I log in, it will write me my error message "You are not allowed. back to login page". Where should be problem? It's working on http protocol fine :-( Thanks for your help!
index.php with login
<?php
include_once "../inc/connection.php";
if(isset($_POST['go'])){
$usr = mysqli_real_escape_string($conn, htmlentities($_POST['u_name']));
$psw = SHA1($_POST['u_pass']) ; //using SHA1() to encrypt passwords
$q = "SELECT * FROM users WHERE username='$usr' AND password='$psw'";
$res = mysqli_query($conn, $q);
if(mysqli_num_rows($res) == 1){
session_start();
$_SESSION['log'] = 'in';
header('location:photos.php');
} else {
$error = 'Wrong details. Please try again';
}
}
?>
and photos.php
<?php
session_start();
if( !isset($_SESSION['log']) || ($_SESSION['log'] != 'in') ){
echo "You are not allowed. <a href='index.php'>back to login page</a>";
exit();
}
if(isset($_GET['log']) && ($_GET['log']=='out')){
session_destroy();
header('location:index.php');
}
?>
I think you session path is not writable.
try
ini_set("session.save_handler", "files");
session_save_path ("/tmp");
This is probably a duplicate but i am having this issue on login when running the following code
<?php
include('includes/functions.php');
if(isset($_POST['login'])) {
if(isset($_POST['username'])) {
if(isset($_POST['password'])) {
$username = $_POST['username'];
$query = mysql_query("SELECT * FROM users WHERE Username = '$username'") or die(mysql_error());
$user = mysql_fetch_array($query);
if(md5($_POST['password']) == $user['password']); {
echo 'Login successful';
$_SESSION['user'] = $user['FullName'];
header("Location:index.php");
}
} else {
echo "Please check your password!";
include('login.php');
}
} else {
echo "Please check your Username!";
include('login.php');
}
} else {
echo "Please check you filled out the login form!";
include('login.php');
}
?>
So when username and password are entered i get this output in browser
Login successful
Warning: Cannot modify header information - headers already sent by (output started at /home/site/public_html/admin/dologin.php:12) in /home/site/public_html/admin/dologin.php on line 14
All help will be greatly appreciated
if(md5($_POST['password']) == $user['password']); {
^
echo 'Login successful';
$_SESSION['user'] = $user['FullName'];
header("Location:index.php");
}
There are 2 issues. That ; inside the if statement should not be there, and then that echo should also go as already mentioned by other answers. Removing the echo should fix that error but your if is messed up because of ; which then causes the header not to work.
Side note: How can I prevent SQL injection in PHP?
There should be no output before the header(<..>) so you should get rid of it (remove lines with echo).
USe :-
<script>location.href - "index.php"; </script>
instead of
header("Location:index.php");
add ob_start(); at the beginning of file..and remove spaces before and after php tags..
Hello im completely new to php and my question is how can i echo out the username of the person who has logged in, on the page they get sent to after logging in successfully?
ive got the login system working and everything but not sure where to write the session stuff etc.
This is my login2a.php
$username = $_POST['username'];
$password = $_POST['password'];
$conn = mysqli_connect('localhost', 'root', '', 'assign02');
$username = mysqli_real_escape_string($conn, $username);
$query = "SELECT password, salt
FROM members
WHERE username = '$username';";
$result = mysqli_query($conn, $query);
if(mysqli_num_rows($result) == 0) // User not found. So, redirect to login_form again.
{
header('Location: login.html');
}
$userData = mysqli_fetch_array($result, MYSQL_ASSOC);
$hash = hash('sha256', $userData['salt'] . hash('sha256', $password) );
//check to see if the password is wrong if wrong redirect user to login forma again and if correct redirect to
if($hash == $userData['password'])
{
header('Location: signed_in.php?username = $username ');
//header('Location: login.html');
}else{ // Redirect to home page after successful login.
//header('Location: signed_in.php?username=$username');
header('Location: login.html');
}
?>
This is the page that i want their username to be displayed, this is just some parts of the website because its too big, what ive echoed is completely wrong i know but hope someone could help me with this problem. This page is the signed_in.php
<div class="layout-978">
<img id="content_background" src="Images/Background.png" />
<div class="main_content">
<div id="top_sellers_title">
<div class="col7">
<!--username displayed to show logged in-->
<?php
if (isset($_SESSION['username'])){
echo "<div id=\"welcome_msg\"> $username </div>";
}
?>
Modify this in your login page and don't forget to use session_start(); at the very beginning of your login page.
if($hash == $userData['password'])
{
$_SESSION['username'] = $username;
header('Location: signed_in.php');
//header('Location: login.html');
}
Then in signed_in.php page, to display the username just do the following
<?php
if(isset($_SESSION['username'])) echo '<div id="welcome_msg">'.$_SESSION['username']. '</div>';
?>
Use session_start() on top of both login2a.php and signed_in.php.
In your login2a.php file where you've successfully authenticated a user, create a session variable named username and assign the username you've passed to the query to that session variable. Here's how
.
.
.
if($hash == $userData['password'])
{
$_SESSION['username'] = $username;
// Continue with your code
}
Hope my answer helps
I'm using $_SESSION to keep my users logged in after they have logged in.
When they return to the homepage, they at first appear to be logged in, but after refreshing the page once, they are no longer logged in.
NOTE: I'm still learning PHP programming so please don't mind that most of my code is rather, noobish.
Index.php Code:
<?php
session_start();
$UserOnline = "Guest";
if (isset($_SESSION['username'])) {
$UserOnline = $_SESSION['username'];
}
echo $UserOnline;
?>
Login.php Code:
<?php
session_start();
$username = $_POST['username'];
$password = $_POST['password'];
if (empty($username)) {
$InvalidLogin = "Please submit a username";
$_SESSION['IL'] = $InvalidLogin;
header ('Location: http://localhost/practice/index.php');
exit;
} elseif (empty($username)) {
$InvalidLogin = "Please submit a password";
$_SESSION['IL'] = $InvalidLogin;
header ('Location: http://localhost/practice/index.php');
exit;
}
require 'required/connect.php';
$result = mysqli_query($con, "SELECT * FROM users WHERE username='$username'");
$row = mysqli_fetch_array($result);
if ($password == $row['password']) {
$_SESSION['username'] = $username;
echo "Successful Login!";
echo "<br>";
echo "<a href='index.php'>Return to HomePage?</a>";
} else {
$InvalidLogin = "Your info didn't match ours!";
$_SESSION['IL'] = $InvalidLogin;
header ('Location: http://localhost/practice/index.php');
exit;
}
?>
I have tested on the login.php page if the user is in a session there, and I always get the correct return value. The issue is that after I refresh once on the Index.php page, the user is no longer in a session.
Is there something I'm forgetting, or am I not using the $_SESSION correctly? Is there another error that I simply do not know about?
Put exit; after header('location:.....') and your problem will be solved.
Issue is resolved. Error was found in Index.php. Set Variable $UserOnline before the if(isset($_SESSION['username'])). Thanks for the help guys
I got a little problem with my php code here... Can you please help me out?
The problem is that when i, in my logout.php, unsets and destroys sessions, it works the first time i load some of my other pages.. but when i refresh right after, the session is started again, which i dont really understand? Because i have my page to look for a session with a specific name. Here is my code:
Login.php:
<?php session_start();
//Get username and password
$email = $_POST['email'];
$password = $_POST['password'];
//Sorting special characters away, with exception of "-" and "."
stripslashes($email);
$email = preg_replace('/[^A-Za-z0-9#\.\-]/','', $email);
//Getting the password from the database
$link = mysqli_connect("****", "****", "****", "****");
if (mysqli_connect_errno($connect))
{
echo "Connection Failed!";
mysqli_close($connect);
}
$sql = "SELECT * FROM admins WHERE email = '". $email . "'";
if ($result = mysqli_query($link, $sql))
{
while ($row = mysqli_fetch_row($result))
{
$db_password = $row[2];
}
mysqli_free_result($result);
}
mysqli_close($connect);
//Compare DB-password to entered password
if ($db_password == $password)
{
$_SESSION['admin'] = $email;
header("Location: ../index.php");
exit();
}
header("Location: index.php");
exit();
?>
Logout.php:
if(!isset($_SESSION['admin']))
{
header("Location: ../index.php");
exit();
}
else
{
session_unset();
session_destroy();
echo '<h1>You have been succesfully logged out!</h>';
exit();
}
Index.php:
if (isset($_SESSION['admin']))
{
echo '<div id="admin"><br>
<h3>'.$_SESSION["admin"].'</h3>
<span>Admin panel</span><br>
<span>Log out</span>
</div>';
}
And yes, i got session_start() on top of every one of my pages.
As you can see in the index.php, i want some code to be written if $_SESSION['admin'] is set. And when i destroy the session in my logout.php, and goes to index.php, it works the first time i load the page. But i i refresh, the code reappear, which means the session must have been set again, somehow! But i dont know why? Please help!
EDIT: I have put the whole code of the login.php now. The rest of the other 2 pages, is pure HTML. What i have posted is all my PHP code!
It might because of the PHPSESSID cookie. just try it by removing PHPSESSID cookie from browser
if(!isset($_SESSION['admin']))
{
header("Location: ../index.php");
exit();
}
else
{
session_unset();
session_destroy();
setcookie('phpsessid','value',time()-1);
echo '<h1>You have been succesfully logged out!</h>';
exit();
}
Once you refresh, your following condition staisfies:
if ($db_password == $password)
connection establishes, session is created and you are redirected to index.php from login.php.
Change this condtion and your script works