1

I little while back I posted this question. I have updated that question with the AJAX script that worked for about 1 week. Basically I can use session_start() from the AJAX script, and then I could access the session variables that I needed.

It is really strange, but I came in after the weekend, and this morning this script does not work anymore. It is very simple, here:

<?php

session_start();

$ajax_connection = mysql_connect('10.X.X.X',$_SESSION['username'],$_SESSION['password']);

$result_set = array();

while ($result_set[] = mysql_fetch_assoc($results)){
    // do nothing
}

echo json_encode($results);

?>

Last week this worked flawlessly, and now in my error log i get the Undefined index: username and Undefined index: password warnings. And of course the MySQL connection is not established. So this script is not running the same session as the original connection. I used error_log(session_id()) to check the IDs of the parent page and the AJAX script, and sure enough they are different. When i reload the page and try every again, the IDs stay the same for the page and the AJAX script respectively, but they should be the same ID, not 2 different ones.

Anyway, does anyone have any idea why this wouldn't be working anymore, after working well for over a week?

Community
  • 1
  • 1
jeffery_the_wind
  • 17,048
  • 34
  • 98
  • 160
  • Why would you store mysql connection info in a session variable? – N.B. Mar 26 '12 at 12:44
  • @N.B. Well because it works. How else would I get the connection info to the AJAX script? – jeffery_the_wind Mar 26 '12 at 12:47
  • 1
    What prevents you from including a file that holds db credentials into your AJAX script? For 10 000 users, you'd fill in sessions with the same information. It's not really feasible, is it? It also, apparently, produces problems for you. Therefore, it implies a bad design decision. I could go on how it's unsafe on shared hosting etc. but I won't, it's simply bad design decision to have db info stored in session. – N.B. Mar 26 '12 at 13:08
  • @N.B. Thanks for the help! To include a PHP file in an AJAX script you have to store the file in the web directory, and therefore web users have access to the location. I thought this was unsafe?? I would rather store this file with DB credentials outside of the web directory. I am under the impression that AJAX scripts cannot access files outside of the web directory. – jeffery_the_wind Mar 26 '12 at 13:26
  • Even if the file with the db credentials WAS available via HTTP, what does it matter? If you are not echoing the db information, it's useless to the person accessing it. They'll receive parsed PHP output. So if a file is full of variables or constants that aren't being outputted, it's not unsafe. However, as you said, you'd want to keep this file below the DocumentRoot. Nothing prevents you to include it into your AJAX php script tho. – N.B. Mar 26 '12 at 13:58

2 Answers2

4

Here's the kind of Class you can use. It is in singleton to make sure you instanciate it only once. Instanciate it with

$db = Db::getInstance();

then

$db->connect();

this is a much safer way to use Dbase connections (Note that I used PDO, but if you really need to keep using mysql_ functions, you can still modify it).

class Db {

    private static $instance = null;
    private $db = null;
    private $host = '';
    private $name = '';
    private $username = '';
    private $password = '';

    private function __construct() {
        $this->host = 'yourHost';
        $this->name = 'yourDbName';
        $this->username = 'yourUserName';
        $this->password = 'youPassword';
    }

    public static function getInstance() {
        if(is_null(self::$instance)) {
            self::$instance = new Db();
        }
        return self::$instance;
     }

     public function connect() {
        try {
            $this->db = new PDO('mysql:host=' . $this->host . ';dbname=' . $this->name, $this->username, $this->password);
        } catch(Exception $e) {
            throw new Exception('Connection error: either the database is unavailable or connection infos are not valid. Please contact the webmaster.');
        }
    }
}
Ronan
  • 1,482
  • 11
  • 11
0

Not sure if this will solve your problem, but you should add the following anyway at the top of your php script called in Ajax:

header('Cache-control: no-cache, must-revalidate');
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');

It solved some problems I use to have with sessions and Ajax.

Ronan
  • 1,482
  • 11
  • 11
  • Must be added after the session_start() though – Ronan Mar 26 '12 at 12:44
  • What do you get whith var_dump($_SESSION) ? I guess it's empty. You must have modified some of your code since last time it worked. – Ronan Mar 26 '12 at 13:01
  • 1
    Anyway, I would rather make a separated file with your dbase connection, or even better, a Dbase class that u can call, rather than storing your database connection infos in Session variables, which is not safe at all... – Ronan Mar 26 '12 at 13:09
  • thanks for the info, I am using this method now because I thought it was better than how I was passing connection information previously. So i guess this is not very safe like you said. I will look into creating this class. Any suggestions where to starting learning about this? – jeffery_the_wind Mar 26 '12 at 13:23
  • I'll post you an example in another answer – Ronan Mar 26 '12 at 13:26