I have a login.php file:
<?php
session_start();
include('db.php');
if(isset($_POST['email']) && !empty($_POST['email']) AND isset($_POST['password']) && !empty($_POST['password'])){
$email = mysql_escape_string($_POST['email']);
$password = mysql_escape_string($_POST['password']);
$search = mysql_query("SELECT * FROM users WHERE email='".$email."' AND password='".$password."' AND active='1'") or die(mysql_error());
$match = mysql_num_rows($search);
if($match > 0){
$row = mysql_fetch_assoc($search);
$user=$row['forename'].' '.$row['surname'];
$_SESSION['username']=$user;
//$msg = 'Login Complete! Thanks, '.$user.'!';
header( 'Location: page1.php' ) ;
die;
}else{
$msg = 'Login Failed!<br /> Please make sure that you enter the correct details and that you have activated your account.';
}
}
?>
Now, when I load page1.php I have issues. The file contains this...
<?php
session_start();
include('db.php');
if(isset($_SESSION['username'])){
echo 'Success, '.$_SESSION['username'].'!';
}else{
echo 'No dice!';
//header( 'Location: login.php' ) ;
}
?>
I ideally want it to redirect to login if there isn't a username stored. If there is, I want to allow them to view. However, I am getting "No dice!" every time, so it looks like I am not retrieving (or storing) the data correctly. What am I doing wrong?
To be clear, the else shouldn't be firing as it should be referring to session data set in index.php. The redirection is not a problem.
The problem was specific to my host who had a strange setup. On contacting them, they provided me the correct path information which I had to use session_save_path to set. Awarded the right answer on this basis.
Redirect is malformed. You have to specify full url, like this:
header('Location: http://your.site.com/page1.php');
die;
It's important to end the script after redirect.
If session data is not preserved, maybe you have some configuration issues. Verify your php configuration and check write permissions where session data is stored.
<?php phpinfo();?>
I would comment this but the under 50 rep limit means I can't for some reason. Try
$row = mysql_fetch_assoc($search);
$user=$row['forename'].' '.$row['surname'];
echo 'User: '.$user.'<br />';
$_SESSION['username']=$user;
echo 'Session: '.$_SESSION['username'];
//header( 'Location: page1.php' ) ;
and see if anything is actually being stored in the varibles.
EDIT: Try this
if($match > 0){
$row = mysql_fetch_assoc($search);
$user=$row['forename'].' '.$row['surname'];
$_SESSION['username']=$user;
$_SESSION['logintrue'] = true;
//$msg = 'Login Complete! Thanks, '.$user.'!';
header( 'Location: page1.php' ) ;
die;
}
session.php
<?php
session_start();
if(!$_SESSION['logintrue'])
{
header( 'Location: login.php' ) ;
}
$SessionUsername = $_SESSION['username'];
?>
page1.php
<?php
require_once 'session.php';
require_once 'db.php';
echo 'I work now maybe?<br />';
echo $SessionUsername;
?>
Also includes aren't functions so write them like include 'db.php'; I've made that mistake aswell.
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");
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
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
I'm running a login script and according to who logs in I redirect to one of two pages
If I direct to a page that is in a directory below the main directory all works fine, however if i direct to a page that is above the directory in which the index.php file sits, the session information seems to be lost and the user is asked to login again
I know that I could simply place the second page in a directory below the main directory but I would like to understand if it is possible to maintain the session information when directing to a page above the main directory
the user goes to a page called login.html, when they have input there information, they are sent to login.php, it is here where the redirect occurs
if ($username==$dbusername&&$password==$dbpassoword)
{
if($admin == "1"){
header('location: http://www.edit.domain_name.co.uk/');
$_SESSION['username']=$username;
$_SESSION['id']=$id;
}else{
header('location: /member');
$_SESSION['username']=$username;
$_SESSION['id']=$id;
}
}
I have put session_start (); at the beginning of every page where the user would need to login to access. Any input would be greatly received
the full code for the login script is
<?php
session_start () ;
$username = $_POST['username'] ;
$password = $_POST['password'] ;
################# ADMIN OR NOT ###################################################
include_once "mysql/global.php";
$result = mysql_query("SELECT admin FROM users WHERE username = '$username'");
if (!$result) {
echo 'Could not run query: ' . mysql_error();
exit;
}
$row = mysql_fetch_row($result);
$admin = $row[0];
################# ###############################################################
if ($username&&$password)
{
include "mysql/global.php";
$query = mysql_query("SELECT * FROM users WHERE username='$username'") ;
$numrows = mysql_num_rows($query) ;
if ($numrows!=0)
{
while ($row = mysql_fetch_assoc($query) )
{
$dbusername = $row['username'] ;
$dbpassoword = $row["password"] ;
}
// check to see if they match!
if ($username==$dbusername&&$password==$dbpassoword)
{
if($admin == "1"){
session_start();
header('location: http://www.edit.domin_name.co.uk/admin');
$_SESSION['username']=$username;
$_SESSION['id']=$id;
}else{
session_start();
header('location: /member');
$_SESSION['username']=$username;
$_SESSION['id']=$id;
}
}
else
echo "<center>incorrect password!</center>" ;
}
else
die ("<center>That user does not exist!</center>") ;
}
else
echo ("<center>Please enter a username and password</center><br/>") ;
die ("<a href=\"index.php\"><center><b>Click here to try again</b></center></font>");
?>
In order to load sessions, you must place session_start() at the top of each page.
Also, you need to call session_start() before setting them and before redirecting:
if ($username == $dbusername && $password == $dbpassoword) {
if($admin == "1"){
session_start();
$_SESSION['username']=$username;
$_SESSION['id']=$id;
header('Location: http://www.edit.domain_name.co.uk/');
}
else {
session_start();
$_SESSION['username']=$username;
$_SESSION['id']=$id;
header('Location: /member');
}
}
header('location: /member');
For a start, this is invalid. The Location header should be followed by a full, not a relative, URL.
Secondally, if /member is a directory, and you access www.example.com/member, Apache is quite likely to redirect you to example.com/member/, adding the forward slash and dropping the www.. The move to a different domain name is likely to result in the loss of session data.