0

I made a small test script while trying to solve issues with sessions going missing after switching to PDO.

In testing the script I am finding that every other load of the page gets

Access denied for user 'DB_USER'@'[ip snipped]' (using password: YES)

So DB_USER is uninterpolated for every second load. The first load of the page gets a successful connection.

Why is that? PHP version is 5.4.42.

<? session_start(); define("DB_HOST", "myserver"); define("DB_USER", "myuser"); define("DB_PASS", "mypass"); define("DB_NAME", "mydb"); class DB { protected $link; public function __construct() { $this->dsn = 'mysql:host=' . DB_HOST . ';dbname=' . DB_NAME . ';charset=utf8'; $this->connect(); } private function connect() { $options = array( PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION ); $this->pdo = new PDO($this->dsn, DB_USER, DB_PASS, $options); } public function __sleep() { return array('dsn', 'username', 'password'); } public function __wakeup() { $this->connect(); } } $db = new DB; 
2
  • The real question is why are you serializing your DB object at all? Commented Dec 10, 2015 at 23:14
  • @Phil though I am not doing this in this script in my main script I store a User object which inherits from class DB. As far as I know I do not serialize the DB object otherwise. Commented Dec 10, 2015 at 23:18

1 Answer 1

1
public function __wakeup() { $this->dsn = 'mysql:host=' . DB_HOST . ';dbname=' . DB_NAME . ';charset=utf8'; $this->connect(); } 

will fix this. But the main problem is that you havent define variables like

protected $dsn; 

So the wakup fails.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.