I am new to $_SESSIONS but needs it to re-use variables between different php files. In the below code I want to use the variable $word in another php file, but I am unsure how to do this.
My php file looks like this:
<?php
if (isset($_POST["search"])) {
//include database connection
$word = mysql_real_escape_string($_POST["search"]);
$word = htmlentities($word);
$sql = ("SELECT task_id, task_date FROM customer JOIN task ON customer.id = task.customer_id WHERE mobil = $word ORDER BY task_date DESC LIMIT 0, 10");
$results = mysql_query($sql);
if (mysql_num_rows($results)==0) {
echo $word, " text bla";
}else {
echo $word, " text bla bla";
while ($row = mysql_fetch_assoc($results)) {
echo '<pre>', print_r($row), '<pre>';
}
}
}?>
Looking forward to your suggestions.
---UPDATE Sessions still not working on page2.php?---
I do not understand why $_SESSION do not work. One page1.php I can echo($_SESSION['word']) and get the correct value, but one page2.php I get ('$'."_SESSION['word'] isn't set because you had never been at file one");
I tested all the below solutions but none of them worked = same result on page2.php.
My page1.php file.
<?php
session_start();
//if we got something through $_POST
if (isset($_POST["search"])) {
// include database connection
$connect = mysql_connect('localhost', 'root', 'NomiS123') or die(mysql_error());
mysql_select_db('workcard');
// sanitize user input
$word = mysql_real_escape_string($_POST["search"]);
$word = htmlentities($word);
// build search query to the database
$sql = ("SELECT task_id, task_date FROM customer JOIN task ON customer.id = task.customer_id WHERE mobil = $word ORDER BY task_date DESC LIMIT 0, 10");
// get results
$_SESSION['word'] = $word;
$results = mysql_query($sql);
if (mysql_num_rows($results)==0) {
$_SESSION['word'] = $word;
echo($_SESSION['word']. "<br>");
var_dump($_SESSION);
echo "<br>";
echo "link link <br>";
echo "new card <br>";
echo "New Search";
} else {
echo $word, " bla bla text <br> Create card <br>";
echo "Edit info on: ", $word, "<br>";
echo "New Search <br>";
while ($row = mysql_fetch_assoc($results)) {
echo '<pre>', print_r($row), '<pre>';
}
//$results->free();
}
}
// mysql_close($connect);
?>
My PAGE2.php file.
<?php
session_start();
if(isset($_SESSION['word'])) {
$word = $_SESSION['word'];
echo($word);
} else {
die('$'."_SESSION['word'] isn't set because you had never been at file one");
}
?>
I am going insane over this.
UPDATE - SOLVED
I tested all the below suggestions but none of them worked which was weird because I could set and echo out the sesson_id() on page1.php and page2.php, but on page2.php I got a different sesson_id(). I began to look into my MAMP sessions settings, but everything was correct set. The solution was "simply" to place the session_start(); on the very top on page2.php. And by the very top I mean before everything even the <!DOCTYPE html> etc. Solved + lesson learned :-)
First you must start the seesion via session_start(); directly after the opening PHP 'tag' (<?php session_start();... ?>)
Then you must save your variable to the session.
You can use $_SESSION['word'] = $word; for this purpose.
And in the other file you must also use session_start(); at the very first after the <?php 'tag'.
Then you could access the old variable via $word = $_SESSION['word'];.
You now can also use $word in the second file. But you only can use it if it's set (and you where at the first file before).
File one:
<?php
session_start();
if (isset($_POST["search"])) {
//include database connection
$word = mysql_real_escape_string($_POST["search"]);
$word = htmlentities($word);
$_SESSION['word'] = $word;
$sql = ("SELECT task_id, task_date FROM customer JOIN task ON customer.id = task.customer_id WHERE mobil = $word ORDER BY task_date DESC LIMIT 0, 10");
$results = mysql_query($sql);
if (mysql_num_rows($results)==0) {
echo $word, " text bla";
}else {
echo $word, " text bla bla";
while ($row = mysql_fetch_assoc($results)) {
echo '<pre>', print_r($row), '<pre>';
}
}
}?>
File two:
<?php
session_start();
if(isset($_SESSION['word'])) {
$word = $_SESSION['word'];
} else {
die('$'."_SESSION['word'] isn't set because you had never been at file one");
}
echo $word;
?>
Hope this helps ;)
To use PHP sessions you would do the below:
Initiate the session, session_start();
Note: session_start(); must be the first line of PHP in your file.
Create the session, $_SESSION['word'] = $word;
To access it on another page:
Initiate the session, session_start();
Access the session, $word = $_SESSION['word'];
session_start() means that you are using session variables, make sure it's at the top of the page. To make a session you do: $_SESSION['word'] = [some value]. This can be used between pages as long as you have session_start() at the top. Make sure to make sure it's set first, if it's not set initialize.
<?php session_start(); ?>
...
<?php
if ( isset($_SESSION['word']) ) {
$_SESSION['word'] = /* change existing session value */;
} else {
$_SESSION['word'] = /* new session value */;
}
?>
You first of all should start the session using the function 'session_start()'.
Place this in your index.php/bootstrap.php (a file that is always loaded when loading your website).
After that, you can use the '$_SESSION' global to set data.
//In your index.php/boostrap.php
session_start();
In the file you want to save the $word:
$_SESSION['myword'] = $word;
And from that point you can use this variable on another page.
//On another page, after the variable is being set
echo $_SESSION['myword'];
Be aware that when you are using shared webhosting, your session data is often stored in a global folder on the webserver and can be used by every website on that server. To prevent this, you should change you session save path using the 'session_save_path()' function or by creating you own session handler.
Call session_start(); at the beginning of the PHP file, and if anything is set in the $_SESSION super global array, you can re-access it.
If it isn't set you can set it with:
$_SESSION['a name']= 'some thing';
So for your example:
PHP FILE1
<?php
session_start();
$_SESSION['word'] = $_POST['word']
?>
PHP FILE2
<?php
session_start();
echo $_SESSION['word'];
?>
There are many many ways to accomplish this it all depends on how you want to use it. You can include your file in that file, you can use require or require_once, or yes you can use the session super global.
The $_SESSION super global will be accessible to all files within your application. The only thing you need to make sure you do is use session_start() on the page as the first thing on that page. If you use session_start() after any output has gone to teh browser it will not work. Usually you will want to run session_start() as the first line on your index.php file. Then you can use ...
<?php
if (isset($_POST["search"])) {
//include database connection
$word = mysql_real_escape_string($_POST["search"]);
$word = htmlentities($word);
$_SESSION['word'] = $word;
$sql = ("SELECT task_id, task_date FROM customer JOIN task ON customer.id = task.customer_id WHERE mobil = $word ORDER BY task_date DESC LIMIT 0, 10");
$results = mysql_query($sql);
if (mysql_num_rows($results)==0) {
echo $word, " text bla";
}else {
echo $word, " text bla bla";
while ($row = mysql_fetch_assoc($results)) {
echo '<pre>', print_r($row), '<pre>';
}
}
}?>
then in any page you want access to it just cal it up...
<?php
echo $_SESSION['word'];
Hope that helps
Related
After i submit a form and save the info to a database i use the header function to redirect to a more user friendly url but the variable $checkError is not saving, it gets reset after the header redirect. How can i save the variable even if the page gets refreshed?
if(isset($_GET['submit'])){
// get the post records <<
$id = '2';
$title = $_GET['title'];
$link = $_GET['link'];
// database connection
$con = mysqli_connect("localhost", "user", "password", "db_test");
$sql = "INSERT INTO test (id, title, link)
VALUES ($id, '$title', '$link')";
$rs = mysqli_query($con, $sql);
if($rs){
$checkError = '<div class="success">Success!</div>';
}else{
$checkError = '<div class="error">Not working!</div>';
}
mysqli_close($con);
//redirect to user friendly url
header("Location: /index.php?id={$id}");
}
You can write this to session data and recall it later, as one potential solution.
Modify/add in your example code block:
session_start();
if($rs){
$_SESSION['checkData'] = '<div class="success">Success!</div>';
}else{
$_SESSION['checkData'] = '<div class="error">Not working!</div>';
}
header("Location: /index.php?id={$id}");
And back on index.php, you would need to add/modify:
session_start();
if( isset( $_SESSION['checkData'] ) ){ // check whether it's set
echo $_SESSION['checkData']; // output variable
unset( $_SESSION['checkData']; // reset variable
}
You can use $GLOBALS OR $_SESSION as an array for $GLOBALS more details click here
you can use it as the below code in your header file
set value in $GLOBALS
$GLOBALS['checkError'] = '<div class="success">Success!</div>';
get value from $GLOBALS
echo $GLOBALS['checkError'];
Another way, very easy to implement is to skip $checkError variable and redirect user to a specific page:
// ...
$rs = mysqli_query($con, $sql);
mysqli_close($con);
$page = $rs ? 'success' : 'failure';
header("Location: /{$page}.php?id={$id}");
You have to store your data in cookies or sessions before the redirect.
A session is also used to store data, but I suggest you store data in cookies because the session stores data on the server-side, creating performance issues, whereas cookie stores data on the client-side.
You can check the critical difference of Cookie and Session
first.php
<?php
if($rs){
setcookie('checkError', '<div class="success">Success!</div>');
}else{
setcookie('checkError', '<div class="error">Not working!</div>');
}
?>
second.php
<?php
if(!isset($_COOKIE['checkError'])) {
echo $_COOKIE['checkError'];
}
?>
I hope this is helpful to you.
First let me explain my code.
It comprises of three php files.
inc_fn_header_and_menu.php, contains the HTML and CSS header details
and it initializes the session via session_start();
This is later included in project_status.php] .
In project_status.php] , I have included another file
project_status_app.php which contains a HTML form.
project_status.php:
<?php
include 'inc_fn_header_and_menu.php';
function includeFile($file,$variable) {
$var = $variable;
include($file);
}
if (isset($_GET['id']) && $_GET['id']!="") {
$pid = $_GET['id'];
$_SESSION['pidForApproval'] = $_GET['id'];
$query = 'SELECT * FROM `profile` WHERE pid ='.'\''.$pid.'\'';
$result=mysqli_query($db,$queryToRetrievePP) or die("There are no records to display ... \n".
mysqli_error());
foreach ($result as $row) {
$status = $row['status'];
?>
project_status_app.php
In project_status_app.php I am attempting to retrieve pidForApproval from the $_SESSION array.
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
include '../../inc/fastlogin.php';
$sql = "UPDATE pp SET customer_purchase_remarks ='{$_POST['remarkstxt']}' WHERE pp.pid='{$_SESSION['pidForApproval']}'";
$result = mysqli_query ( $fastdb, $sql ) ;
if (mysqli_affected_rows($fastdb) != 1) {
$_SESSION['err_cpa_rmks'] = "<p>Error while updating WHERE id='{$_SESSION['pidForApproval']}'</p>";
} else {
$_SESSION['suc_cpa_rmks'] = "<p>Records was updated successfully.</p>";
}
header ("location: project_status.php?id="$_SESSION['pidForApproval']);
exit();
}
?>
When I load project_status.php, project_status_app.php is supposed to display the form. Once the user fills in the form the and the submit button has been pressed, the UPDATE statement is supposed to run and then it is supposed to navigate back to project_status.php?id=FA142. But the update is failing and the when the project_status.php is loaded back, the url looks like this http://localhost/fast/project_status.php?id= . The id is empty. It is supposed to be something like this http://localhost/fast/project_status.php?id=FA142. With the id being populated at the
header ("location: project_status.php?id=".$_SESSION['pidForApproval']);
I suspected that my $_SESSION['pidForApproval'] is not being populated in project_status.php but I echoed back $_SESSION['pidForApproval'] in that file itself and I can see it is being populated. Hence, I suspect that the $_SESSION['pidForApproval'] is not being passed to project_status_app.php. I have already attempted to include session_start(); clause in project_status_app.php but that gives an error, stating that the session has already started, in inc_fn_header_and_menu.php. Can someone help me as to why the $_SESSION['pidForApproval'] is not being passed on to the project_status_app.php file. Thank you.
Requirement: use QRBOT-app to scan a barcode on a mobile and give the number scanned to the website.
Problem: I've a session open (1), from here I'm opening the app (see ScanBardcode.php), I scan and the app returns to the callback-URL including the required parameters. However I do expect it is re-using it's session, it creates a new one (2). Can someone help me? It does have both sessions active and both pages keep using it's own session. I can only test it on my cell phone, which I checked is using each time (the initiate-1 and the callback-2 the same browser)
What I tried already:
1. Pass the sessionID in the callback URL (QRBOT doesn't allow parameters)
2. Set Session.auto_start to 1
ScanBarcode.php
<?php
include_once('../../config.inc.php'); //contains DB connection details and other settings
include_once($fullurl . '../../admin/includes/sessie.inc.php'); //generates session
echo "SessionID=". session_id() . "!";
$_SESSION['BarCode'] = "VoorraadTellen";
echo "Wat gaan we doen? " . $_SESSION['BarCode'] . "</br></br>";
//URL to open qrbot.
echo "click"
?>
ScanBarcodeCallBack.php
<?php
$source = $_GET['x-source'];
$content = $_GET['content'];
$format = $_GET['format'];
include_once('../../config.inc.php');
include_once($fullurl . '../../admin/includes/sessie.inc.php');
echo "Wat gaan we doen? " . $_SESSION['BarCode'] . "</br></br>";
echo "SessionID=". session_id() . "!";
echo $source . $content . $format;
// HERE I WRITE TO THE DB.
?>
sessie.inc.php
<?php
$a = session_id();
if(empty($a))
{
session_start();
}
if(isset($_SESSION['sgebruiker']))
{
$now = time();
if($now - $_SESSION['stijd'] > $_SESSION['maxidle'])
{
$_SESSION = array();
session_destroy();
}
else
{
$_SESSION['stijd'] = $now;
}
}
elseif(isset($_COOKIE['login_cookie']))
{
//Check against db and set cookie.
}
?>
Adding screenshot when I add the sessionId in the URL as a parameter:
enter image description here
Update to ScanBarcode.php
`echo "click"
as far as i know you don't need the whole check with session_id(). PHP Documentation for session_start() says:
session_start() creates a session or resumes the current one based on a session identifier passed via a GET or POST request, or passed via a cookie.
this is also my experience. every time i used session_start() i just put it at the top of every file (or included it like you did)
When you pass the session ID in the URL, you need to use the parameter to set the session ID before calling session_start(). Change sessie.inc.php to:
<?php
if (isset($_GET['s'])) {
session_id($_GET['s']);
}
session_start();
if(isset($_SESSION['sgebruiker']))
{
$now = time();
if($now - $_SESSION['stijd'] > $_SESSION['maxidle'])
{
$_SESSION = array();
session_destroy();
}
else
{
$_SESSION['stijd'] = $now;
}
}
elseif(isset($_COOKIE['login_cookie']))
{
//Check against db and set cookie.
}
?>
Working with both #Tsai and #Barmar we found the solution.
We fixed it by:
- Encoding the URL by using urlencode-function
- Take the sessionID from URL and apply that using session_id-function before initiating the start_session (see also).
The cleaned up code below; hopefully someone would be able to use it also.
ScanBarcode.php
<?php
include_once('../../config.inc.php'); //contains DB connection details and other settings
include_once($fullurl . '../../admin/includes/sessie.inc.php'); //generates session
echo "SessionID=". session_id();
//URL to open qrbot.
$CallbackUrl = "http://ilonashairstyling.nl/2016UAT/module/Ilonas_admin/ScanBarcodeCallBack.php?s=" . htmlspecialchars(session_id());
echo "click"
?>
ScanBarcodeCallBack.php
<?php
$source = $_GET['x-source'];
$content = $_GET['content'];
$format = $_GET['format'];
include_once('../../config.inc.php');
ini_set("session.use_cookies",0);
ini_set("session.use_trans_sid",1);
session_id($_GET['s']);
//print_r($_SESSION); //You can test it with this code
//print(session_id()); //You can test it with this code
ini_set("session.use_cookies",1);
ini_set("session.use_trans_sid",0);
include_once($fullurl . '../../admin/includes/sessie.inc.php');
echo "Wat gaan we doen? " . $_SESSION['BarCode'] . "</br></br>";
echo "SessionID=". session_id() . "!";
echo $source . $content . $format;
// HERE I WRITE TO THE DB.
?>
sessie.inc.php is unchanged
i have in my sandbox many of function, some of the function are public, and other's i want them to be only for website member's.
this is an example for a function i want it to be for website members only
function get_page ($dbc, $pg) {
// the database connection, our query
$q = "SELECT * FROM pages WHERE name = '$pg' AND status = 1 LIMIT 1";
$r = mysqli_query($dbc, $q);
$page = mysqli_fetch_assoc($r);
echo '<div class=entry>';
echo '<h1>'.$page['title'].'</h1>';
echo '<div class="content_body">'.$page['body'].'</div>';
echo '</div>';
}
is there any way to do that?
"how i require session for a function"
Use the following, as an example:
if(!isset($_SESSION['session_name'])){ die(); }
and to include session_start(); inside all of the files used, and at the * top.
(* Depending on the condition).
For more information on sessions, visit the following:
http://www.php.net/manual/en/features.sessions.php
Footnotes:
Should you be faced with an headers already sent... error message later on, you can make use of ob_start(); placed above session_start().
For example:
<?php
ob_start();
session_start();
// code
Your question is really not clear.
You can use something like:
// Private function for members
function privateFunction($isMember=false){
if($isMember){
// DO your things
}
else{
callError();
}
}
Or make use of PHP Session variables directly into your function ?
I am trying to display random banner each time the user refresh the page. The problem I am facing is that I don't want the last banner to be displayed again. I there any other way to remember the last displayed one without using cookies or database implementation?
Cookie Implementation:
<?php
$randIndex = rand(1,6);
if(!isset($_COOKIE["lastDispalyed"])){
setcookie("lastDispalyed",$randIndex,time()+60*60*24);
}
else{
while($_COOKIE["lastDispalyed"] == $randIndex){
$randIndex = rand(1,6);
}
setcookie("lastDispalyed",$randIndex,time()+60*60*24);
} ?>
<img src="images/mainBanners/<?php echo $randIndex; ?>.JPG"/>
You could use a session variable:
<?php
session_start(); // <-- start session before outputting any HTML
$randIndex = rand(1,6);
if (!isset($_SESSION["lastDisplayed"])) {
$_SESSION["lastDisplayed"] = $randIndex;
} else {
while ($_SESSION["lastDisplayed"] == $randIndex) {
$randIndex = rand(1,6);
}
$_SESSION["lastDisplayed"] = $randIndex;
}
?>
Reference session_start().
Set up a session variable for the id or url of the banner:
$_SESSION['lastDisplayed'] = $id; //could be the id of the banner you are displaying, or the file's url, whatever you have access too
And then test for it when you go to display a new banner.