I use CI 2.2 to build a simple login system. But I get problem when I try to generate session. Of course I have properly set up libraries (database, session) and User_M. When I retrieve data from database (without session), that's work fine. This is my Controller code:
public function verify()
{
// Define variable
$user = $this->input->post('username');
$pass = $this->input->post('password');
// Check input data
if (!empty($user) AND !empty($pass))
{
// Check match data from db
$checks = $this->User_M->check_user($user, $pass);
if($checks->num_rows() == 1)
{
foreach ($checks->result() as $check)
{
$sess = array (
'username' => $check->username,
'logged_in' => TRUE
);
$rest = $this->session->set_userdata($sess);
if ($rest)
{
echo "working";
} else {
echo "not working";
}
}
} else {
echo "Not found";
}
} else {
echo "You've empty field";
}
}
Additional explain, I check the result with if ($rest)...bla..bla..bla, that's echoing Not Working. Please let me know where's my mistakes?
Thank in advance
I think the problem is with this statement
$rest = $this->session->set_userdata($sess);
the set_userdata() does not return anything, so according to your condition it will always execute the else part.
Try to change your condition like this
if (!empty($this->session->userdata("username"))){
echo "Working";
}else{
echo "Not Working";
}
Related
So im using the exact same script as I used to a while back and for some reason when I move to my new domain and hosting it is having really weird issues, I created a user and got hm to try login, It wasnt working for him I got a new hash from a random test.php file with this php:
<?php
/**
* In this case, we want to increase the default cost for BCRYPT to 12.
* Note that we also switched to BCRYPT, which will always be 60 characters.
*/
$options = [
'cost' => 9,
];
echo password_hash("His Pass", PASSWORD_BCRYPT, $options)."\n";
?>
It then worked, He logged in fine and I then tried to login to my main admin account and for some reason its now not working even when I try remaking the hash 2 times now.
I have no idea whats going on can someone please enlighten me.
Heres the login code:
//If User Submits Form continue;
if(isset($_POST['username'])) {
//If the captcha wasn't submitted;
if(empty($_POST['g-recaptcha-response'])) {
//And theres already a try with there IP;
if($trycount != '0') {
//Increment there try count and give a notification;
updateTries(); ?>
<script type="text/javascript">localStorage.setItem("notification", "nocaptcha");</script> <?php
//If there isn't a try on there IP yet;
} else {
//Add one try and give a notification;
addTry(); ?>
<script type="text/javascript">localStorage.setItem("notification", "nocaptcha");</script> <?php
}
//If the captcha was submitted;
} else {
//Set captcha variable to the Submitted Captcha Response;
$captcha=$_POST['g-recaptcha-response'];
//Captcha Verification Url;
$url = 'https://www.google.com/recaptcha/api/siteverify?secret=t&response=';
//JSON Encode the Captcha's response and Site IP;
$response = json_decode(file_get_contents($url.urlencode($captcha).'&remoteip='.$_SERVER['REMOTE_ADDR']), true);
//If the captcha wasn't verified;
if($response['success'] == false) {
//And theres already a try with there IP;
if($trycount != '0') {
//Increment there try count and give a notification;
updateTries(); ?>
<script type="text/javascript">localStorage.setItem("notification", "captchafailed");</script> <?php
//If there isn't a try on there IP yet;
} else {
//Add one try and give a notification;
addTry(); ?>
<script type="text/javascript">localStorage.setItem("notification", "captchafailed");</script> <?php
}
//Otherwise if it was verified;
} else {
//Try log in with the given details;
user_login($_POST['username'],$_POST['password']);
//If logged in redirect and give a notification;
if(loggedin()) { ?>
<script type="text/javascript">localStorage.setItem("notification", "loggedin");</script>
<meta http-equiv="refresh" content="0;URL='https://gameshare.io'" /> <?php
} else {
//And theres already a try with there IP;
if($trycount != '0') {
//Increment there try count and give a notification;
updateTries(); ?>
<script type="text/javascript">localStorage.setItem("notification", "loginfailed");</script> <?php
//If there isn't a try on there IP yet;
} else {
//Add one try and give a notification;
addTry(); ?>
<script type="text/javascript">localStorage.setItem("notification", "loginfailed");</script> <?php
}
}
}
}
}
User_login function:
//Create a new function named user_login;
function user_login($username = false, $password = false) {
//Fetch for the username and password applied;
$st = fetch("SELECT username,password,email,image FROM users WHERE username = :username",array(":username"=>$username));
//If a row was found continue
if($st != 0) {
$storedhash = $st[0]['password'];
if (password_verify($password, $storedhash)) {
//Set a new username session and set it the username;
$_SESSION['username'] = $username;
$_SESSION['email'] = $st[0]['email'];
$_SESSION['image'] = $st[0]['image'];
if($username == 'admin') {
$_SESSION['role'] = 'admin';
} else {
$_SESSION['role'] = 'user';
}
}
}
//If no errors happened Make the $valid true;
return true;
$dontaddtry = true;
}
Fetch function:
//Create a new function named fetch;
function fetch($sql = false,$bind = false,$obj = false) {
//Prepare The SQL Query;
$query = Connect()->prepare($sql);
//Execute Binded Query;
$query->execute($bind);
//While Fetching Results;
while($result = $query->fetch(PDO::FETCH_ASSOC)) {
//Add a row to the results respectiveley;
$row[] = $result;
}
//If there are no rows;
if(!empty($row)) {
//Make it an object;
$row = ($obj)? (object) $row : $row;
} else {
//Else row is false;
$row = false;
}
//If no errors happened Make $row true;
return $row;
}
Connect Function:
//Create a new function named LoggedIn, And apply database info;
function Connect($host = 'localhost',$username = 'x',$password = 'x',$dbname = 'x') {
//Try execute the PHP with no errors;
try {
//Create a PDO Session;
$con = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
//Session Attributes;
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$con->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
}
//Catch all PDOException errors;
catch (PDOException $e) {
//If any errors print result;
echo "<code><pre>".print_r($e)."</pre></code>";
//Make the PDO session false;
$con = false;
}
//If no errors happened Make the PDO session true;
return $con;
}
P.S If you wish to get an account to try on my site let me know and ill make a temporary account.
Make sure your the php version of your new hosting. password_hash needs at-least PHP 5.5.0.
You can check your current PHP version via following code.
<?php
echo 'Current PHP version: ' . phpversion();
?>
I know how to create session in core PHP, and I have understand how to do this in codeigniter, but I am unable to understand how to check, if the session is set or not? I have tried to check this through View but it always give me the meesage Please Login.
Kindly tell me how can I check whether the session is Set or not Set
Controller
if ($user_type=='Student')
{
if ($LoginData= $this->loginmodel->studentLogin($username,$password))
{
foreach($LoginData as $UserId)
{
$currentId= $UserId->StudentId;
}
//[[session]]
$data['students_data']= $this->loginmodel->student_profile($currentId);
$this->session->userdata('$data');
$this->load->view('students',$data);
}
else
{
//$data['message']= array('Invalid Username or Password');
$this->load->view('Login');
echo "Invalid Username or Password";
}
}
elseif ($user_type=="Faculty")
{
if($data['faculty_data']=$this->loginmodel->faculty_admin($username, $password))
{
$this->session->userdata('$data');
$this->load->view('faculty');
}
else
{
$this->load->view('Login');
echo "Invalid Username or Password";
}
}
VIEW
<?php
if (!$this->session->userdata('$data'))
{
echo "Please Login";
}
else
{
}
?>
<!DOCTYPE
Creating Session:
$newdata = array(
'username' => 'johndoe',
'email' => 'johndoe#some-site.com',
'logged_in' => TRUE
);
$this->session->set_userdata($newdata);
or
$this->session->set_userdata('some_name', 'some_value');
But before that ensure that you have the session library included.
$this->load->library('session');
Get Session Data:
if($this->session->userdata('whatever_session_name_is')){
// do something when exist
}else{
// do something when doesn't exist
}
if ($this->session->userdata('variable') !== FALSE) {
echo 'Variable is set';
} else {
echo 'Variable is not set';
}
More info
Demo code
Using has_userdata
if ($this->session->has_userdata('username')) {
return TRUE;
} else {
return FALSE;
}
Ive got a Codeigniter login system here, and just wondering where im going wrong. Heres my code:
View
<?php
echo form_open('handyman/logIn');
echo form_label('Email: ','useremail');
echo form_input('useremail');
echo "<br />";
echo form_label('Password: ','userpassword');
echo form_input('userpassword');
echo "<br />";
echo form_submit('Logmein','Log In');
echo form_close();
?>
Controller
public function logIn(){
$useremail=$this->input->post('useremail');
$userpassword=md5($this->input->post('userpassword'));
$this->load->model("HandymanModel");
if($useremail && $userpassword && $this->HandymanModel->logInUser($useremail,$userpassword)){
$data['msg']="Successfully Logged in!";
$data['title']="Logged In";
$this->load->view("header",$data);
$this->load->view("confirmation",$data);
$this->load->view("footer",$data);
} else{
$data['title']="Sign up / Log in";
$this->load->view("header",$data);
$this->load->view("page3", $data);
$this->load->view("footer",$data);
}
}
Model
function logInUser($useremail,$userpassword) {
$this->db->where('email',$useremail );
$this->db->where( 'password', $userpassword );
$login = $this->db->get()->result();
if (is_array($login) && count($login) == 1) {
return true;
} else {
return false;
}
I'm getting Error Number: 1064 which is check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHERE email = 'email#gmail.com' AND password = '1a1dc91c9073' at line 2
Thanks
You re missing the table name
$login = $this->db->get( )->result();
^^here
Try this by adding table name
$login = $this->db->get('your table name')->result();
$this->db->get();
I would change your model to something like...
function logInUser($useremail,$userpassword) {
$query = $this->db->query('SELECT * FROM tbl_name WHERE account_email="'.$useremail.'" AND account_password = "'.$userpassword.'"');
if ($query->num_rows() != 0){
return true;
} else {
return false;
}
}
I would also suggest encrypting user passwords as well. take a look at MD5. Make sure you use a hash as well.
Cheers!
I'm trying to update a field on my database with PHP and AJAX
I have tested and found that the correct data is being sent, but the PHP that is handling the update is not working correctly.
All that happens is that I get the else response in conditional.
I need to update the DB depending on what the user input is.
Like I said, all I get for the response is the else response.
$youruname = $_POST['youruname'];
$selectedplayer = $_POST['selectedplayer'];
$selPlayerUname = $_POST['selPlayerUname'];
$flag = "";
$itStatus = "";
$checkit = mysqli_query($conn,"SELECT it FROM login WHERE uname='$selPlayerUname'");
while($row = mysqli_fetch_array($checkit))
{
$itStatus = $row["it"];
}
if($itStatus == "not it")
{
mysqli_query("UPDATE login SET it = CASE WHEN uname = '$youruname' THEN 'not it' ELSE 'it' END WHERE uname IN ('$youruname', '$selPlayerUname')");
$flag = "success";
}
else if($itStatus == "it")
{
$flag = "nope";
}
else
{
$flag = "error";
}
echo json_encode(array("message" => $flag, "tagged" => $selectedplayer));
mysqli_free_result($checkit);
mysqli_close($conn);
There is something confusing here. You have a loop and after loop conditionals. Shouldnt your update query be inside a loop like:
while($row = mysqli_fetch_array($checkit))
{
$itStatus = $row["it"];
if($itStatus == "not it")
{
mysqli_query("UPDATE login SET it = CASE WHEN uname = '$youruname' THEN 'not it' ELSE 'it' END WHERE uname IN ('$youruname', '$selPlayerUname')");
$flag = "success";
}
else if($itStatus == "it")
{
$flag = "nope";
}
else
{
$flag = "error";
}
}
Your $iStatus gets the last value from the database since its in the loop and then you check in conditionals
If above does not help then check your $_POST values to see if any of them are blank or null and do the query on PHPMyAdmin see if it actually returns anything.
mysqli_query requires you to pass the connection.
I wasn't doin that.
When I passed the values to the query directly, I figured it out.
Thank you very much for the help everyone
I was looking to see what would be the best way to handle errors from functions. Is the "DIE" method appropriate?
ie. php function calls another, for example:
function login(){
$result = verifyDetails("bob", "password123");
if($result == "accepted"){
echo "Welcome bob";
}else{
echo "Error!! \n";
echo $result;
}
}
function verifyDetails($user, $pass){
if(empty($user) || empty($pass)){
die("cannot be empty");
}
if($user == "bob" && $pass == "password"){
return "accepted";
}else{
die("username or password incorrect");
}
}
does the "DIE" method return the message or does everything come to a standstill?
thanks in advance
UPDATE
what if the output is not known?
for example. in the above example I have placed "accepted" as the only correct answer.
What if the return is a name or id number.. then you cant really separate the error and correct returns.
thanks again.
UPDATE / Possible Solution
function login(){
$result = verifyDetails("bob", "password123");
if($result[0] == "SUCCESS"){
echo "Welcome bob";
}else if($result[0] == "ERROR"){
echo "Error!! \n";
echo $result;
}else{
echo "Unknown Error!!";
}
}
function verifyDetails($user, $pass){
$msg = array();
if(empty($user) || empty($pass)){
$msg[0] = "ERROR";
$msg[1] = "cannot be empty"
return $msg;
}
if($user == "bob" && $pass == "password"){
//say $customerID is extracted from a db
$msg[0] = "SUCCESS";
$msg[1] = $customerID
return $msg;
}else{
$msg[0] = "ERROR";
$msg[1] = "username or password incorrect"
return $msg;
}
}
ideas & suggestions on the above "possible" solution are welcome
UPDATE
Check Shikiryu update 2 answer below for a cleaner version using arrays
die() just echo your message and stop the script because die() is an alias of exit().
In your case, since the password isn't password but password123, the script will stop just displaying "username or password incorrect".
But as I can see here, you want a return "cannot be empty";, so that it'll display :
Error!!
username or password incorrect
(and optionally the rest of the html which die() won't)
Update 2 (ugly way) :
function login(){
$result = verifyDetails("bob", "password123");
if(isset($result['success']){ // verifyDetails return true?
echo $result['success'];
}else{
echo "Error!! \n";
echo $result['error']; // Display the error verifyDetails throws
// You may want to check if $result['error'] exists.
}
}
function verifyDetails($user, $pass){
if(empty($user) || empty($pass)){
return array('error'=>"cannot be empty");
}
if($user == "bob" && $pass == "password"){
return array('success'=>"Welcome bob");
}else{
return array('error'=>"username or password incorrect");
}
}
die terminates the execution of the PHP script at the line it is called. Therefore, your message would no be returned.
You might want to simply use return instead of die;
Yes, you could use die() to debug.
does the "DIE" method return the message or does everything come to a standstill?
Yes, it returns the error message and yes, the script will stop continuing.
Well the only acceptable way in your case is return FALSE
if these functions are really methods of some class, use class variable to store actual errors.
if these functions belongs to no class, I wouldn't use them at all, but write it in plain code
if($user == "bob" && $pass = "password"){
echo "Welcome bob";
}else{
echo "incorrect username or password");
}
updated answer
Well there is nothing to invent. Just follow the way PHP goes:
Make your function return either value or FALSE
however, for the validation purpose you have to make it this way:
function validSomething($val){
return (bool)rand(0,1);
}
$err = array();
if (!validSomething($var)) {
$err[] = "Whatever error";
}
i.e. function returns only boolean values and actual error message being added by application logic.
However, in your example user-defined functions are totally misused.