unexpected Inifite loop using switch and some function - php

Basically I have a piece of code that has a switch statement and some functions. It goes to the switch statement using a parameter given by the browser "?step=X" and then selects the appropriate function.
My problem is even when at the end of each function I specify to go to the next switch statement it never does it and somehow it becomes an infinite loop of the function that I selected with the "step=x" in the browser...
Why is getting stuck in 1 function and not iterating through them? (the code for the step is highlighted at the end of the script)
I get the output in the browser of any selected function. so It enters the switch and the selected function... but then it becomes and infinite loop because in the broswer i get 300 of the same echo statements. It is never able to iterate through them or exit the selected function.
<?php
//DB Config File
$dbFile = 'dbconfig.php';
$username = $_GET['username'];
$password = $_GET['password'];
$server = $_GET['server'];
$dbname = $_GET['dbname'];
$step = $_GET["step"];
function createfile ($dbFile) {
//Creates File and populates it.
$fOpen = fopen($dbFile, 'w');
global $username, $password, $server, $dbname;
$fString .= "<?php\n";
$fString .= "// Database Constants\n";
$fString .= "\$DB_SERVER =" . "\"" . $server . "\";\n";
$fString .= "\$DB_USER =" . "\"" . $username . "\";\n";
$fString .= "\$DB_PASS =" . "\"" . $password . "\";\n";
$fString .= "\$DB_NAME =". "\"" . $dbname . "\";\n";
$fString .= "?>";
fwrite($fOpen, $fString);
fclose($fOpen);
return true;
}
try {
$db = new PDO ('mysql:host=' .$server.';dbname='.$dbname,$username,$password);
if ($db) { //if succesful at connecting to the DB
if (file_exists($dbFile)){
if (is_readable($dbFile) && is_writable($dbFile)){
//Creates File, populates it and redirects the user
if (createfile($dbFile)) {
echo "nelxt";
stepFunction($step);
exit ();
}
} else {
echo "The file {$dbFile} cannot be accessed. Please configure the file manualy or grant Write and Read permission."; }
} else {
//Creates File, populates it and redirects the user
if (createfile($dbFile)) {
echo "next";
stepFunction($step);
exit ();
}
}
}
} catch (PDOException $e) { //Catchs error if can't connect to the db.
echo 'Connection failed: ' . $e->getMessage();
}
// Prepare SQL Statements
$IDB = $db->prepare(
"CREATE TABLE pages (
id int(11) NOT NULL auto_increment,
subject_id int(11) NOT NULL,
menu_name varchar(30) NOT NULL,
position int(3) NOT NULL,
visible tinyint(1) NOT NULL,
content text NOT NULL,
PRIMARY KEY (id)
)ENGINE=MyISAM AUTO_INCREMENT=7 DEFAULT CHARSET=utf8");
$IDB2 = $db->prepare("
CREATE TABLE subjects (
id int(11) NOT NULL auto_increment,
menu_name varchar(30) NOT NULL,
position int(3) NOT NULL,
visible tinyint(1) NOT NULL,
PRIMARY KEY (id)
)ENGINE=MyISAM AUTO_INCREMENT=6 DEFAULT CHARSET=utf8");
$IDB3 = $db->prepare("
CREATE TABLE users (
id int(11) NOT NULL auto_increment,
username varchar(50) NOT NULL,
hashed_password varchar(40) NOT NULL,
PRIMARY KEY (id)
)ENGINE=MyISAM AUTO_INCREMENT=2 DEFAULT CHARSET=utf8");
//Set Option to True or False
if (empty ($_GET['fot']) ) {
$fOT = false;
} else { $fOT = true;
}
///////////////////////////////
// PROBLEMATIC STEP BEGINS HERE
///////////////////////////////
function createTablePages (){
global $db,$IDB;
echo "0 <br>";
stepFunction (1);
}
function createTableSubjects ($fOT){
global $db,$IDB2;
echo "1 <br>";
stepFunction (2);
}
function createTableUsers ($fOT){
global $db,$IDB3;
echo "3 <br>";
}
function stepFunction ($step,$fOT){
global $db,$IDB1,$IDB2,$step,$fOT;
switch ($step) {
case 0: echo "hola";
createTablePages ($fOT);
break;
case 1: echo "hola2";
createTableSubjects($fOT);
break;
case 2: createTableUsers ($fOT);
break;
}
}
?>

Fix
function stepFunction ($step,$fOT){
global $db,$IDB1,$IDB2,$step,$fOT;
to
function stepFunction ($step){
global $db,$IDB1,$IDB2;
You are overriding your $step variable with the global one of the same name. Thus when you come with ?step=0 you call stepFunction with 0 then it goes to createTablePages then it goes to stepFunction with 1, but is immediately replaced with 0 (because that's what the global $step's value is) and again and again...

Related

Using the count function to determine what displays in if statement

I am running into some issues with a query I am trying to make. What I am doing is trying to create a template for multiple pages to display specific images that correlate with that page.
I have individual pages where I am assigning a variable to define the page (you can see where I do this in my code with $page). Then within my database, under solution I am naming the specific records one of the individual page names. For example: if I named a page "Ball", under the database column solution, I would name a few records Ball.
Then within my query, I am trying to count how many records exist that match $page. If the record count is more than 0, I want to display the code in my else statement.
As of now, my database connection is working. I am not getting any errors being printed. You can see my echo $solution_count;. This is showing a 0, but my else-statement is running, which makes 0 sense.
Am I doing anything wrong with how I am trying to count the records? Does anyone see why this isn't working?
DB Table - show create table
projectslider
CREATE TABLE `projectslider` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`solution` varchar(50) NOT NULL,
`image` text NOT NULL,
`alt` text NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=latin1
Code on the individual pages:
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
$page = "enclosures";
include_once("projectSlider.php");
?>
Master page - projectSlider.php
error_reporting(E_ALL);
ini_set('display_errors', 1);
$servername = 'localhost';
$username = 'root';
$password = '';
try {
$con = new PDO('mysql:host='.$servername.';dbname=mb', $username, $password);
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//$page = mysql_real_escape_string($page);
//SQL Call
$sql_project = "
SELECT *, COUNT(solution) AS solution_count
FROM projectslider
WHERE solution = '. $page .'
";
if ($project_stmt = $con->prepare($sql_project)) {
$project_stmt->execute();
$project_rows = $project_stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($project_rows as $project_row) {
$solution_count = $project_row['solution_count'];
echo $solution_count;
$project_solution = $project_row['solution'];
$project_img = $project_row['image'];
$project_alt = $project_row['alt'];
$project_img = '<img class="home-comment-profile-pic" src=" '. $project_img .'" alt="' . $project_alt .'">';
if ($solution_count === 0) {
echo 'No projects found.';
} else {
echo '<section id="solProj">';
echo '<div class="projSlide">';
echo $project_img;
echo '</div>';
echo '</div>';
}
}
}
}
catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
One project have many sliders , for this you should have two tables projects and projectsliders with relationship.
projects table:
CREATE TABLE `projects` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`project_name` varchar(50) NOT NULL
)
projectsliders:
CREATE TABLE `projectsliders` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`solution` varchar(50) NOT NULL,
`image` text NOT NULL,
`alt` text NOT NULL,
`project_id` int(11),
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=latin1
fetching projectSliders for one project, Master page - projectSlider.php
Best way to fetching projectsliders for one project is to use OOP you can call a method and pass project id and method should return you a array with projectsliders for this project , but i am improving your code.
error_reporting(E_ALL);
ini_set('display_errors', 1);
$servername = 'localhost';
$username = 'root';
$password = '';
try {
$con = new PDO('mysql:host='.$servername.';dbname=mb', $username,
$password);
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//$page = mysql_real_escape_string($page);
//SQL Call
$sql_project = "SELECT * FROM projectsliders ps inner join projects p
on p.id = ps.project_id
WHERE p.project_name = '. $project_page .'";
if ($project_stmt = $con->prepare($sql_project)) {
$project_stmt->execute();
$count = project_stmt->rowCount();
if( $count != 0 ){
$project_rows = $project_stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($project_rows as $project_row) {
$project_solution = $project_row['solution'];
$project_img = $project_row['image'];
$project_alt = $project_row['alt'];
$project_img = '<img class="home-comment-profile-pic" src=" '.
$project_img .'" alt="' . $project_alt .'">';
echo '<section id="solProj">';
echo '<div class="projSlide">';
echo $project_img;
echo '</div>';
echo '</div>';
}
}else{
echo 'No projects found.';
}
}
}
catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
Individual pages :
error_reporting(E_ALL);
ini_set('display_errors', 1);
$project_page = "enclosures";
include_once("projectSlider.php");
I hope that this can help you ,enjoying coding.

PDO fetchAll only outputting one record [duplicate]

I am running into some issues with a query I am trying to make. What I am doing is trying to create a template for multiple pages to display specific images that correlate with that page.
I have individual pages where I am assigning a variable to define the page (you can see where I do this in my code with $page). Then within my database, under solution I am naming the specific records one of the individual page names. For example: if I named a page "Ball", under the database column solution, I would name a few records Ball.
Then within my query, I am trying to count how many records exist that match $page. If the record count is more than 0, I want to display the code in my else statement.
As of now, my database connection is working. I am not getting any errors being printed. You can see my echo $solution_count;. This is showing a 0, but my else-statement is running, which makes 0 sense.
Am I doing anything wrong with how I am trying to count the records? Does anyone see why this isn't working?
DB Table - show create table
projectslider
CREATE TABLE `projectslider` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`solution` varchar(50) NOT NULL,
`image` text NOT NULL,
`alt` text NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=latin1
Code on the individual pages:
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
$page = "enclosures";
include_once("projectSlider.php");
?>
Master page - projectSlider.php
error_reporting(E_ALL);
ini_set('display_errors', 1);
$servername = 'localhost';
$username = 'root';
$password = '';
try {
$con = new PDO('mysql:host='.$servername.';dbname=mb', $username, $password);
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//$page = mysql_real_escape_string($page);
//SQL Call
$sql_project = "
SELECT *, COUNT(solution) AS solution_count
FROM projectslider
WHERE solution = '. $page .'
";
if ($project_stmt = $con->prepare($sql_project)) {
$project_stmt->execute();
$project_rows = $project_stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($project_rows as $project_row) {
$solution_count = $project_row['solution_count'];
echo $solution_count;
$project_solution = $project_row['solution'];
$project_img = $project_row['image'];
$project_alt = $project_row['alt'];
$project_img = '<img class="home-comment-profile-pic" src=" '. $project_img .'" alt="' . $project_alt .'">';
if ($solution_count === 0) {
echo 'No projects found.';
} else {
echo '<section id="solProj">';
echo '<div class="projSlide">';
echo $project_img;
echo '</div>';
echo '</div>';
}
}
}
}
catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
One project have many sliders , for this you should have two tables projects and projectsliders with relationship.
projects table:
CREATE TABLE `projects` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`project_name` varchar(50) NOT NULL
)
projectsliders:
CREATE TABLE `projectsliders` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`solution` varchar(50) NOT NULL,
`image` text NOT NULL,
`alt` text NOT NULL,
`project_id` int(11),
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=latin1
fetching projectSliders for one project, Master page - projectSlider.php
Best way to fetching projectsliders for one project is to use OOP you can call a method and pass project id and method should return you a array with projectsliders for this project , but i am improving your code.
error_reporting(E_ALL);
ini_set('display_errors', 1);
$servername = 'localhost';
$username = 'root';
$password = '';
try {
$con = new PDO('mysql:host='.$servername.';dbname=mb', $username,
$password);
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//$page = mysql_real_escape_string($page);
//SQL Call
$sql_project = "SELECT * FROM projectsliders ps inner join projects p
on p.id = ps.project_id
WHERE p.project_name = '. $project_page .'";
if ($project_stmt = $con->prepare($sql_project)) {
$project_stmt->execute();
$count = project_stmt->rowCount();
if( $count != 0 ){
$project_rows = $project_stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($project_rows as $project_row) {
$project_solution = $project_row['solution'];
$project_img = $project_row['image'];
$project_alt = $project_row['alt'];
$project_img = '<img class="home-comment-profile-pic" src=" '.
$project_img .'" alt="' . $project_alt .'">';
echo '<section id="solProj">';
echo '<div class="projSlide">';
echo $project_img;
echo '</div>';
echo '</div>';
}
}else{
echo 'No projects found.';
}
}
}
catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
Individual pages :
error_reporting(E_ALL);
ini_set('display_errors', 1);
$project_page = "enclosures";
include_once("projectSlider.php");
I hope that this can help you ,enjoying coding.

A query to MySQL returns null and before it used to work just fine

Basically I want to create a query using a php PDO to check if the table "page" exists in my db "test". I didn't know how to do it and I got some help here.
My code worked perfect ... Until now that I made everything go in classes... and now the var_dump($r2) returns NULL and I don't know what's wrong with the code. I didnt change anything other than putting this into OOP...
Can anyone spot the problem?? because I cant see it.
Thx u
$r1 = $this->db->query('SHOW TABLES LIKE \'page\'');
// Debbug
$r2 = $r1->fetchAll;
var_dump ($r2);
if (count($r1->fetchAll()) > 0 ) {
echo "The table PAGE exists";
}
The full class is the following one
class phase2 {
function __construct () {
$dbFile = 'dbconfig.php';
$this->dbFile = $dbFile;
require_once ("$dbFile");
$step = $_GET["step"];
$username = $DB_USER;
$password = $DB_PASS;
$server = $DB_SERVER;
$dbName = $DB_NAME;
$this->step = $step;
$this->dbFile = $dbFile;
$this->username = $username;
$this->password = $password;
$this->server = $server;
$this->dbName = $dbName;
$db = new PDO ('mysql:host=' .$server.';dbname='.$this->dbName,$this->username,$this->password);
$this->db = $db;
if (empty ($_GET['fot']) ) {
$fOT = 'false';
} elseif ($_GET['true']) { $fOT = 'true'; }
$this->fOT = $fOT;
$this->IDB = $this->handleDatabase( 1 );
$this->IDB2 = $this->handleDatabase( 2 );
$this->IDB3 = $this->handleDatabase( 3 );
}
public function handleDatabase ($num = 1){
// Prepare SQL Statements
$IDB1 = $this->db->prepare(
"CREATE TABLE pages (
id int(11) NOT NULL auto_increment,
subject_id int(11) NOT NULL,
menu_name varchar(30) NOT NULL,
position int(3) NOT NULL,
visible tinyint(1) NOT NULL,
content text NOT NULL,
PRIMARY KEY (id)
)ENGINE=MyISAM AUTO_INCREMENT=7 DEFAULT CHARSET=utf8");
$IDB2 = $this->db->prepare("
CREATE TABLE subjects (
id int(11) NOT NULL auto_increment,
menu_name varchar(30) NOT NULL,
position int(3) NOT NULL,
visible tinyint(1) NOT NULL,
PRIMARY KEY (id)
)ENGINE=MyISAM AUTO_INCREMENT=6 DEFAULT CHARSET=utf8");
$IDB3 = $this->db->prepare("
CREATE TABLE users (
id int(11) NOT NULL auto_increment,
username varchar(50) NOT NULL,
hashed_password varchar(40) NOT NULL,
PRIMARY KEY (id)
)ENGINE=MyISAM AUTO_INCREMENT=2 DEFAULT CHARSET=utf8");
$name = "IDB".$num;
return isset( $$name)?$$name:false;
}
//Set Option to True or False
function createTablePages ($fOT){
$r1 = $this->db->query('SHOW TABLES LIKE \'page\'');
// Debbug
$r2 = $r1->fetchAll;
var_dump ($r2);
if (count($r1->fetchAll()) > 0) {
echo "The table PAGE exists";
} elseif ($fOT == 'true') {
echo "enteres";
$this->IDB1->execute();
$this->stepFunction (1,false);
}
}
function createTableSubjects ($fOT){
$r2 = $this->db->query('SHOW TABLES LIKE \'subjects\'');
if (count($r2->fetchAll()) > 0 && $fOT == 'false') {
echo "The table SUBJECTS exists ";
} elseif ($fOT == 'true') {
$this->IDB2->execute();
$this->stepFunction (2,false);
}
}
function createTableUsers ($fOT){
$r3 = $this->db->query('SHOW TABLES LIKE \'users\'');
if (count($r3->fetchAll()) > 0 && $fOT == 'false') {
echo "The table USERS exists";
} elseif ($fOT == 'true') {
$this->IDB3->execute();
echo "Would you like to populate all the tables?";
}
}
public function stepFunction ($fOT,$step){
switch ($step) {
case 0:
$this->createTablePages ($fOT);
break;
case 1:
$this->createTableSubjects($fOT);
break;
case 2: $this->createTableUsers ($fOT);
break;
}
}
}
Your query is trying to find a table named page, however, your CREATE TABLE creates a table named pages:
$IDB1 = $this->db->prepare(
"CREATE TABLE pages ("
...
$r1 = $this->db->query('SHOW TABLES LIKE \'page\'');
Unless you actually have both tables, the error lies in one of those two places.
The biggest problem that I can see is you are not creating $db - only inside the construct. Try adding to this section:
class phase2 {
function __construct () {
Adding this statement public $db;:
class phase2 {
public $db;
function __construct () {
Unless I am mistaken, you can't cast a variable from within a method without declaring it first. You'd need to do the same for any other variables you need to access from other methods in that class. Take a read of the basics: http://www.php.net/manual/en/language.oop5.basic.php
Also, I'd suggest turning on error reporting.
You are using require_once() in your constructor. The class will only initialize correctly the first time. After that the config won't load so the variables aren't set.

user level issue with redirecting [duplicate]

This question already exists:
Closed 10 years ago.
Possible Duplicate:
checklogin condition issue in php
i have this quick question please,
i have this piece of code which isn't working properly, something about the syntax.. could you please help me with it?
i know it may sound stupid enough but i'm trying to understand!
Thanks!
<?php
session_start();
require_once('db.php');
include('functions.php');
if (checkLogin('1 2')) {
echo "hello ".$_SESSION['user_id']." You are now logged in.";
} else if (checkLogin('3')) {
echo "hey tst";
} else {}
?>
function checkLogin($levels)
{
if(!$_SESSION['logged_in'])
{
$access = FALSE;
}
else {
$kt = split(' ', $levels);
$query = mysql_query('SELECT Level_access FROM users WHERE ID = "'.mysql_real_escape_string($_SESSION['user_id']).'"');
$row = mysql_fetch_assoc($query);
$access = FALSE;
while(list($key,$val)=each($kt))
{
if($val==$row['Level_access'])
{//if the user level matches one of the allowed levels
$access = TRUE;
}
}
}
if($access==FALSE)
{
header("Location: login.php");
}
else {
//do nothing: continue
}
}
CREATE TABLE `users` (
`ID` int(11) NOT NULL auto_increment,
`Username` varchar(255) NOT NULL,
`Password` varchar(255) NOT NULL,
`Temp_pass` varchar(55) default NULL,
`Temp_pass_active` tinyint(1) NOT NULL default '0',
`Email` varchar(255) NOT NULL,
`Active` int(11) NOT NULL default '0',
`Level_access` int(11) NOT NULL default '2',
`Random_key` varchar(32) default NULL,
PRIMARY KEY (`ID`),
UNIQUE KEY `Username` (`Username`),
UNIQUE KEY `Email` (`Email`)
) ENGINE=MyISAM AUTO_INCREMENT=2 DEFAULT CHARSET=latin1 AUTO_INCREMENT=2 ;
Well you could simplify your checkLogin() function
function checkLogin($levels)
{
$access = false;
if (!isset($_SESSION['logged_in']) || !$_SESSION['logged_in'])
return false;
//use mysqli instead mysql
$con = new mysqli("localhost", "username", "password", "database");
$query = $con->query('SELECT Level_access FROM users WHERE ID = "'.$con->real_escape_string($_SESSION['user_id']).'"');
$row = $query->fetch_assoc();
$con->close();
if (in_array($row['Level_access'], explode(" ", $levels))) $access = true;
return $access;
}
This function should return true or false!
After that your code could look like this
session_start();
require_once('db.php');
include('functions.php');
if (checkLogin('1 2')) {
echo "hello ".$_SESSION['user_id']." You are now logged in.";
} else if (checkLogin('3')) {
echo "hey tst";
} else {
header("Location: login.php");
}
Hope this helps you.
Your if statements need parenthesis around them:
if( checkLogin('1 2')) {
^ ^
Try this
<?php
session_start();
require_once('db.php');
include('functions.php');
if (checkLogin('1 2')) {
echo "hello ".$_SESSION['user_id']." You are now logged in.";
} else if (checkLogin('3')) {
echo "hey tst";
} else {}
?>
Run the code in your browser. You'll get an error message. Use that error message to figure out what's wrong. Repeat until you get no error messages, and the program runs as designed.
That's how we debug things in the real world.

session_set_save_handler - Why isn't this code working?

I've been trying to save PHP session data in a MySQL database, but can't get it to work.
For a simple example, here's code that should increment a counter with each visit. I've seen other examples, etc. but can someone please tell me why this code isn't working? (Apache/2.2.11 (Win32) DAV/2 mod_ssl/2.2.11 OpenSSL/0.9.8i PHP/5.2.9 MySQL client version: 5.0.51a)
Here is the mysql database table:
CREATE TABLE IF NOT EXISTS `sessions` (
`session_ID` varchar(32) COLLATE utf8_unicode_ci NOT NULL,
`session_data` mediumblob NOT NULL,
`access` int(10) unsigned NOT NULL,
PRIMARY KEY (`session_ID`),
KEY `access` (`access`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
And the PHP code (just plug in your db credentials):
<?PHP
function mysession_open()
{
global $sdbc; // Session Database Connection
if ($sdbc) {
return true;
} else {
return false;
}
}
function mysession_close()
{
global $sdbc;
return mysqli_close($sdbc);
}
function mysession_read($session_id)
{
global $sdbc;
$session_id = mysqli_real_escape_string($sdbc, $session_id);
$sql_sel = "SELECT session_data FROM sessions WHERE session_id = '$session_id'";
$data_sel = mysqli_query($sdbc, $sql_sel);
$row_sel = mysqli_fetch_array($data_sel);
if (isset($row_sel['session_data'])) {
return $row_sel['session_data'];
} else {
return '';
}
}
function mysession_write($session_id, $session_data)
{
global $sdbc;
$access = time();
$session_id = mysqli_real_escape_string($sdbc, $session_id);
$access = mysqli_real_escape_string($sdbc, $access);
$session_data = mysqli_real_escape_string($sdbc, $session_data);
$sql_write = "REPLACE INTO sessions (session_ID, session_data, access) " .
"VALUES ('$session_id', '$session_data', '$access')";
return mysqli_query($sdbc, $sql_write);
}
function mysession_destroy($session_id)
{
global $sdbc;
$session_id = mysqli_real_escape_string($sdbc, $session_id);
return mysqli_query($sdbc, $sql_del);
}
function mysession_gc($max)
{
global $sdbc;
$old = time() - $max;
$old = mysqli_real_escape_string($sdbc, $old);
$sql_old = "DELETE FROM sessions WHERE access < '$old'";
return mysqli_query($sdbc, $sql_old);
}
global $sdbc;
$sdbc = mysqli_connect('localhost', '...', '...', '...') or die('Could not connect to SDBC');
session_set_save_handler('mysession_open','mysession_close','mysession_read','mysession_write','mysession_destroy','mysession_gc');
session_start();
if (isset($_SESSION['counter'])) {
echo "counter is already set and it is " . $_SESSION['counter'] . '<br />';
$_SESSION['counter']++;
} else {
echo "counter is not set. setting to 1<br />";
$_SESSION['counter'] = 1;
}
echo "<br />Dumping SESSION data:<br />";
var_dump($_SESSION);
session_write_close();
?>
Thanks in advance for your help.
If you comment out the session_set_save_handler line of code, it works fine (it increments). But using the save handler it does not.
None of your query calls have any error checking. Instead of blindly assuming the database portion works, do some basic error checking at each stage, e.g:
function mysession_write($session_id, $session_data) {
global $sdbc;
[...snip...]
$stmt = mysqli_query($sdbc, $sql_write);
if ($stmt === FALSE) {
error_log("Failed to write session $session_id: " . mysqli_error($sdbc);
}
return($stmt);
}
There's only way way for a query to succeed, but zillions of ways to fail.
From the manual:
"Warning
As of PHP 5.0.5 the write and close handlers are called after object destruction and therefore cannot use objects or throw exceptions. The object destructors can however use sessions.
It is possible to call session_write_close() from the destructor to solve this chicken and egg problem. "

Categories