Variable $_SESSION does not work PHP - php

I want to add a simple "login/logout" script to my web site but it does not work.
<?php if(isset($_POST["signin"])){
session_start();
$username=stripslashes($_POST["username"]);
$password=stripslashes($_POST["password"]);
$username = mysql_real_escape_string($username);
$password = mysql_real_escape_string($password);
$nom=checkUser($username, $password);
if(!$nom=="")
{
$_SESSION['name'] = $nom;
header("location:account.php");
}
else {
echo 'WRONG USERNAME OR PASSWORD';}
}?>
the script above is header.php which means it's included in every single page; now here is the page of "account.php"
<?php if(isset($_SESSION['name']))
{
include('header.php');
echo'
</article>
<article class="col1 pad_left1">
<p>Bienvenue '.$_SESSION['name'].'</p>
</article>
</header>
</div>';
include('footer.php');}
header("location:index.php");
?>
The problem is that i always get to the index.php even if i'm logged in as if this test if(isset($_session['name'])) is always false.

I guess you rather want to use if($nom!="") than if(!$nom==""). Additionally, you need to call session_start() before you can use $_SESSION (you're doing it the other way round at the moment).

you have to start session in every page at the top by
session_start();
probably you are missing this.

Try to add session_start(); before if(isset($_SESSION['name'])) and check if it's a blank lines in your files at the top and in the end.

Related

Display a link only if user is an admin

I am very new to PHP and I am trying to make a registration form only for an admin(no need for other users). I want to show one of the menu nav ("Add photo") only to admins.
LOGIN.php:
<?php
include_once 'header.php';
$username = "Efren";
$password = "111";
if (($_POST['txt_uname_email'] == $username)&& ($_POST['txt_password'] == $password)) {
session_start();
$_SESSION['admin_is_logged'] = true;
echo '<script type="text/javascript"> window.open("homepage.php","_self");</script>';
}
This is the part of the header that I am trying to show only to admins:
<?php
if (isset($_SESSION['admin_is_logged']) && $_SESSION['admin_is_logged'] == true){
echo '<li>add photo</li>';
}
?>
</ul>
Right now “add photo” is hidden both to admin and other visitors.
You need to start session on every page you want access to $_SESSION variable. I saw your session_start is inside if statement. Just set it on top of every file (where you need session) and it should work.
Put
session_start();
on file beginning just after <?php

How to call a script every time a user logs in (or whenever a session is active)

I am trying run a script called random_post_generator.php which should execute every time a user is logged in.
I am using this approach as an alternative to cron.
Here is how my session is currently created:
<?php
ob_start();
session_start();
if (!isset($_SESSION["user_login"])) {
header("Location: index.php");
} else {
$username = $_SESSION["user_login"];
}
?>
But how do I say - "if session is active, then run this script"?
<?php
ob_start();
session_start();
if (!isset($_SESSION["user_login"])) {
header("Location: index.php");
} else {
$username = $_SESSION["user_login"];
include 'random_post_generator.php';
}
?>
or you can use require 'random_post_generator.php'
If I understood correctly, you are trying to find out how to include a script of php (that is located in an outside .php file) inside your current file while using your previous code that checks if a user is logged in:
<?php
$root_directory_path = $_SERVER['DOCUMENT_ROOT'];
ob_start();
session_start();
if (!isset($_SESSION["user_login"])) {
header("Location: index.php");
} else {
$username = $_SESSION["user_login"];
$pathName = $root_directory_path."myScript.php";//I am assuming here
//the script is located inside the root directory, and not in a sub
//directory
require($pathName);
}
?>
just remember that whatever php code is inside myScript.php has to have the <?php ?> tag surrounding it. Your code does not reuse the <?php ?> tag of the "calling" file.
Let me know if that worked for you

Session is not maintained

I have a simple authentication: you login in the login.php page and you are redirected to the home.php page.
This is the code of login.php:
if(pg_num_rows($rs) == 0){ //I search in db for a row with username and password
$errMess = "error";
pg_close($conn);
}else{
$row = pg_fetch_row($rs);
session_start();
$_SESSION['username']=$_POST["nick"];
$_SESSION['admin'] = $row[0];
pg_close($conn);
header("Location: /home.php");
}
now in the home I have the header done in this way:
<?php require_once("scripts/functions.php");
require_once("scripts/config.php");
session_start();
?>
<div id="siteHeader" class="headersLeft"><?php echo WELCOME;?></div>
<div id="userContainer" class="headersRight">
Logged as: <?php echo getDisplayName(); ?>
<?php if(isset($_SESSION['username'])) {?>
<button class="button" onclick="location.href='/logout.php';">logout</button>
<?php }else{ ?>
<button class="button" onclick="location.href='/login.php';">login</button>
<?php }
?>
</div>
it doesn't work: even if data is correct it still gives me "guest", the session variable is lost in the header passage..how come?
Solved: i was under windows and the default path to the temp folder, where php actually saves session files, was wrong: was "/tmp" and was not recognized.
I set it to "C:\php\tmp" and it worked: session file was not saved at all!
Write session_start(); on top of everything (right after
<?php
session_start();
require_once("scripts/functions.php");
require_once("scripts/config.php");
?>
or if still doesn't work then write your code like this:
<?php
ob_start();
session_start();
require_once("scripts/functions.php");
require_once("scripts/config.php");
?>
Also don't forget to put these two lines at the top of your login.php page.
Hope it helps :)
I'm guessing there's some more code after the if statement that continues to manipulate $_SESSION. That's where $_SESSION['username'] is assigned the 'guest' value.
Remember, header("Location: /home.php"); only sets a response header. It doesn't redirect immediately, stopping script execution.
Place a exit; command right after header() to prevent execution from reaching the rest of the code:
header("Location: /home.php");
exit;
this works for me:
session_save_path ( "" ) ;
session_start();

Changing Index Page According to Login

Im creating an website where i am checking for login and redirecting the user to the index page, if his login was successful i want him to see something else instead of the login button
i have followed this approach for my query
<?php
if(!isset($_SESSION['uid']))
{
?>
<span class="Login">Login</span>
<?php
}
else if(isset($_SESSION['uid']))
{
?>
<span>Post</span>
<?php
}
?>
it doesn't seem to work quite the way i want. The 'Login' span is always visible, it would seem that the $_SESSION['uid'] is not being set, but that is not the case. To be honest i don't even know if this is the correct way of doing this
You need to put session_start(); in each page that need to access the session data before accessing (or creating) any session data.
See: Session Manuel
<?php
session_start();
$linkPage = 'login.php';
$linkName = 'Login';
if(isset($_SESSION['uid'])) {
$linkPage = 'postThread.php';
$linkName = 'Post';
}
?>
<span class="link"><?php echo $linkName; ?></span>

Create a function that sets $_SESSION variables

I created a site where you need to login to visit the different pages, nothing special.
To keep the user logged in, I'm setting the session on top of every page.
My problem is, I don't wanna have to set the different session variables on top on each page. I'd rather have one function I can call to set them. Plus I don't need all those variables on each page, so I'd like the function to accept optional parameters (like the email, or profile picture that are not used on every page).
I call this on top of each page:
<?php
require_once 'session.php';
confirm_logged_in();
$username = $_SESSION['username'];
$email = $_SESSION['email'];
$picture = $_SESSION['picture'];
$group = $_SESSION['group'];
?>
I would like to make it more like this and be able to set only the variables I need:
<?php
require_once 'session.php';
confirm_logged_in();
set_variables($username, $email);
?>
The 'session.php' file is like this:
<?php
session_start();
function logged_in(){
return isset($_SESSION['username']);
}
function confirm_logged_in(){
if(!logged_in()){
header('location: start.php');
}
}
?>
I've tried a few things, but it just led me to huge amounts of errors.
Has someone already done this or found a script doing this? Is that possible?
First of all, if what you want to do is overload your function, you can't do that. For more info on that see this. However, you can do this:
<?php
set_variables($username, $email, $picture,$group)
{
$_SESSION['username'] = $username;
$_SESSION['email'] = $email;
$_SESSION['picture'] = $picture;
$_SESSION['group'] = $group;
}
?>
Put this function in your session.php file.
I am not sure if I understood right, but if I did, all you need to do is create a new file, let's call it "Session_Variables.php".
After you created the file, paste the following code into it:
<?php
require_once 'session.php';
confirm_logged_in();
$username = $_SESSION['username'];
$email = $_SESSION['email'];
$picture = $_SESSION['picture'];
$group = $_SESSION['group'];
?>
Then, finally, just replace the old code with:
include("Session_Variables.php");
Not directly related to the question you are asking, but you should really add exit; after a redirect header. Clients can ignore headers and still load your page even while not being logged in.
if you want to make set_variables($username, $email) work like i think you wanted, you need to write something like this.
Session.php
<?php
session_start();
function logged_in(){
return isset($_SESSION['username']);
}
function confirm_logged_in(){
if(!logged_in()){
header('location: start.php');
}
}
//Only Picture and group are Optionals
function set_variables($username, $email, $picture = '', $group = ''){
//you can check here is thoses variables are set or valid before assign them
$_SESSION['username'] = $username;
$_SESSION['email'] = $email;
$_SESSION['picture'] = $picture;
$_SESSION['group'] = $group;
}
//create a function that we need to retrieve thoses values
function get_variable($name){
if ( isset( $_SESSION[$name] ) ) return $_SESSION[$name];
return FALSE; //if the variable is not set.
}
?>
And you can use it like this
<?php
require_once 'session.php';
confirm_logged_in();
set_variables($username, $email);
$username = get_variable('username');
?>
I think you need to move the session_start(); to the actual page. Using a require_once on the session_start(); is not a good plan.

Categories