PHP Problem: else condition not executing - php

function procLogin( $user, $pass, $remember, $hostname, $domainame )
{
global $session, $form;
$retval = $session->login( $user, $pass, $remember );
if ( $retval )
{
if ( $session->userlevel == 9 )
if ( $session->isAdmin() )
return ( array(
$session->userlevel, $session->userid
) );
} else {
$process = new process( );
//process->s_Host('domain.com');
//$process->s_Domain('domain.com');
$process->s_Host( $hostname );
$process->s_Domain( $domainname );
$process->s_processSecure( false );
$process->s_User( $user );
$process->s_Pass( $pass );
// First check we actually have a username and password set inside the process object.
if ( $process->g_User() && $process->g_Pass() )
{
if ( $process->processConn() )
{
if ( $process->processBind() )
{
return 'google';
}
}
}
}
}
My problem is if the login is false, why does it not turn towards else condition....
if i remove the code inside else part and put return 'no' it does work.... i just want to know why the code inside the else part does not execute

$session->login(... must somehow always evaluate to true. You would probably be better off posting the code of the login method.

Maybe login is returning "false" as a string? It is evaluating to true because it is not null.

Without a specific error or details of the implementation, or a hint that the PHP runtime or builtin or library is broken ...
This looks like a case of go back, check, debug.

Related

Why does the PODS wordpress plugin is not return true when checking -> exists() against a valid POD?

I'm using the PODS plugin for custom post types within WordPress.
The problem I've got is in the
if ($mypod->exists() ){ line - I've hard coded the $user_id and $id - to values that definitely exist in the database - 100% checked.
The code below gets past the if ( false !== $mypod) check - but then when I go to "exists" that check fails and it goes to "doesn't exist".
Is there a problem with my $params definition, or is it in my inderstanding of the "exists()" check?
Thanks, Mark
$user_id=2;
$id=720;
$params = [
'where' => 't.ID = ' . $id . ' and t.post_author = ' . $user_id
];
$mypod = pods( 'tftracker', $params);
// Check if the pod is valid.
if ( false !== $mypod ) {
// Check if the pod item exists.
if ($mypod->exists() ){
echo 'exists';
$fields = array( 'measure_description', 'unit_type', 'latest_result', 'result_date' );
// Output an edit form with all fields
echo $mypod->form( $fields );
}
else
{
echo 'doesn\'t exist';
}
}
Try changing if ( false !== $mypod ) to if ( $mypod ). It's possible the pods() function returns null rather than false as a failure result.
I think you need to use the strict option:
https://docs.pods.io/code/pods/

receive returned value by class in oop

i have a class like this :
<?php
class connection {
public $db;
public function __construct() {
$this->db = new mysqli('localhost', 'root', '', '');
if($this->db->connect_errno > 0){
die('error ' . $this->db->connect_error);
}
$this->db->set_charset("utf8");
}
}
class masssave extends connection {
public $sql;
public function insert_all {
// do some works
if ( $sql = $this->db->query("INSERT INTO $db_name ($str_db_value) values ($str_form_value_found) ")) {
return true;
}
else {
return false;
}
}
}
?>
in masssave class i seted $sql as public , now i want to use this class in some pages , like register page
$save = new masssave;
if ( $save->sql = true ) {
echo 'ok';
}
else {
echo 'failed';
}
but the upper code is not working , it always echo 'ok' even the query was failed ,
i also use if ( $save->sql == true ) but this code always echo 'failed'
i am newbie in oop , but i think my php classes are ok , i think i am doing wrong way for checking returned value
replace $sql = $this->db->query with $this->sql = $this->db->query -- $sql - local variable. $this->sql - object property
call proper method after $save = new masssave; use $save->insert_all()
use comparison (but not assigment) $save->sql = true - assigment, $save->sql == true - comparison. Assigment reutrns value of variable, so $save->sql = true is always true.
This line should be...
if ( $save->insert_all() == true )
Because....First off, you are just checking if $save->sql is set, which will always echo true in your case.
Also you weren't even checking you were actually setting (= vs ==)
$save = new masssave;
if ( $save->sql = true )
Should be...
$save = new masssave;
if ( $save->sql == true ) {
But that will always return true anyways, because its just checking if the variable exists, which it does. What you really want is what I posted at the top. Because query is actually inside the insert_all function, which is where you are returning true or false.
It will always echo ok because you're setting the $save->sql to true
if ( $save->sql = true ) {
The above is a big NO NO.
What you want is to compare it, so using == to compare the values
if ( $save->sql == true ) {
It would be simpler to just do:
if($save->sql) {
echo 'ok;
} else {
echo 'fail';
}
the above if check is basically saying IF(TRUE) { SAY OK} ELSE { SAY FAIL}

How to set new array if unserialize string changed by user

$apply_id=25;
if(isset($_COOKIE['apply'])){$apply_cookie=$_COOKIE['apply'];}
else{$apply_cookie=serialize(array());}
$apply_cookie=unserialize($apply_cookie);
//HAVE COOKIE
if(in_array($apply_id, $apply_cookie)==TRUE){echo "COOKIE=TRUE<BR>"; print_r($apply_cookie);}
else{
//NO COOKIE,DB HAVE RECORDED
$db=FALSE;//I don't want to query, so just set TRUE FALSE
if($db==TRUE){
echo "COOKIE=FALSE; DB=TRUE";
$apply_cookie[]=$apply_id;
$apply_cookie=serialize($apply_cookie);
setcookie("apply", $apply_cookie);
}
else{
//NO COOKIE,NO RECORDED
echo "COOKIE=FALSE, DB=FALSE";
$apply_cookie[]=$apply_id;
$apply_cookie=serialize($apply_cookie);
setcookie("apply", $apply_cookie);
//process the apply query...
}
}
I have set up a cookie for my apply button, if user have been apply, it will pop message instate to query again, if no cookie, it will check db and update cookie.
I store array(unserialize) into cookie and I use in_array to check.
However if user try to change my cookie, unserialize will get error.
Is any way to set up like- if unserialize=FALSE apply_cookie=array();
something like that
unserialize returns false if it fails.
$apply_cookie = #unserialize($apply_cookie);
if ($apply_cookie === false) {
$apply_cookie = array();
}
use #unserialize, the "#" infront of a function will silence errors
<?php
$apply_id = 25;
if ( isset( $_COOKIE["apply"] ) ) {
$apply_cookie = $_COOKIE["apply"];
}
$apply_cookie = ( isset( $apply_cookie ) ) ? #unserialize( $apply_cookie ) : array();
$apply_cookie = ( is_array( $apply_cookie ) ) ? $apply_cookie : array();
//HAVE COOKIE
if ( in_array( $apply_id, $apply_cookie ) ) {
echo "COOKIE=TRUE<BR>";
print_r( $apply_cookie );
}
else {
//NO COOKIE,DB HAVE RECORDED
$db = false;
if ( $db === true ) {
echo "COOKIE=FALSE; DB=TRUE";
$apply_cookie[] = $apply_id;
$apply_cookie = serialize( $apply_cookie );
setcookie( "apply", $apply_cookie );
}
else {
//NO COOKIE,NO RECORDED
echo "COOKIE=FALSE, DB=FALSE";
$apply_cookie[] = $apply_id;
$apply_cookie = serialize( $apply_cookie );
setcookie( "apply", $apply_cookie );
//process the apply query...
}
}
?>
You should use $_SESSION instead of $_COOKIE.
To unserialzie user inputs is VERY DANGEROUS.
unserialize
http://www.php.net/manual/en/function.unserialize.php
Warning
Do not pass untrusted user input to unserialize().
Unserialization can result in code being loaded and executed due to
object instantiation and autoloading, and a malicious user may be able
to exploit this. Use a safe, standard data interchange format such as
JSON (via json_decode() and json_encode()) if you need to pass
serialized data to the user.
If you defined like the following class:
<?php
class TestClass {
public function __destruct() {
echo '__destruct() called';
}
}
And if you get serialized data:
O:9:"TestClass":0:{}
It will be displayed, __destruct() called.

PHP case insensitive usermame match

ANSWER EDIT:
The fix was to change:
if (get_user_data( $input_user, $logindata ) === $input_pwd ) {
to
if (get_user_data(strtolower($input_user), $logindata) === $input_pwd ) {
so that the username is forced to lowercase. I just have to be conscious to store my usernames as all lowercase too.
I am aware of strcasecmp. I am not sure how that would apply to my working code though, as you can only compare 2 variables.
Am I able to make preg_match case insensitive in the context of my working code below?
Can I add the /i regex to my preg_match command to a returned variable?
I just want the username that is entered by the user (including domain name) to be case insenstive. (ie. uSeRnAMe#dOmAIN1.CoM) without having to add every combination of valid username to my pseudo database!
This is my working code:
// Get users
$input_pwd = ( isset( $_POST["password"] ) ? $_POST["password"] : '' );
$input_user = ( isset( $_POST["username"] ) ? $_POST["username"] : '' );
// Your pseudo database here
$usernames = array(
"username#domain1.com",
"username2#domain1.com",
"username3#domain1.com",
"username1#domain2.com",
"/[a-z][A-Z][0-9]#domain2\.com/", // use an emtpy password string for each of these
"/[^#]+#domain3\.com/" // entries if they don't need to authenticate
);
$passwords = array( "password1", "password2", "password3", "password4", "", "" );
// Create an array of username literals or patterns and corresponding redirection targets
$targets = array(
"username#domain1.com" => "http://www.google.com",
"username2#domain1.com" => "http://www.yahoo.com",
"username3#domain1.com" => "http://www.stackoverflow.com",
"username1#domain2.com" => "http://www.serverfault.com",
"/[a-z][A-Z][0-9]#domain2\.com/" => "http://target-for-aA1-usertypes.com",
"/[^#]+#domain3\.com/" => "http://target-for-all-domain3-users.com",
"/.+/" => "http://default-target-if-all-else-fails.com",
);
$logindata = array_combine( $usernames, $passwords );
if ( get_user_data( $input_user, $logindata ) === $input_pwd ) {
session_start();
$_SESSION["username"] = $input_user;
header('Location: ' . get_user_data( $input_user, $targets ) );
exit;
} else {
// Supplied username is invalid, or the corresponding password doesn't match
header('Location: login.php?login_error=1');
exit;
}
function get_user_data ( $user, array $data ) {
$retrieved = null;
foreach ( $data as $user_pattern => $value ) {
if (
( $user_pattern[0] == '/' and preg_match( $user_pattern, $user ) )
or ( $user_pattern[0] != '/' and $user_pattern === $user)
) {
$retrieved = $value;
break;
}
}
return $retrieved;
}
You can do a case insensitive match in PHP with i. For instance, the following will print 'This matches!':
<?php
if ( preg_match('/def/i', 'ABCDEF') ) {
echo 'This matches!';
}
?>
So just add i to the pattern, and the case will be ignored.
One approach if you want case-insensitive usernames is to always lowercase a new one when you store it, and then to always lowercase the comparing value when you check. (This is a lot faster than using preg_match.)

PHP setcookie issue

After a user signs in and his password is verified, I need to store his username in a cookie. I tried to simply add setcookie() when the password is successfully verified in the section that looks like if ( $password_match == $user_login_password ) {... but for some reason it doesn't seem to be working. I can't set cookies when a user successfully logins with correct password/username. Is there some reason you can't setcookies from inside a function?
public function write($p) {
if ( $_POST['user_login_username'] )
$user_login_username = mysql_real_escape_string($_POST['user_login_username']);
if ( $_POST['user_login_password'] )
$password = mysql_real_escape_string($_POST['user_login_password']);
$password .= 'some_Salt';
$user_login_password = hash('sha256', $password);
} elseif ( $user_login_username && $user_login_password ) {
$q = "SELECT * FROM users WHERE username = '$user_login_username'";
$r = mysql_query($q);
if ( $r !== false && mysql_num_rows($r) > 0 ) {
while ( $a = mysql_fetch_assoc($r) ) {
$password_match = stripslashes($a['password']);
}
if ( $password_match == $user_login_password ) {
echo $this ->display_login('Correct!');
setcookie('user','some_username');
} else {
echo $this ->display_login('Wrong Password!');
}
} else {
echo $this ->display_login('That username does not exist.');
}
return;
} else {
return false;
}
}
I'd do this that way:
function mysetcookie($name, $value, $timestamp=null, $directory='/') {
return setcookie($name, $value, time()+$timestamp, $directory);
}
And I'd be using mysetcookie() instead of setcookie() :) And I'd consider reading this:
http://php.net/manual/en/function.setcookie.php
Ahh I got it. Protocol restriction with setcookie, I was trying to set it after the tags. Thanks to everyone who looked, I should have read the documentation better. Sorry!

Categories