Here I have foo.php that runs in the background without any HTML, it's never visited by the user.
<?php
if (isset($_GET['data'])) {
$bar = $_GET['data']; // data comes from a html form on another page.
$str = strtoupper($bar);
echo $str;
}
This is just a simple example, but let's say I wan't to pass $str to another file, script.php for extra processing.
What's the best method for this? The only way I can think of doing this is by posting it into a database and then retrieving it inside of script.php ?
Using Session:
//On page 1
$_SESSION['varname'] = $bar;
//On page 2
$var_value = $_SESSION['varname'];
Remember to run the session_start() statement on both these pages before you try to access the $_SESSION array, and also before any output is sent to the browser.
Cookie:
//One page 1
$_COOKIE['varname'] = $bar;
//On page 2
$var_value = $_COOKIE['varname'];
As # Rizier123 mentioned "Cookies can be deleted or disabled! Wouldn't do that if the variable is very important ". So better avoid this approach.
Something like this is probebly a easy way to do it:
You can make a function out of the if statement
foo.php:
<?php
function fooFunction() {
if (isset($_GET['data'])) {
$bar = $_GET['data']; // data comes from a html form on another page.
$str = strtoupper($bar);
return $str;
}
}
?>
script.php:
<?php
require_once 'foo.php';
?>
OR if you already have a session you can insert it into the session array like this:
foo.php:
<?php
session_start();
if (isset($_GET['data'])) {
$bar = $_GET['data']; // data comes from a html form on another page.
$str = strtoupper($bar);
$_SESSION['str'] = $str;
}
?>
script.php:
<?php
session_start();
echo $_SESSION['str'];
?>
If you include (or require) a php script X into another php script Y, Y will have acces to all X datas and functions. You could also use sessions like #sanki commented.
Here are some links that could be useful for you:
include
require
Sessions
Pass data as GET parameter
<?php
if (isset($_GET['data'])) {
$bar = $_GET['data']; // data comes from a html form on another page.
$str = strtoupper($bar);
echo $str;
header("Location: script.php?data={$str}");
}
?>
But this will make script.php run immediately after current file.
you can do
`php script.php $str`;
to invoke script.php with your string as a command line argument.
http://php.net/manual/en/language.operators.execution.php
Related
I have tried passing sensitive information from 1 page to the next using Cookies and PHP Sessions but still no luck. This works fine in all browsers I have tested except Opera Mini. I also found this: http://caniuse.com/#search=cookie
This is how I have it currently setup.
page1.php:
<?php
session_start();
$time = time();
$key = '';
$hash = md5($key . $time);
$_SESSION['inno'] = '';
header("Location: page2.php". $hash);
exit;
?>
page2.php:
<?php
session_start();
if (isset( $_SESSION['inno'])) {
include("../global/header.php");
include("../global/content.php");
}
session_destroy();
?>
The content of the page is the sensitive information, So that is why it goes from page1.php to page2.php.
Is there some kind of workaround for this if passing information this way isn't supported in Opera Mini?
Use classes for reusable resources, they are less messy.
Looks like you forgot to assign data, so
Here is the promising structure:
index.php
<?php
include_once 'session.php';
$my_session = new session_helper;
//SET YOUR SESSION VARIABLES
if($my_session->get_session_data('username') == null){
$sessionData = array(
'username'=>'me',
'logged'=>true,
'password'=>md5('password')
);
$my_session->set_session_data($sessionData);
}
?>
View my session
view_session.php
<?php
include_once 'session.php';
$my_session = new session_helper;
?>
<!--GET YOUR SESSION VARIABLES-->
<p>Username: <?php echo $my_session->get_session_data('username'); ?></p>
<p>Logged: <?php echo $my_session->get_session_data('logged'); ?></p>
<p>Password: <?php echo $my_session->get_session_data('password'); ?></p>
<p> </p>
<?php $my_session->debug_session(); ?>
session.php to get rid of headaches
<?php
//MANAGE YOUR SESSION
class session_helper
{
//Start session when class instance created
function __construct()
{
session_start();
}
//Session data set using an array to easily add multiple values e.g. on login page
function set_session_data($sessionData)
{
forEach($sessionData as $key => $value){//Go through each key
$_SESSION[$key] = $value;//And assign it to session
}
}
function get_session_data($session_data_key)
{
return $_SESSION[$session_data_key];//Call this to get your values
}
function debug_session()
{
print_r($_SESSION); //Check what session contains if something is wrong
}
function close_session()
{
session_destroy(); //Good to use for fresh start/logout.
}
}
?>
session.php manages sessions. Accessing directly will output an empty page.
index.php uses a condition to set the variables. You don't need to rework data everytime when you have it.
view_session.php has all the info regarding the session.
Best practice of retrieving info is storing secure/encrypted primary keys of the database, then use them to retrieve everything else from the database, e.g. by user ID get the e-mail, profile creation time, name, surname etc.
i have a problem calling a session variable from another script. can anybody help me on this matter.
Below is the script that i create the session and store the time in a session variable.
<?php
session_start();
$orgtimestamp = date("Y-m-d h:i:sa");
$_SESSION['orgtimestamp'] = $orgtimestamp;
?>
Here is the script that i try to access this session variable from a function of it. till now nothing worked
<?php
include '../../mydomain/myscript.php';
class survey_Tracksciprt
{
public static function timeofclick(){
session_start();
$time_org = $_SESSION['orgtimestamp'];
echo $time_org;
}
}
this hasnt worked upto now, nothing prints...can anybody give tips to sought this out and its compulsory to have this function timeofclick
You're not creating your class on your second file add:
//I don't know what this does but if it already starts a session remove the session start inside the class.
include '../../mydomain/myscript.php';
$survey = new survey_Tracksciprt();
$survey::timeofclick();
class survey_Tracksciprt
{
public static function timeofclick(){
session_start();
$time_org = $_SESSION['orgtimestamp'];
echo $time_org;
}
}
I also advice putting session_start at the top of your file.
<?php
session_start();
include '../../mydomain/myscript.php';
class survey_Tracksciprt
{
public static function timeofclick(){
$time_org = $_SESSION['orgtimestamp'];
echo $time_org;
}
}
Always use the session_start(); at the top line of the page.
First, you need an init-session.php file, containing:
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
Second, you need to include this file at the start of your loader/layout (whatever you have there), so no operation will be executed before you initialize your session.
Third, you should initialize $orgtimestamp like this:
<?php
$orgtimestamp = date("Y-m-d h:i:sa");
$_SESSION['orgtimestamp'] = $orgtimestamp;
?>
Fourth, you need to call survey_Tracksciprt::timeofclick().
Im using two pages first page s getting values from url and its displaying some content. I included first page in second page but the first page should not be displayed but i have to access the values in second page which is used in first page..
The coding for first page
first.php
In utl the value is passed as first.php?Logid=7773&shiftdate=2013-01-04&shiftid=146&pshift=1&tsid=1&dctype=timebased
<?php
$Logid=$_GET['Logid'];
$ShiftDate=$_GET['shiftdate'];
$ShiftID=$_GET['shiftid'];
$PShift=$_GET['pshift'];
$TsID=$_GET['tsid'];
$DcType=$_GET['dctype'];
// below this some process is carried out
sec.php
<?php
ob_start();
include('first.php');
ob_end_clean();
echo $Logid;
echo $ShiftDate;
echo $ShiftID;
echo $PShift;
echo $TsID;
echo $DcType;
?>
The value is not displayed in second page..
Say how i can access the values in second page .
Pls help me
Thank u !!!
The best way to access data in PHP "generally" (except in small, insubstantial snippets) is through encapsulation. You could put those values into an object. Then, you will be able to access them on sec.php:
first.php:
<?php
class pageData {
public $Logid;
public $ShiftDate;
public $ShiftID;
public $PShift;
public $TsID;
public $DcType;
public function __construct() {
$this->Logid = $_GET['Logid'];
$this->ShiftDate = $_GET['shiftdate'];
$this->ShiftID = $_GET['shiftid'];
$this->PShift = $_GET['pshift'];
$this->TsID = $_GET['tsid'];
$this->DcType = $_GET['dctype'];
}
}
$pageData = new pageData();
?>
sec.php:
<?php
include('first.php');
echo $pageData->Logid;
// ...
echo $pageData->DcType;
?>
Remove ob_end_clean(); and see that will solve it.
ob_end_clean — Clean (erase) the output buffer and turn off output buffering
More
sec.php
<?php
error_reporting(E_ALL);
ini_set("display_errors", 1);
include("first.php");
?>
try above code and see if its return any error.
You are trying to pass the values which are set by GET in the page to the second page, am I right? How about trying to use sessions instead.
You can start a session and define values which will be stored as long as the browser is open and the session is still alive. So:
first.php
<?php
// Starting the session
session_start();
$_SESSION['Logid'] = $_GET['Logid'];
$_SESSION['ShiftDate'] = $_GET['shiftdate'];
$_SESSION['ShiftID'] = $_GET['shiftid'];
$_SESSION['PShift'] = $_GET['pshift'];
$_SESSION['TsID'] = $_GET['tsid'];
$_SESSION['DcType'] = $_GET['dctype'];
?>
sec.php
<?php
echo $_SESSION['Logid'];
echo $_SESSION['ShiftDate'];
echo $_SESSION['ShiftID'];
echo $_SESSION['PShift'];
echo $_SESSION['TsID'];
echo $_SESSION['DcType'];
?>
and use
session_unset();
session_destroy();
to kill the session and destroy the data in the global variable ($_SESSION). If you want to be extra cautious you can use:
session_unset();
session_destroy();
session_write_close();
setcookie(session_name(),'',0,'/');
session_regenerate_id(true);
to make sure everything is really destroyed. A bit of an overkill if you'd ask me but use if necessary.
Hope it helps!
I'm working on a simple Ajax exercise where I separate the query, the Ajax, and the url that Ajax calls. In short, I run a query in one page and attach the resulting array to $_SESSION, then I display some html and the Ajax code calls a third page to get the elements from the array one by one via a counter attached to the $_GET superglobal. The three files are linked by require_once().
When the page loads initially, all is as expected. The $_SESSION contains the entire array pulled from MySQL, and the $_GET is null.
Once I click on the button to execute the Ajax code, the $_GET value changes and receives the value of the counter, as expected.
However, $_SESSION ceases to exist. The var_dump now returns null and I get an error Notice: Undefined variable: _SESSION in C:\wamp\www\.....\ajax.php. I don't understand why that is.
Here is my code. First, index.php :
<?php
session_start();
$dbhost = "localhost";
$dbuser = "admin";
$dbpass = "XXXXXXX";
$dbname = "test";
mysql_connect($dbhost, $dbuser, $dbpass);
mysql_select_db($dbname) or die(mysql_error());
$query = "SELECT ae_name FROM ajax_example";
$qry_result = mysql_query($query) or die(mysql_error());
$result;
while($row = mysql_fetch_array($qry_result,MYSQL_ASSOC)){
$result[]=$row;
}
$_SESSION['array']=$result;
require_once ("viewUsers.php");
require_once ("ajax.php");
?>
Then the html and ajax code in viewUsers.php:
<html>
<body>
<script type="text/javascript">
<!--
function createRequest() {
try {
request = new XMLHttpRequest();
} catch (tryMS) {
try {
request = new ActiveXObject("Msxml2.XMLHTTP");
} catch (otherMS) {
try {
request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (failed) {
request = null;
}
}
}
return request;
}
var indx=0;
function calcIndex(){
return indx++;
}
function ajax(){
ajaxRequest = createRequest();
var index=calcIndex();
var url="ajax.php?index=" + index;
ajaxRequest.open("GET",url, true);
ajaxRequest.onreadystatechange = display;
ajaxRequest.send(null);
}
function display(){
if(ajaxRequest.readyState == 4){
var ajaxDisplay = document.getElementById('ajaxDiv');
ajaxDisplay.innerHTML = ajaxRequest.responseText;
}
}
//-->
</script>
<form name='myForm'>
<input type='button' onclick='ajax()' value='Show next name' />
</form>
<div id='ajaxDiv'>Your result will be displayed here</div>
</body>
</html>
And then the PHP that receives the array from $_SESSION and (should) return the next item based on the value of $_GET['index']. The file is ajax.php.
<?php
var_dump('Get value in ajax.php',$_GET); // The values are as expected
var_dump('Session value in ajax.php',$_SESSION); // This global cease to exist after I click the button
if(isset($_SESSION['array'])){
$array=$_SESSION['array'];
$cnt=count($array);
$index=null;
if(isset($_GET['index'])){
$index=$_GET['index'];
if($index>=$cnt){
$str="And that's it....";
}else{
$str="The next name is ".$array[$index]['ae_name'];
}
echo $str;
}
}
?>
The problem is that session in ajax.php is not started / resumed.
When you call index.php, it is:
index.php -> .. -> ajax.php (SESSION EXISTS (session_start() called in index.php))
then you request your ajax.php through ajax:
html -> ajax.php (SESSION DOESNT EXISTS (session_start() was not ever called as we dont come from index.php))
You just need to initialize / resume session in your ajax.php, but you have to check if its not already initialized from index.php. Put this chunk of code into your ajax.php file:
if(!session_id()) // check if we have session_start() called
session_start(); // if not, call it
ajax.php needs a session_start() at the beginning, otherwise, when you call it standalone via ajax, you won't have a session, hence no $_SESSION var.
From PHP DOC
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.
When session_start() is called or when a session auto starts, PHP will call the open and read session save handlers. These will either be a built-in save handler provided by default or by PHP extensions (such as SQLite or Memcached); or can be custom handler as defined by session_set_save_handler(). The read callback will retrieve any existing session data (stored in a special serialized format) and will be unserialized and used to automatically populate the $_SESSION superglobal when the read callback returns the saved session data back to PHP session handling.
Without calling session_start definitely $_SESSION would not be populated accordingly why advice is to always call session_start if you in your script if you are going to be using sessions .
Quick Few steps
Remove require_once ("ajax.php"); from index.php its not needed there
PHP CODE
$_SESSION['array']=$result;
require_once ("viewUsers.php");
require_once ("ajax.php"); //<------ remove this
Add session_start(); to ajax.php
From PHP DOC on mysql_query
Use of this extension is discouraged. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide and related FAQ for more information. Alternatives to this function include:mysqli_query()
PDO::query()
Your index.php should finally look like this
session_start();
// Put this in config file
$dbhost = "localhost";
$dbuser = "admin";
$dbpass = "XXXXXXX";
$dbname = "test";
$array = array();
//Start DB Connection
$mysqli = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
$query = "SELECT ae_name FROM ajax_example";
$result = $mysqli->query($query);
//Get Information
while ( $row = $result->fetch_assoc() ) {
$array[] = $row;
}
$result->free();
$mysqli->close();
// Add Info to session
$_SESSION['array'] = $array;
require_once ("viewUsers.php");
#JDelage,
Your question has a very simple solution - Just add session_start() at the top of the ajax.php file.
However, the major problem here is lack of organization in your code structure.
Session / Configurations are preloaded in most of the actions. And these are included in a file which is loaded in every call.
Your file ajax.php apparently seems to be an independent file, however is dependent upon index.php, meanwhile index.php depends on ajax.php (require_once).
So the best work around for your type of code is as follows.
bootstrap.php
<?php
// just to check to prevent overwriting of your configs / preloads.
if(!defined("INITIALIZED")){
session_start();
//.. some other basic settings if you require
define("INITIALIZED", 1);
}
?>
index.php
<?php
include_once "bootstrap.php";
// .. your code
require_once("viewUsers.php");
require_once("ajax.php");
ajax.php (Yes you need session_start() here, because when you make asynchronous request to this file, it acts as an independent request regardless of index.php. AJAX call is a client side asynchronous request, not a server side. )
<?php
include_once 'bootstrap.php';
// .. your code
viewUsers.php
// since your viewUsers.php file isn't an independent file and is included by index.php only, you can simply add this line at the top to prevent direct invocation of the file.
<?php
if(!defined("INITIALIZED")){die();}
PS:
There isn't an unique solution. An approach is what you have to decide. Your approach is an approach, which isn't any kind of approach. Rest is fine.
I hope I have answered your queries.
Regards,
You have a number of if conditions that are making it difficult for you to see errors. Add some echo statements at those locations to see what is happening in your program flow. It will be easier to troubleshoot. For example:
<?php
//session_start();
echo 'You sent ' . $_GET['index'] . '<br>'; //Ensure index value arriving
if(isset($_SESSION['array'])){
$array=$_SESSION['array'];
$cnt=count($array);
$index=null;
if(isset($_GET['index'])){
$index=$_GET['index'];
echo 'Got to here<br>'; //Another checkpoint - send something back
if($index>=$cnt){
$str="And that's it....";
}else{
$str="The next name is ".$array[$index]['ae_name'];
}
echo $str;
}else{
echo 'GET var "index" was not set<br>';
}
}else{
echo 'SESSION var "array" was not set<br>';
}
?>
Of course, you will remove those echo statements as you fix your code... They are only temporary, for debugging.
I faced similar issue. I found that in one of the ajax call I forgot to call session_start().
when I ensured that I session_start() is always called in all the php code that are called thru ajax, then this problem went away.
When using AJAX sometimes the session is not carried over. In your AJAX post/get include the sessionID. Then on the receiving end do something like:
$sid = ($_POST['sid']) ? $_POST['sid'] : ''; //Check for posted session ID
session_start($sid); //Start session using posted ID or start new session
*Old-school method, yes, but tried and true.
I'm trying to implement caching for a PHP script I'm writing, but I keep running into the following problem. I want the script to be included in other PHP pages, but when I try to pass the cached file and exit the embedded script it exits both the script and the parent page, but doesn't parse the rest of the code on the parent page. See the code below for an example.
index.php
<?php
echo "Hello World!<br />";
include("file2.php");
echo "This line will not be printed";
?>
file2.php
<?php
$whatever = true;
if ($whatever == true) {
echo "file2.php has been included<br />";
exit; // This stops both scripts from further execution
}
// Additional code here
?>
If the above index.php is executed you get the following output:
Hello World!
file2.php has been included
However, I'm trying to get it to look like this:
Hello World!
file2.php has been included
This line will not be printed
Use return; instead of exit; in the included file - this will only halt execution of that script.
Note that you an also use this to return a value to the parent script e.g.
file1.php
<?php
echo 'parent script';
$val = include('file2.php'); //$val will equal 'value'
echo 'This will be printed';
file2.php
<?php
echo 'child script';
return 'value';
Just wrap the "additional code here" in an else statement?
<?php
$whatever = true;
if ($whatever == true) {
echo "file2.php has been included<br />";
} else {
// Additional code here
}
?>
Otherwise I'm not sure what you're getting at. The exit command always terminates the current execution in whole - not just execution of the current file (for which, there is no command)
EDIT
Thanks to comments and posts by PHLAK, tomhaigh, MichaelM, and Mario, I myself learned something today - that you CAN indeed terminate the execution of a single included file w/the return command. Thanks, guys!
I personally try to avoid if-else conditions where possible and use (not sure if there's a coined term for it but) early-exit intercepting conditions.
index.php
<?php
echo 'header';
include 'content.php';
echo 'footer';
?>
content.php
<?php
if ($cached)
{
echo cached_version();
return; // return is not just for functions, in php...
}
//proceed with echoing whatever you want to echo if there's no cached version.
...
...
?>
Why not encapsulate the contents of file2.php into a function. That way you can return from the function when you need to, and the rest of the execution will not halt. eg:
file2.php
<?php
// this function contains the same code that was originally in file2.php
function exe()
{
$whatever = true;
if ($whatever)
{
echo "file2.php has been included <br />";
// instead of exit, we just return from the function
return;
}
}
// we call the function automatically when the file is included
exe();
?>
Leave index.php exactly as it is and you should see the output you are trying to achieve.