Php database handling - php

I'm working on a php page that compare information received by a client with information in a database, but I'm not so good in php and I don't know what I did wrong, I always get response code 500, internal server error.
Here is the code:
<?php
/**
* #var object $payload The payload sent from the client
*/
$payload = json_decode(file_get_contents("php://input"), true);
/**
* #var object $user_name The username sent by the client
* #var object $user_name The password sent by the client
*/
$user_name = $payload['username'];
$user_password = $payload['password'];
$response = null;
$responseCode = 200;
$result_row = null;
/**
* The form representing a positive response
*/
class Response {
public $accessToken = "";
public $availableProfiles = "";
public $selectedProfile = "";
}
/**
* The form representing a negative response
*/
class negativeResponse {
public $error = "";
public $errorMessage = "";
}
/**
* #var object $db_connection The database connection
*/
$db_connection = null;
try {
$db_connection = new PDO('mysql:host=localhost;dbname=launcher_login;charset=utf8', 'myUser', 'myPass');
} catch (PDOException $e) {
//Catch exception
}
// user can login with his username or his email address.
// if user has not typed a valid email address, we try to identify him with his user_name
if (!filter_var($user_name, FILTER_VALIDATE_EMAIL)) {
// database query, getting all the info of the selected user
$query_user = $this->db_connection->prepare('SELECT * FROM users WHERE user_name = :user_name');
$query_user->bindValue(':user_name', $user_name, PDO::PARAM_STR);
$query_user->execute();
// get result row (as an object)
$result_row = $query_user->fetchObject();
// if user has typed a valid email address, we try to identify him with his user_email
} else {
// database query, getting all the info of the selected user
$query_user = $db_connection->prepare('SELECT * FROM users WHERE user_email = :user_email');
$query_user->bindValue(':user_email', trim($user_name), PDO::PARAM_STR);
$query_user->execute();
// get result row (as an object)
$result_row = $query_user->fetchObject();
}
// if this user not exists
if (!isset($result_row->user_id)) {
$response = new negativeResponse();
$response->error = "Credenziali Invalide";
$response->errorMessage = "Non esiste un account con questa combinazione nome utente/password";
$responseCode=201;
// if the password isn't correct
} else if (!password_verify($user_password, $result_row->user_password_hash)) {
$response = new negativeResponse();
$response->error = "Credenziali Invalide";
$response->errorMessage = "Non esiste un account con questa combinazione nome utente/password";
$responseCode=201;
// if the account exists but it isn't activated
} else if ($result_row->user_active != 1) {
$response = new negativeResponse();
$response->error = "Account non attivo";
$response->errorMessage = "Devi attivare l'account! Controlla l'email inserita";
$responseCode=201;
} else {
$response = new Response();
$response->accessToken = hash('md5', $user_name);
$response->availableProfiles = array(array('id' => hash('md5', $user_name), 'name' => $user_name, 'legacy' => true));
$response->selectedProfile = array('id' => hash('md5', $user_name), 'name' => $user_name, 'legacy' => true);
}
echo json_encode($response);
http_response_code($responseCode);
My table is created with this query:
CREATE TABLE IF NOT EXISTS `launcher-login`.`users` (
`user_id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'auto incrementing user_id of each user, unique index',
`user_name` varchar(64) COLLATE utf8_unicode_ci NOT NULL COMMENT 'user''s name, unique',
`user_password_hash` varchar(255) COLLATE utf8_unicode_ci NOT NULL COMMENT 'user''s password in salted and hashed format',
`user_email` varchar(64) COLLATE utf8_unicode_ci NOT NULL COMMENT 'user''s email, unique',
`user_active` tinyint(1) NOT NULL DEFAULT '0' COMMENT 'user''s activation status',
`user_activation_hash` varchar(40) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT 'user''s email verification hash string',
`user_password_reset_hash` char(40) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT 'user''s password reset code',
`user_password_reset_timestamp` bigint(20) DEFAULT NULL COMMENT 'timestamp of the password reset request',
`user_rememberme_token` varchar(64) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT 'user''s remember-me cookie token',
`user_failed_logins` tinyint(1) NOT NULL DEFAULT '0' COMMENT 'user''s failed login attemps',
`user_last_failed_login` int(10) DEFAULT NULL COMMENT 'unix timestamp of last failed login attempt',
`user_registration_datetime` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
`user_registration_ip` varchar(39) COLLATE utf8_unicode_ci NOT NULL DEFAULT '0.0.0.0',
PRIMARY KEY (`user_id`),
UNIQUE KEY `user_name` (`user_name`),
UNIQUE KEY `user_email` (`user_email`)
) ENGINE=MyISAM AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='user data';
EDIT: I feel stupid, the error was $query_user = $this->db_connection->prepare('SELECT * FROM users WHERE user_name = :user_name');. I was using this outside of a class, now I'm working on the client part, thank you all for help

I'm almost certain the issue is that $db_connection is null since the connection is failing. Based on what you provided your database name should be launcher-login instead of launcher_login as you've specified in your connection string. As such the following edit should fix your problem.
try {
$db_connection = new PDO('mysql:host=localhost;dbname=launcher-login;charset=utf8', 'myUser', 'myPass');
} catch (PDOException $e) {
echo 'Unable to connect to database'; exit;
}

Related

SQLSTATE[HY093]:Invalid parameter number:parameter was not defined

Problem came multiple times, but I really can not find the mistake in my code. I saw that the solutions are in misspelled words usually, but I can not find that. So I thought that maybe I am wrong in something other because I am new in using PDO.
I am making signup page and error is
SQLSTATE[HY093]: Invalid parameter number: parameter was not defined
here is my code:
//index.php
if(isset($_POST['btn-signup-preduzece'])) {
$uname = trim($_POST['pr-username']); //there are inputs in my html
$umail = trim($_POST['pr-email']);
$upass = trim($_POST['pr-password']);
$comp = trim($_POST['pr-naziv']);
$maticni = trim($_POST['pr-maticni']);
$pib = trim($_POST['pr-pib']);
$sifra = trim($_POST['pr-sifra']);
$racun = trim($_POST['pr-racun']);
$adresa = trim($_POST['pr-adresa']);
if($uname=="") {
$error[] = "provide username !";
}
else if($umail=="") {
$error[] = "provide email id !";
}
else if(!filter_var($umail, FILTER_VALIDATE_EMAIL)) {
$error[] = 'Please enter a valid email address !';
}
else if($upass=="") {
$error[] = "provide password !";
}
else {
try {
$stmt = $DB_con->prepare("SELECT username,email FROM preduzeca WHERE username=:uname OR email=:umail");
$stmt->execute(array(':uname'=>$uname, ':umail'=>$umail));
$row=$stmt->fetch(PDO::FETCH_ASSOC);
if($row['username']==$uname) {
$error[] = "sorry username already taken !";
}
else if($row['email']==$umail) {
$error[] = "sorry email id already taken !";
}
else {
//PROBLEM IS HERE IN THIS FUNTION BELLOW, when I put here some echo it writes me that, but if i put echo bellow this if statement it gives me nothing
if($user->registerPreduzece($uname,$upass,$umail, $comp, $maticni, $pib, $sifra, $racun, $adresa)) {
$user->redirect('ostalo/uspesno.php');
}
}
}
catch(PDOException $e) {
echo $e->getMessage();
}
}
}
and here is my problematic function form class User
public function registerPreduzece($uname,$upass,$umail, $comp, $maticni, $pib, $sifra, $racun, $adresa) {
try
{
$new_password = password_hash($upass, PASSWORD_DEFAULT);
$stmt = $this->db->prepare("INSERT INTO preduzeca(naziv,maticniBroj,PIB,sifraDelatnosti,racun,adresa,username,password,email)
VALUES(:comp, :maticni, :pib, :sifra, :racun, :adresa, :uname, :upass, :umail)");
$stmt->bindparam(":naziv", $comp);
$stmt->bindparam(":maticniBroj", $maticni);
$stmt->bindparam(":PIB", $pib);
$stmt->bindparam(":sifraDelatnosti", $sifra);
$stmt->bindparam(":racun", $racun);
$stmt->bindparam(":adresa", $adresa);
$stmt->bindparam(":username", $uname);
$stmt->bindparam(":password", $new_password);
$stmt->bindparam(":email", $umail);
$stmt->execute();
return $stmt;
}
catch(PDOException $e)
{
echo $e->getMessage();
}
}
and my table
CREATE TABLE `preduzeca` (
`idPreduzeca` int(10) UNSIGNED NOT NULL,
`naziv` varchar(45) NOT NULL,
`maticniBroj` varchar(8) DEFAULT NULL,
`PIB` varchar(11) DEFAULT NULL,
`sifraDelatnosti` varchar(5) DEFAULT NULL,
`racun` varchar(20) DEFAULT NULL,
`adresa` int(11) DEFAULT NULL,
`username` varchar(45) NOT NULL,
`password` varchar(45) NOT NULL,
`email` varchar(45) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
ALTER TABLE `preduzeca`
ADD PRIMARY KEY (`idPreduzeca`),
ADD UNIQUE KEY `idfirme_UNIQUE` (`idPreduzeca`),
ADD UNIQUE KEY `username_UNIQUE` (`username`),
ADD UNIQUE KEY `maticniBroj_UNIQUE` (`maticniBroj`),
ADD UNIQUE KEY `PIB_UNIQUE` (`PIB`),
ADD UNIQUE KEY `racun_UNIQUE` (`racun`),
ADD KEY `fk_preduzeca_adrese1_idx` (`adresa`);
The binding of your parameters seems to be off. Try instead
$stmt = $this->db->prepare("INSERT INTO preduzeca(naziv,maticniBroj,PIB,sifraDelatnosti,racun,adresa,username,password,email)
VALUES(:comp, :maticni, :pib, :sifra, :racun, :adresa, :uname, :upass, :umail)");
$stmt->bindparam(":comp", $comp);
$stmt->bindparam(":maticni", $maticni);
$stmt->bindparam(":pib", $pib);
$stmt->bindparam(":sifra", $sifra);
$stmt->bindparam(":racun", $racun);
$stmt->bindparam(":adresa", $adresa);
$stmt->bindparam(":uname", $uname);
$stmt->bindparam(":upass", $new_password);
$stmt->bindparam(":umail", $umail);
$stmt->execute();

Check MySQL if token is valid, then return. If not, generate token

I have this table:
CREATE TABLE wp_tokens (
ID int(12) NOT NULL AUTO_INCREMENT,
USER varchar(128) NOT NULL COMMENT 'User name',
TS timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
IP varchar(64) NOT NULL,
TOKEN varchar(128) NOT NULL COMMENT 'Hashed tokens',
VALID (12),
PRIMARY KEY (`ID`)
)
And I want to check if a token exists for a user. If it exists, then it should return the token. If not, it should generate one.
Here is my PHP:
<?php
global $wpdb;
global $user_login;
$token = uniqid();
$hashedtoken = md5($token);
$user = $user_login;
$ip = $_SERVER['REMOTE_ADDR'];
$valid = "1";
$chkdb = mysql_query("SELECT valid FROM wp_tokens WHERE user=$user");
if(mysql_num_rows($chkdb) == 1)
{
echo $hashedtoken;
}
else
{
$wpdb->insert('wp_tokens',
array('user' => $user, 'token' => $hashedtoken, 'ip' => $ip, 'valid' => $valid),
array('%s','%s','%s'));
}
?>
It doesn't work and I cannot solve. It's being executed on Wordpress $wpdb should be working. Please help!

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'];
....
}

Codeigniter session different site

Hi all I have two sites developed in codeigniter. These sites are completely different but the mdoel of user is similar like the login method because I thinked to recycle that code.
The problem is: If I log in into a site and open the other I am logged in inside it with the user of the other site that doesn't exist into my database.
Database are different, I don't know what is the problem or if I have to change my login method into my model or some configuration.
This is my method in the model:
function login($username = '', $password = '') {
$user_name = base64_decode($username);
$password = base64_decode($password);
//Make sure login info was sent
if($username == '' || $password == '') {
return FALSE;
}
//Check if already logged in
if( $this->session->userdata('username') == $username && $this->session->userdata('logged_in') ) {
//User is already logged in.
return TRUE;
}
//Check against user table
$this->db->where('username', $user_name);
$this->db->where('password', $this->encrypt->sha1($password) );
$this->db->where('active', 1);
$query = $this->db->get_where($this->user_table);
if ($query->num_rows() > 0) {
$row = $query->row_array();
//Destroy old session
$this->session->sess_destroy();
//Create a fresh, brand new session
$this->session->sess_create();
//Update Last Login
$data = array(
'last_login' => date('Y-m-d H:i:s')
);
$this->db->where('id', $row['id']);
$this->db->update($this->user_table, $data);
//Set session data
$this->session->set_userdata(array('id' => $row['id'], 'username' => $row['username'],'name' => $row['name'], 'surname' => $row['surname'], 'language' => $row['language']));
if ($row['type']==1){
//se è 1 è un administrator
$this->session->set_userdata(array('is_admin' => 1));
}
else{
$this->session->set_userdata(array('is_admin' => 0));
}
//Set logged_in to true
$this->session->set_userdata(array('logged_in' => TRUE));
//image profile
$this->db->where('user_id', $row['id']);
$query2 = $this->db->get_where('user_image_profile');
if ($query2->num_rows() > 0) {
$row_image = $query2->row_array();
$this->session->set_userdata(array('img_profile' => $row_image['filename']));
}
//Login was successful
return TRUE;
} else {
//No database result found
return FALSE;
}
}
I think the problem is in the config file. Here you use the same "encryption_key" for the both site for that reason when you log in one site and open the other one here you also logged. So you have to use different "encryption_key" for the both site.
like that for first web site-
$config['encryption_key'] = 'gHZc2let11sp3YAns00rggHlYNMp7CVX';
and the second one -
$config['encryption_key'] = 'V1M839GlUk65rKzm1GM67H66X1WLD6ay';
for each application you can configure the session to be stored in the database. change config file.
sess_use_database = true;
after that you need to create this table in your database
CREATE TABLE IF NOT EXISTS `ci_sessions` (
session_id VARCHAR(40) DEFAULT '0' NOT NULL,
ip_address VARCHAR(16) DEFAULT '0' NOT NULL,
user_agent VARCHAR(120) NOT NULL,
last_activity INT(10) UNSIGNED DEFAULT 0 NOT NULL,
user_data TEXT NOT NULL,
PRIMARY KEY (session_id),
KEY `last_activity_idx` (`last_activity`)
);

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.

Categories