I'm trying to pass variables between consecutive pages of an automated php process. Because this is automated, I tried setting the variables like this in the prior page:
$_POST['index1'] = $variable1;
$_POST['index2'] = $variable2;
$_POST['index3'] = $variable3
$_POST['index4'] = "hard coded string";
I also have alert statements printing out these values on the prior page just to make sure they're getting set, which they are. But when I move to the following page and try to access those variables, I get undefined index errors for all of these variables. What's happening to the variables from one page to the next that they're not getting passed as expected?
Let's try the following since the information is sensitive.
At the very, very, very, very top of each of the PHP pages connected to this function add:
<?
session_start();
?>
Make sure nothing else is above it, no html, no nothing! Otherwise it will mess up whatever you are trying to do.
On the page you were originally setting your $_POST variables do the following:
$_SESSION["variable1"] = "You";
$_SESSION["variable2"] = "Shall";
$_SESSION["variable3"] = "Not";
$_SESSION["variable4"] = "Pass";
You can ofcourse change the "variable1","variable2" and all of its values into whatever you like.
On whichever page you have included
<?
session_start();
?>
You can now call echo/print/assign each of the $_SESSION variables you set before by echoing:
echo $_SESSION['variable1'];
This would produce the following: "You"
This is a more secure way of transferring data (however sessions can still be hijacked unless you're using HTTPS).
Whenever you are done using the data you can simply unset each $_SESSION variable by using either session_unset(); or session_destroy();
I hope this helps!
Related
I have a problem with PHP session. When i start session, and try to add a variable to it i can only get in the same PHP script where i declared it like it's normal variable. Browser debuger also seems to not see any variable in session.
<?php
echo session_start(); //This returns 1 so session is created
$_SESSION["A"] = "B";
echo $_SESSION["A"]; // And this prints "B" as predicted
?>
But there is nothing in session!
You are confusing server-side PHP sessions, with the client-side JavaScript sessionStorage here. Both are two completely different things.
https://www.php.net/manual/en/intro.session.php
https://developer.mozilla.org/en-US/docs/Web/API/Window/sessionStorage
Browser debuger also seems to not see any variable in session.
PHP session data is kept on the server, the browser can never “see it”, unless you explicitly output it somewhere (as you did with echo $_SESSION["A"];, but even then it of course won’t show in the sessionStorage debug panel.)
i can only get in the same PHP script where i declared it like it's normal variable.
Then you most likely neglected to pick your session up again in the other script files. You need to call session_start at the beginning of all of them.
So I'm trying to make the posts.php page look like this >> 'posts.php?user='.$username << for each individual user.
Here is the code on my index.php page (which after a user logs in/signs up turns into >> 'index.php?user='.$username :
<?php
include('header.php');
session_start();
if(!isset($_SESSION['username'])) {
//do nothing
} else {
$_SESSION['username'] = $_GET['user'];
$username = $_GET['user'];
$_SESSION['username'] = $username;
}
Here is the code so far on my posts.php page :
<?php
include('header.php');
session_start();
if(!isset($_SESSION['username'])) {
header('location: must_login.php');
} else {
//idk what to put here
}
?>
I'm trying to get my posts.php page header to look like this >> 'posts.php?user='.$username
I understand you are on day 1 of PHP learning. You are getting a lot of negative responses because your question isn't very specific. You aren't very clear about what is "not working." You should say what you expect to happen, and what is happening.
Here's my answer based on what I think you're asking.
Since the username would usually be gotten from a sign-in form, and sign-in forms usually use POST, you should probably do that. Use POST instead of GET.
included files have access to all the global variables in the file from which they are included.
File#1:
// index.php
$username = $_POST['user'];
include('header.php');
File#2:
// header.php
<div id="header">
<p>You are logged in as user "<?= $username ?>"</p>
</div>
The variable you set in index.php $username is available for use in header.php.
Ok so there's a fair few things you need to consider here, but we all had to learn once so I'll try and cover most of them.
Firstly (as #TrentonMaki has said): DO NOT USE USERNAMES IN URLs. If this site is going live, it is probably the most dangerous thing you can do, aside from printing out your passwords onto the screen.
You must read about authorisation and authentication before you continue.
Secondly, in the interests of learning: the $_SESSION super-global is not the right one to use for URL variables. We call URL variables "GET" variables and therefore they are accessible like this:
$user = mb_convert_encoding($_GET['myVar'], ‘UTF-8′, ‘UTF-8′);
$user = htmlentities($user, ENT_QUOTES, ‘UTF-8′);
These functions 'escape' the data in the variables to make them safe from XSS and SQL Injection attacks (there are alot of other precautions you need to take as well - but they are outside of the scope of this question).
In terms of Sessions, these are variables that are stored in the server memory and persist between pages. there are several considerations when using Sessions (security vulnerabilties like "Session Hijacking") and things you can do to make Sessions safer, but here is how they basically work.
//start the session to retrieve or set variables
session_start();
//you should regenerate session_id here - you need to look up how to do this and other Session santisation.
//set a session var
$_SESSION['myVar'] = "myString";
Now when a new page is loaded you can get the value of a $_SESSION var:
//start the session to retrieve or set variables
session_start();
//you should regenerate session_id here - you need to look up how to do this and other Session santisation.
//get a session var
$myVar = $_SESSION['myVar'];
Some other topics you should definitely learn before you go any further:
mysqli extension - do not use the mysql functions - this is by far the most common mistake new PHP developers make
Prepared statements - these are a MUST for live data security. You should learn them so you never use anything else.
Note :
1.Passing Variable above included file will passing variable to all included script
2.session_start(); must ONLY ONTOP of script and call only session_start(); to avoid session already started error.
<?php
session_start();
$username = $_POST['user'];
include('header.php');
?>
Is it not mandatory to use session_start() before using any session variables in PHP?
I tried the following piece of code without declaring session_start() at the beginning, it worked fine.
So, now I'm confused. Please help !!!!
Also, I did not use any $_POST or $_GET to pass $uname to home.php, but still how does it work? If we use include 'home.php' then does it treat login.php and home.php as same page?
// code login.php//
<?
require_once 'db_connect.php';
if (isset($_SESSION ['user_id']) && !empty($_SESSION ['user_id']))
{
$u_name = $_SESSION['user_name'];
include 'home.php';
}
else
{
//some stmt
}
?>
/*******home.php file ****/
<?php
require_once 'dbconnect.php';
$_SESSION['username'] = $u_name;
//echo $_SESSION['username'];
//blah blah
?>
You definitely need it, if session.autostart is not set in php.ini. But you would probably know that then.
Do you not call it in db_connect.php? Also, I'm pretty sure you wouldn't get any errors, the session would just be empty.
If you include a file via php, Session keeps active (as any others variables set too). If you would access this file as new request, you would need to set session_start().
This behaviour is because include and require act like moving the code of the included file into the current one, as you would have typed the code into one single file.
Plus: you don't need to require dbconnect.php twice.
edit: you asked about both files used as the same page - the page is the output given after the whole php code is done. The page itself doesn't care about how many files internally are used for generating it.
Use the session_start () is obligatory for every session in php. Being passed through a variable values is not necessary to make POST or GET the same, since there is already the case the value increment. If not ouver value in the same session is null or blank, if you open the page in the same way the condition is wrong.
(!Isset($_SESSION ['user_id']) &&!Is_Null($_SESSION['user_id']))
isset to check if empty this need! before, IF(!isset($_SESSION['user_id']) and in the second case would be to check if it is not null and void, for a session either exists or does not exist and if a value is set inesistente is null. So correct view is this: is_null($_SESSION ['user_id'])
Importantly, in the login page does not include but redirect to the page. in the case with a header.
Or could do everything in a single page, but it would not be legal to display on a page called login page. The default would be the index, ie if the login stay within a folder, you place it inside the index page and the address of the folder.
The reason for the session can still open is that sometimes the webserver does not realize that erased part of the code and loads of it from the system cache.
Ok, this is starting to annoy me, as it's quite simply and works elsewhere, but on this current task it doesn't, so here I go!
There is a main page which relies on either a session variable being set or not to display certain information.
Let's say this page is located here: http://dev.example.com/some_page.php
e.g.
if (isset($_SESSION["some_var"])) { /* it's set so do whatever */ }
else { /* not set so do whatever else.. */ }
There is an ajax page triggered by jQuery $.ajax() to call and set this session variable to null to change the action of the main page, let's say it's located here: http://dev.example.com/ajax/some_ajax_page.php
It's code looks like so:
<?php
if (!isset($_SESSION)) session_start();
$_SESSION["some_var"] = null;
When the main page is reloaded after the ajax is triggered, the session var "some_var" is still intact, but if it's echoed after the "null" in the ajax page then it is set to "null".
Basically it doesn't seem to write to the global session, only to the local path.
Does this make sense?
Any help please? Also if you want more clarification with anything let me know!
The session_start() function will handle the attempt to create and persist a session for you, as defined by PHP's configuration, or optionally at runtime if you set your own save handler. Make sure you read the documentation here:
http://us2.php.net/manual/en/function.session-start.php
For your code, you want to make sure to call session_start() at the beginning of any page in which you'd like to save or access session variables. So your page above may look like:
<?php
session_start();
$_SESSION['myvar'] = 'some value';
Then in a different page you can try to access that value:
<?php
session_start();
if ($_SESSION['myvar'] == 'some value') {
// do something
}
That should work fine.
Get rid of the check for session. If this is the only file your calling just do this:
<?php
session_start();
$_SESSION["some_var"] = null;
Also, are you using framework that auto-regenerates session ID on each request? If so, you'll might have problems.
If you have a dev machine to play with and permissions to do so, you can manually delete all sessions in the /var/lib/php/session/ directory. As you use your site, only one session file should be created. You can also inspect that file to see what is getting written and when.
Seems that you are using different sessions vars. One for the AJAX call and another for the normal pages calls. This may occur when you do not init both call in the same way (or using the same starting code that initializes the sessions)
Be sure to session_start() both calls using the same session_id.
// try in both calls
session_start();
echo session_id(); // must return the same id in both calls
Why don't you use unset? It is the proper way to do it.
Turns out the application I was working on had it's own session_handler and if it was not included before requesting the session data, it was always invalid, eventhough it was the same session_id.
I want to save some values to the $_SESSION variable, I tried to create sessions like this:
if(isset($row_WADAsarenewals['AgreeNum'])) {
$_SESSION['AgreeNum'] = $row_WADAsarenewals['AgreeNum'];
}
But when I try to display this session like this it does not show up? echo($AgreeNum); What am I doing wrong?
To echo your session you will need to call the session-variable, not a regular variable with the same name as the the session-variable. So your echo would be:
echo $_SESSION["AgreeNum"];
Also, if you are having problems writing to your session, you might have to call session_start() prior to writing anything to your session.
You need to use
session_start()
at the beginning of your new script.
You need to use session_start(); prior to store something on the $_SESSION.
Then on the page you want to display the stored values, resume the session by calling again the session_start(); function. And retrieve the stored data like $AgreeNum = $_SESSION['AgreeNum'];
A call to echo($AgreeNum); should output the stored value.
You need to do;
echo $_SESSION['AgreeNum'];
Your solution just work when you have http://www.php.net/manual/en/security.globals.php turned on, which is not recommended. Because then $AgreeNum can came from $_GET for example.