Create a function that sets $_SESSION variables - php

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.

Related

how to read data from variables using header function in php

in the root of my project folder i have a file called index.php and a directory called views which contains a file called page_one.php ...
index.php file has the follwing code:
<?php
$action = "one";
if ($action == 'one') {
$name = "John";
//include './views/page_one.php';
header("Location: views/page_one.php");
}
?>
and page_one.php has the following code:
<?php echo 'Name = ' . $name; ?>
in the above code I have commented out the line with include because that works perfectly..I want to pass the value of $name using the header function..Is there a way of doing it WITHOUT sending the value in the URL?
I want the address in the URL to change when page_one.php is accessed that is why I am using the header function instead of include...
#Qirel as per said, try using session. Do something like this in index.php
<?php
session_start();
$_SESSION['name'] = "John";
header("Location: views/page_one.php);
exit();
?>
and inside page_one.php
<?php
session_start();
echo $_SESSION['name'];
unset($_SESSION['name']); // remove it now we have used it
?>

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

Multiple steps form with sessions security

Hi i'm developing a multi steps form with php using session and i've been wondering if there is a way for the user to alter session variables for example on the first page i have something like this :
<?php
session_start();
if(isset($_POST['submit'])){
$_SESSION['name'] = $_POST['name'];//and so on
}
?>
and the other page has something like :
<?php
session_start();
$name = $_SESSION['name'];
?>
my question is can the user modify the value of the session variable on the second page
Since you're populating the session variable with the value of a POST variable, they can continue to resubmit the first form as much as they want with arbitrary values.
You can use application logic to defeat this:
<?php // form1
session_start();
if (empty($_SESSION['step'])) {
$_SESSION['step'] = 1;
}
if ($_SESSION['step'] > 1) {
header("Location: form2.php");
exit; // This exit is very important, don't neglect it
}
if (isset($_POST['submit'])){
$_SESSION['name'] = $_POST['name'];//and so on
$_SESSION['step'] = 2;
}
And then
<?php // form2
session_start();
if (empty($_SESSION['step'])) {
header("Location: form1.php");
exit;
}
if ($_SESSION['step'] > 2) {
header("Location: form3.php");
exit;
}
if ($_SESSION['step'] < 2) {
header("Location: form1.php");
exit;
}
$name = $_POST['name'];
By using application logic, you can control the flow of your visitors within your application.
If you're asking if users can change $_SESSION variables outside of any code you've written, the answer is usually no. See also: this answer.

$_SESSION Variable not set until I call another function?

I have a very perplexing problem, namely at the top of my files I call a foreign function "sessionTest", which tests various session criteria and returns the correct header string. This is necessary, because I have two different headers: one for logged in users and one for non-users/logged out users.
My problem is in the following code:
<?php include './session.php';
include './db.php';
$con = genCon();
if(isset($_SESSION['logged'])){
echo "Logged: ".$_SESSION['logged'];
}
$headerstring = sessionTest($con); ?>
...Rest of Page...
For some reason, isset($_SESSION['logged']) is returning false here, but true in sessionTest:
function sessionTest($con){
session_start();
$fingerprint = md5($_SERVER['HTTP_USER_AGENT'].session_id());
if(isset($_SESSION['user']) && isset($_SESSION['logged']) && $_SESSION['logged']==TRUE){
$dbFingerprint = qGetUserFingerprint($_SESSION['user'],$con);
$fpMatch = ($dbFingerprint == $fingerprint);
//LEAVING OUT NON RELEVANT CODE
$headerstring = './lheader.html';
}else{
$headerstring = './header.html';
}
return $headerstring;
}
The headerstring is being set to lheader.html, so isset($_SESSION['logged']) is returning true here. Does anyone have an idea why??
Thanks in advance!
you need to put session_start();
<?php
-> session_start();
include './session.php';
include './db.php';
$con = genCon();
if(isset($_SESSION['logged'])){
echo "Logged: ".$_SESSION['logged'];
}
$headerstring = sessionTest($con); ?>

Variable $_SESSION does not work 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.

Categories