0

I have a PHP file (approvals.php) that only gets executed on an AJAX call. It has a postgresql query that searches a table and uses a customer id, which is set as a session variable. Problem is, it seems I can't access this session variable in this file. My query is like:

$query = "SELECT merchant_id FROM ndovu_merchant_users WHERE customer_id={$_SESSION['customer_id']}";
$result = pg_query($query);

I have tried to echo the session variable $_SESSION['customer_id'] but nothing. However on passing a fixed value to the query, it returns a result.

Denny
  • 1,739
  • 3
  • 20
  • 39

3 Answers3

1

In your case, i would have checked if the session is set in the first place.

//this should be put at the header of the page
session_start();

  if(isset($_SESSION['customer_id']) && !empty($_SESSION['customer_id'])){
        echo $_SESSION['customer_id'];
    }else{
        echo 'session is not set';
    }
Mubo
  • 1,078
  • 8
  • 16
0

You need to place session_start(); above the code section where you use it; the top of the page is usually the best place to place it.

Also, it should be noted; you have what is potentially a large security flaw here, by passing in unescaped data.

You should look into using prepared statements if possible; or at least escape your inputs.

Bowersbros
  • 3,438
  • 2
  • 18
  • 24
  • Why escape? We know an `id` is always numerical, *right*? `ctype_digit()` or a regular expression match `^[0-9]+$`. – ʰᵈˑ Oct 10 '14 at 08:57
  • That would work perfectly fine yes. In my mind, typecasting, or checking for type is a form of escaping anyway. But, I still stand by what I said about prepared statements; using them would be the best still. I believe that MySQL (and other databases most likely too), cache prepared statements better than normal queries – Bowersbros Oct 10 '14 at 09:13
0

The user session is not accesed when the script is called by an ajax request. The session token wich php requires to obtain the session data is stored in the client side(user) inside a session cookie. You can read more here https://stackoverflow.com/a/1535712/3922692

Just pass the user id with GET or POST in the ajax request.

There is not enough code presented but if you realy need to get the id from the session you can use an iframe (which is not recommended), process fetch data server side and output it in the iframe.

Community
  • 1
  • 1
ehwas
  • 248
  • 1
  • 9