Using global variables in a PHP loaded through jQuery - php

I am using a jquery function to call a getdata.php file like this -
$("#tasks").load("getdata.php?choice=" + $("#projects").val());
The getdata.php echoes back results dynamically to the callee.
<?php //getdata.php
global $user_id; //<--These variables are defined in the callee file
global $con;
$choice=$_GET['choice'];
$query="SELECT task_id,title from tasks where user_id=$user_id AND proj_id=$choice";
$result=mysqli_query($con,$query) or die(mysqli_error($con));
if((mysqli_num_rows($res))!=0)
{
while (list($task_id, $title) = mysqli_fetch_row($result))
{
echo "<option value=$task_id>$title</option>";
}
}
else
{
echo "<option>No current Tasks</option>";
} ?>
Is there any way by which I can access the variables in the callee file from here. I tried using global as would normally be the case with included files but that's not working here.

You may consider using $_SESSION variables to set variables that are available to both your callee file and getdata.php.

Why not put them in the request ? `Something like
$("#tasks").load("getdata.php?choice=" + $("#projects").val() + "&user_id=" + user_id;
(How to pass PHP variables to js as already got a lot of answers on SO)
then in getdata.php
$user_id = $_GET['user_id'];
for the DB connection, you can create a kind of config file that you include on every script
config.php
function getDBConnection() {
blah...blah ...
return $con;
}
in getdata.php as in every script that need it :
require_once yourpath/config.php;
$con = getDBConnection();
For security reasons, if your config file contains passwords, login , etc ... put it outside
your web directory.

Related

How to access $msg["CE"] inside function in php?

As i have two files i have declared variable $msg["CE"] in config.php file and i am trying to access that variable in function of login.php page ...
config.php
<?php
$msg["CE"] = "connection_error";
?>
login.php
<?php
include_once "config.php";
function myf()
{
return $msg["CE"];
}
echo myf();
?>
Please help me how to access that msg["CE"]
The variable is available in the file login.php. However, because you attempt to access the variable from within a function (of which you don't supply the variable as a parameter), you need to use the global keyword.
function myf() {
global $msg;
return $msg["CE"];
}
You should take a look at the documentation for variable scope for PHP.

calling a php session variable from outer script

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().

Variables from Session Class not passing to new pages

I defined a session class,which uses values from the $_POST variable in an array called $sessionVars. When a user logs-in a new instance of the session class is created, a construct function sets session variables.I checked that this is working correctly.Problem: When i try to access those variables from a different page the session shows that its not started and those variables are undefined. Confused cause I thought $_SESSION being a super global means its accessible all the time(i.e scope doesn't matter) . I suspect im doing something wrong when I try to access the $_SESSION variables since they are in a class. I appreciate any help..thanks in advance.
class userSession{
public function __construct($sessionVars){
session_start();
$_SESSION['userEmail']=$sessionVars['user'];
$_SESSION['userID']=$sessionVars['userID'];
$_SESSION['userFolder']='users/user_'.$_SESSION['userID'];
}
/*just for housekeeping. not used in application*/
function showvars(){
echo $_SESSION['userEmail'].'<br><br>';
echo $_SESSION['userID'].'<br><br>';
echo $_SESSION['userFolder'];
$sessionID=session_id();
echo '<br><br>'.$sessionID;
}
}//**END USER SESSION
/*This is the login script that calls the session*/
include 'library.php';
$show=new render;
$show->index();
if(!isset($_POST['login']) ){
$show->usrLogin();
} else{
if(!empty($_POST['email'])){
$postVars=array('user'=>$_POST['email'],'pass'=>$_POST['password']);
$user=new user();
$data=$user->loginUser($postVars);
$currSession=new userSession($data);
}else{
die('No data in POST variable');}
}
/*file upload that needs the session[userFolder] variable*/
function file_upload(){
$userFolder=&$_SESSION['userFolder'];
echo '<hr>userFolder is : '.$userFolder;
function do_upload(){
if(!empty( $_FILES) ){
echo $userFolder.'<hr>';
$tmpFldr=$_FILES['upFile']['tmp_name'];
$fileDest=$userFolder.'/'.$_FILES['upFile']['name'];
if(move_uploaded_file($tmpFldr,$fileDest)){
echo 'file(s) uploaded successfully';
}
else{
echo 'Your file failed to upload<br><br>';
}
return $fileDest; //returns path to uploaded file
} else{die( 'Nothing to upload');}
}//END FUNCTION DO_UPLOAD,
/*Perform upload return file location*/
$fileLoc=do_upload();
return $fileLoc;
}
You need to instantiate an object of this class on every page that uses the session (or start the session manually). Also, you'll not want that constructor, instead some other way of setting vars. This is just for illustration of how it works with your current code, there are much better approaches:
class userSession {
public function __construct(){
session_start();
}
function set_login_vars($sessionVars){
$_SESSION['userEmail']=$sessionVars['user'];
$_SESSION['userID']=$sessionVars['userID'];
$_SESSION['userFolder']='users/user_'.$_SESSION['userID'];
}
}
//page1.php
$session = new userSession;
$session->set_login_vars($loginVars);
//page2.php
//you need to start the session, either with the class
$session = new userSession;
//or session_start();
print_r($_SESSION);

In my PHP + Ajax code, why does $_SESSION disappear during execution?

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.

PHP session being lost

I'm trying to implement and authentication system with jQuery and PHP. All the php work is made in the controller and datahandler class. There is no php code inside the .html files, all the values in .html files are rendered via jQuery that request the data from php server. So what I'm trying to do is:
When user clicks the login button, the jQuery makes a call to the authenticate() method in my controller class, it checks if the user is correct and stuff, and if it is, start the session and set the user_id on the session so I can access it later, and returns the userId to the jQuery client again.
After that, if everything is fine, in jQuery I redirect it to the html file. On the html file I call a jQuery from the <script> tag that will handle other permissions. But this jQuery will access the method getPermissionString (from the same class of authenticate() method mentioned before), and it will need to get the session value set in authenticate method.
The Problem:
When I try to get the session value inside getPermissionString() it says:
Notice: Undefined variable: _SESSION
I've tried to check if the session is registered in the second method, but looks like it's not. Here is my PHP code.
Any idea? Thanks.
public function authenticate($login, $password)
{
$result = $this->userDataHandler->authenticateUser($login, $password);
if(is_numeric($result) && $result != 0)
{
session_start();
$_SESSION["uid"] = $result;
if(isset($_SESSION["uid"]))
{
echo "registered";
$userId = $_SESSION["uid"];
}
else
{
echo "not registered";
}
echo $result;
}
else
{
echo 0;
}
}
public function getPermissionString()
{
if(isset($_SESSION["uid"]))
{
echo "registered";
$userId = $_SESSION["uid"];
}
else
{
echo "not registered";
}
}
Before you can access $_SESSION in the second function you need to ensure that the program has called session_start() beforehand. The global variable is only populated when the session has been activated. If you never remember to start a session before using it then you can change the php.ini variable below:
[session]
session.auto_start = 1
Further, you said that you're using a class for your code. In this case you can also autos tart your session each time the class in created by using magic methods:
class auth {
function __construct() {
session_start();
}
function yourfunction() {
...
}
function yoursecondfunction(){
...
}
}
If you don't have session.auto_start enabled, and authenticate and getPermissionString are called on two different requests, you need to call session_start() in each function.
If you need more information on how the session ID is passed, just read Passing the Session ID
You should not use that function if session is not started. So throw an exception:
public function getPermissionString()
{
if (session_status() !== PHP_SESSION_ACTIVE)
{
throw new Exception('No active session found.');
}
if(isset($_SESSION["uid"]))
{
echo "registered";
$userId = $_SESSION["uid"];
}
else
{
echo "not registered";
}
}
This ensures the pre-conditions of your functions are checked inside the function so you don't need to check it each time before calling the function.
You will now see an exception if you wrongly use that function and it will give you a backtrace so you can more easily analyze your code.
For php sessions to work you have to call session_start() every time you script is requested by the browser.

Categories