user level issue with redirecting [duplicate] - php

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.

Related

get user rank (mySQL)

I'm making a login, with ranks. When you are logged In you receive a welcome message. But that's diffrent for every rank.
my index.php:
<?php
include_once("config.php");
?>
<?php if( !(isset( $_POST['login'] ) ) ) { ?>
<?php
} else {
$usr = new Users;
$usr->storeFormValues( $_POST );
if( $usr->userLogin() ) {
echo "Welcome ";
if ($rank == 1) {
echo "default user";
}
if ($rank == 10) {
echo "developer! right?";
}
else {
echo "error";
}
} else {
echo "Incorrect Username/Password";
}
}
?>
but how do I get the user ranks?
my sql:
CREATE TABLE IF NOT EXISTS `users` (
`userID` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(50) NOT NULL,
`password` varbinary(250) NOT NULL,
`rank` varbinary(250) NOT NULL,
PRIMARY KEY (`userID`,`username`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=8 ;
how do I edit my code so I can get the rank of user?
Thanks!
EDIT AFTER Zsolt Szilagy's ANSWER:
$rank = 'SELECT rank FROM users WHERE userID = "' . mysql_real_escape_string($usr->get_userID()) . '"';
^^doesn't works^^ or am I doing it wrong?
'SELECT rank FROM users WHERE userID = "' . mysql_real_escape_string($usr->get_userID()) . '"';
Depending on your getters, on how the object was loaded, and on your db abstraction.

store a mysql array records in session

I have a school web application ..
I want to get all the student name on the log_in.php pages in $_SESSION['allStudent']
for retrieve on further page...
here is my log in .php pages content
include("connect.php");
if(isset($_REQUEST['submit']))
{
$id=$_REQUEST['userName'];
$pass=$_REQUEST['password'];
$sel=mysql_query("select * from login_detail where USERNAME='$id' AND PASSWORD='$pass'")or die(mysql_error());
if($arr=mysql_fetch_array($sel))
{
if(($id==$arr['USERNAME']) && ($pass==$arr['PASSWORD']))
{
session_start();
$_SESSION['id']=$id;
$query = "SELECT * FROM student_personal";
$result = mysql_query($query) or die(mysql_error());
if($result)
{
$_SESSION['allStudent']['']= mysql_fetch_array($result);
}
header("location: viewPages/common/main.php?active=dashboard");
}
}
else
{
echo "<script>alert('please enter the correct id and password');</script>";
}
}
and retrieve into main page
this is my main pages
{
//designed Part
}
<?php
if(isset($_SESION['allStudent']))
{
echo "------------------------------------------<br>";
echo "Student Name--------------------------- DOB<br>";
echo "------------------------------------------<br>";
while($row = mysql_fetch_array($_SESSION['allStudent']))
{
echo $row['STUDENT_NAME']." --------------".$row['DOB']."<br>";
}
}
else
{
echo "No result Found";
}
?>
and this is my table
DB NAME : testssdb
Table Name : student_personal
`SR_NUMBER` int(11) NOT NULL,
`STUDENT_NAME` varchar(30) NOT NULL,
`GENDER` int(11) NOT NULL,
`DOB` varchar(25) NOT NULL,
`RELIGION` varchar(30) NOT NULL,
`MAILING_ADDRESS` text NOT NULL,
`TELEPHONE_NO` varchar(22) default NULL,
`MOBILE_NO` varchar(25) default NULL,
`EMAIL` varchar(30) default NULL,
`PERMANENT_ADDRESS` text,
`MOTHER_TONGUE` varchar(30) default NULL,
`CATEGORY` int(11) default NULL,
`STATUS` int(11) NOT NULL default '1',
`REG_DATE` date NOT NULL,
`FIRST_NAME` varchar(25) NOT NULL,
`LAST_NAME` varchar(25) NOT NULL,
PRIMARY KEY (`SR_NUMBER`)
Here $student = $firstname.$lastName;
So basically i want to store all student records on log in and anyneed of student,i do not want to intrect with the database. only use of session i get the student information
session_start();
$_SESSION['count'] = 1;
$_SESSION['record'][$_SESSION['count']] = array();
$query //retrive ur data here
$result set of ur query
while ($row = mysql_fetch_assoc($result))
{
$_SESSION['record'][$_SESSION['count']]['SR_NUMBER'] = $row["SR_NUMBER"];
$_SESSION['record'][$_SESSION['count']]['STUDENT_NAME'] = $row["STUDENT_NAME"];
$_SESSION['record'][$_SESSION['count']]['GENDER'] = $row["GENDER"];
$_SESSION['record'][$_SESSION['count']]['DOB'] = $row['DOB'];
...// and go on
$_SESSION['count'] = $_SESSION['count'] + 1;
}
foreach($_SESSION['record'] as $key => $value)
{
echo $value['SR_NUMBER'];
echo $value['STUDENT_NAME'];
echo $value['GENDER'];
echo $value['DOB'];
....
}

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.

Code not responding accordingly to the parameters passed via the browser [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I put the following code in the browser ?phase=1&step=0&fot=false and I get a black page.
with the PHP error
Undefined variable: fOT in C:\Program Files
(x86)\Zend\Apache2\htdocs\Proj11\1.php on line 219
This is the $this->createTablePages ($fOT); line. If I change it to $this->createTablePages ($this->fOT) I get the following error
Undefined property: phase2::$fOT in C:\Program Files
(x86)\Zend\Apache2\htdocs\Proj11\1.php on line 219
I know that $this->IDB3 = $this->handleDatabase()->$IDB3; in the __constructor is right. How do I do that?
class phase2 {
function __construct () {
$dbFile = 'dbconfig.php';
$this->dbFile = $dbFile;
include_once ("$this->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->IDB = $this->handleDatabase()->$IDB;
$this->IDB2 = $this->handleDatabase()->$IDB2;
$this->IDB3 = $this->handleDatabase()->$IDB3;
}
public function handleDatabase (){
// Prepare SQL Statements
$IDB = $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");
}
//Set Option to True or False
function createTablePages ($fOT){
$r1 = $this->db->query('SHOW TABLES LIKE \'page\'');
if (count($r1->fetchAll()) > 0 && $fOT === 'false') {
echo "The table PAGE exists";
} elseif ($fOT === 'true') {
$this->IDB->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 ($step, $fOT){
switch ($step) {
case 0:
$this->createTablePages ($fOT);
break;
case 1:
$this->createTableSubjects($fOT);
break;
case 2: $this->createTableUsers ($fOT);
break;
}
}
}
} elseif ($fOT = 'true') {
= is an assignment. You want the comparison operator ==.
if (count($r1->fetchAll()) > 0 && $fOT = 'false') {
You've gotten confused between the assignment operator and the comparison one. You need to change that to:
if (count($r1->fetchAll()) > 0 && $fOT === 'false') {
An assignment operation returns the assigned value, so it's probably not going to give you the result you were expecting, as well as messing up the rest of the logic.

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