PHP: testing session - php

Why is the construction brittle? I tried "!empty ( get_original_passhash() )" as a condition, but it ignites the error that you cannot use the return value.
if ( get_original_passhash () != '' )
{
set_login_session ( get_original_passhash() );
}else
print("Please, log in.");

I would be inclined to assign the variable before you test it, and probably also clean up your formatting a little too:
$original_hash = get_original_passhash();
if ($original_hash != ""){
set_login_session(get_original_passhash());
} else {
print("Please Log In");
}
You should also ensure that get_original_passhash() is returning the right type of variable - interger, string, boolean, etc.
Edit:
function get_original_passhash(){
$dbconn = pg_connect("host=localhost port=5432 dbname=heoa user=heoa password=123");
if(!empty($passhash_session)){
return $passhash_session;
} else {
return $passhash_post;
}
}
What is this code supposed to do? It connects to a database, and then tests a variable that just appears out of nowhere? Your code isn't working because, from the example's you've provided us, nothing is even being set. Is this the full source code for this function?

You may want to split up your logic:
if (is_logged_in()) {
set_login_session(get_original_passhash());
} else {
print("Please Log In");
}
Since, in the conditional, you don't want the pass hash. You want to know if they're logged in or not.

Related

Validation function with return value 0

im busy with a school project and i made a function that checks if a password is valid. For some reason it returns "0". I have no clue why. Is there anyone who could help me out here?
I also made functions to check Mail and Username, those work fine.
Thanks in advance for your help!
function checkPassword($pass){
if (strlen($pass) < 6) {
return "Your password must contain more than 6 characters";
}
else {
if (preg_match('~[0-9]~', $pass)){
if (preg_match('/^[\p{L}\p{N}_-]+$/u', $pass)) {
return true;
}
else {
return "Your password contains illegal characters";
}
}
else {
return "Your password must contain at leas one number";
}
}
}
$val3 = checkPassword($_POST['password']);
if ($val3 !== true) {
$_SESSION["wrongreg"] = $val3; // $val3 = 0, for some reason.
header('Location: register.php');
}
As IncredibleHat said, it can't return 0. However, you actually do not show where you print the $_SESSION["wrongreg"] data. You instead redirect with header(). The only explanation to why you could say it tells you the respons is 0, is that something happens on the "register.php" page, which you haven't showed here yet.
One thing you might be doing on that page is: strval(intval($_SESSION["wrongreg"]));
That would give us 0 (but it is a strange thing to do). More probable is that there is some entirely different code on the register.php page, that gets in the way, making the script print something entirely different than the return string from that password function.

Check result of PHP include

I've got my login and session validity functions all set up and running.
What I would like to do is include this file at the beginning of every page and based on the output of this file it would either present the desired information or, if the user is not logged in simply show the login form (which is an include).
How would I go about doing this? I wouldn't mind using an IF statement to test the output of the include but I've no idea how to go about getting this input.
Currently the login/session functions return true or false based on what happens.
Thanks.
EDIT: This is some of the code used in my login/session check but I would like my main file to basically know if the included file (the code below) has returned true of false.
if ($req_method == "POST"){
$uName = mysql_real_escape_string($_POST['uName']);
$pWD = mysql_real_escape_string($_POST['pWD']);
if (login($uName, $pWD, $db) == true){
echo "true"; //Login Sucessful
return true;
} else {
echo "false";
return false;
}
} else {
if (session_check($db) == true){
return true;
} else {
return false;
}
}
You could mean
if (include 'session_check.php') { echo "yeah it included ok"; }
or
logincheck.php'
if (some condition) $session_check=true;
else $session_check=false;
someotherpage.php
include 'session_check.php';
if ($session_check) { echo "yes it's true"; }
OR you could be expecting logincheck.php to run and echo "true" in which case you're doing it wrong.
EDIT:
Yes it was the latter. You can't return something from an included file, it's procedure not a function. Do this instead and see above
if (session_check($db) == true){
$session_check=true;
} else {
$session_check=false;
}
Actually..
$session_check=session_check($db);
is enough
Depending on where you want to check this, you may need to declare global $session_check; or you could set a constant instead.
you could have an included file which sets a variable:
<?php
$allOk = true;
and check for it in you main file:
<?php
include "included.php";
if ($allOk) {
echo "go on";
} else {
echo "There's an issue";
}
Your question seems to display some confusion about how php includes work, so I'm going to explain them a little and I think that'll solve your problem.
When you include something in PHP, it is exactly like running the code on that page without an include, just like if you copied and pasted. So you can do this:
includeme.php
$hello = 'world';
main.php
include 'includeme.php';
print $hello;
and that will print 'world'.
Unlike other languages, there is also no restriction about where an include file is placed in PHP. So you can do this too:
if ($whatever = true) {
include 'includeme.php';
}
Now both of these are considered 'bad code'. The first because you are using the global scope to pass information around and the second because you are running globally scoped stuff in an include on purpose.
For 'good' code, all included files should be classes and you should create a new instance of that class and do stuff, but that is a different discussion.

PHP Function Not Being Recognized?

I have a PHP function I'm using to determine if my user is logged in or not, it's very simple, and the code by itself works. I've never used functions much before, but I want to start. So I have my function is_logged(), which returns true if the user is logged in, obviously false if not. But when using the function, it is always returning true, no matter the circumstance. If I take the code within the function, and plainly have it outside of a function, it works, but if I put it back in the function, even if the user is logged out, it returns true.
is_logged Function
function is_logged(){
if(!empty($_SESSION["user"])){
return true;
} else {
return false;
}
}
How I'm trying to test the function.
if(is_logged) { echo "<br />Logged In"; } else { echo "<br />Not Logged In"; }
But the function only works if I take the inner code out of the function...I'm very confused as to why it's not working. The function is listed in a spot where the session variables can be read.
Change
if(is_logged)
TO
if(is_logged())
And your function can easily be simplified ...
function is_logged() {
return !empty($_SESSION["user"]);
}
You call is_logged() function without () (brackets).
Also I suggest to optimize it with following:
function is_logged(){
return !empty($_SESSION["user"]);
}
if(is_logged()){ echo "<br />Logged In"; } else { echo "<br />Not Logged In"; }
There is no need in if-statement, if you goint to return boolean result. It will only slow the function down.
Try making it more readable on your end:
if (is_logged)
{
echo "<br />Logged In";
}
else
{
echo "<br />Not Logged In";
}
Try making it like this:
if (is_logged() === true){
// Function has returned true so act accordingly
}else{
// If here. Function has returned false, so act accordingly
}
Why use:
is_logged()?
Well, this indicated a function call.. Whereas using is_logged will make PHP look for a defined constant.

An Include inside an if statement in Joomla-PHP

Im adding php inside an article using DirectPHP plugin.
My goal is to create a script that will include a file with text when the user has member = true; and when not to not show anything.
I have added this piece of code in a module in the top next to the logo:
<?php
if ($user =JFactory::getUser()->guest)
{
$member = false;
echo "Welcome guest, sign up and read nice quotes";
}
else
{
$member = true;
$user =& JFactory::getUser();
echo "Welcome " . $user->username;
}
?>
I have set member = true; now that the person has signed in. If he isnt signed in its on false.
Then inside the article I have:
<?php
if ($member == false)
{
$file = file_get_contents ('quotes/quotes.html');
echo $file;
}
?>
<hr id="system-readmore" />
<?php
if ($member == true)
{
include_once JPATH_SITE.'/quotes/random.php';
echo ShowQuotes();
}
?>
I cant find the problem making this not run. The quotes are shown for both $member = false; and $member = true; Are includes always being parsed despite the if statement? Same goes for file_get_contents? I tried to see if the $member declaration from the header is being kept within the parsing and wrote:
<?php
if ($member = true)
{
echo "Logged in";
}
?>
and it worked good so the problem is within the include_once and file_get_contents, I tried to pinpoint it as much as I can.
Thanks in advance for your help!
This is probably your issue:
if ($member = true)
{
echo "Logged in";
}
This is always assigning the value of true to $member.
Also here:
if ($user =JFactory::getUser()->guest)
You might have the same assignment problem (not sure if you intended to set $user and do a conditional at one here.
I might suggest getting in the habit of writing condditionals like this:
if (true === $member) { ... }
By inverting the order of the items, if you ever accidentally type = instead of == or ===, then you will get an error, instead of having the code silently perform unexpectedly.
You seem to have a scope issue here: you are declaring $member in a module, but $member won't be available to the article: and php will evaluate ($something == false) to always succeed if $something is undefined, if you want to check if a variable is really false you need to use ($something===false). Read more here: http://www.php.net/manual/en/language.types.boolean.php
That being said, since there is no real overhead to JFactory::getUser()->guest, just use that as well in you article!
btw, enable notices in your php configuration (either on screen or to a log file) and make sure you read that as you develop, it will tell you whatever is wrong, developing without seeing the errors is a guessing game, you can only bang your head against the wall so many times... you eventually need to switch on the light :-)

Optimal way to handle "return"?

I need an advice how to handle function with lots of different return's better.
I have this simple log in function in my class:
public function login($email, $password){
$record = // Go to database and find what we need.
if($record){
// Check pass, $user_match = TRUE;
} else {
return 1; //No such user. Please register!
}
$active = (1 == $record['is_active']) ? TRUE : FALSE;
$verified = (1 == $record['is_verified']) ? TRUE : FALSE;
//User email and password matched:
if($user_match == true){
if($verified === true){
// Start session and insert to db table "online_users"
// Check that user was inserted to table: $confirm = $stmt->rowCount();
if($confirm !== 1){
return 2; //Unexpected technical error. Please try again in a moment.
}
return 0; //0 means that all clear, we good to go.
} else {
return 3; //not verified
}
} else {
return 4; // no match with email and pass, reject!
}
}
The problem is, that now all the time I need to check all return's, something like that:
$log = $user->login($_POST['email'], $_POST['pass']);
if($log === 0) {
//Log in & edirect
} elseif ($log === 1) {
//No such user. Tell to register
} elseif($log === 2){
//technical error, try again
} elseif($log === 3){
//Not verified
} elseif($log === 4){
//wrong password
It's really annoying right now, and imagine if I would need to check like 20 return's? Is there any better way? How to do it more efficient and faster?
Thanks in advance.
You should rethink the purpose of this function and structure the return types accordingly. If the purpose is to log the user in, there can only be one answer: it either worked or it didn't. So the primary return type of the function should be a boolean. How to differentiate between different causes for failure is a different topic.
Option 1: throw exceptions:
try {
if (!$foo->login()) {
echo 'Invalid credentials';
}
} catch (UserNotActiveException $e) {
...
} catch (UserNotValidatedException $e) {
...
}
Not necessarily the most elegant option, since a failed login isn't really an exceptional circumstance.
Option 2: save the error state in the login provider:
if (!$foo->login()) {
echo "You're not logged in because ", $foo->loginError();
}
Whether this is good or not depends on how the class is used otherwise, you may not want to make it too stateful.
Option 3: separate the problem of login from what is the user's state entirely:
if (!$foo->login($user)) {
switch ($foo->currentStatus($user)) {
case $foo::ALL_OK :
echo 'Login credentials invalid';
break;
case $foo::ACCOUNT_INACTIVE :
...
}
}
Option 4: return a status object:
$result = $foo->login();
switch ($result->status) {
case $result::ALL_OK :
...
}
That's essentially what you're doing now, just without the magic numbers.
Using exceptions would be one way to provide clear handling of error code, depending on how this fits into the rest of your application.
As was pointed out by Nanne, you shouldn't use exceptions for flow control: they should only indicate exceptional circumstances. The technical error is clearly an exceptional circumstance and using exceptions for this would be clear and appropriate.
Using exceptions for the rest of it is less clear, but still an option. You could simply throw an exception with different error messages for each failure condition, or different exception classes that have appropriate handlers for the failure conditions.
This is starting to break the semantics of exceptions, depending on how this code fits in with the rest. Being able to call the login function elsewhere without having to worry about it throwing inappropriate exceptions might be useful or necessary, for example.
In the end, there's probably no getting around the need to have explicit checks for each of those failing conditions and returning them inside the function. Again, depending on how flexible this needs to be, you could just return true on a successful login, or an error message on failure (using === to verify that the result is true, not just truthy). Or you could return an object with a success property and an error condition, which at least makes your error handling code a matter of checking the success and handling the error code.
If you need significantly different error handling mechanisms for each failure condition, then returning a constant for each failure case could at least make it clear what's going on in the code. You can then return LOGIN_PASSWORDS_DO_NOT_MATCH instead of a cryptic number, which could then be checked in your error code.
Better use switch statement if you need many if-else statements:
$log = $user->login($_POST['email'], $_POST['pass']);
switch ($log) {
case 1:
break;
case 2:
break;
//etc....
}
To clarify error codes use named constants or static array of name=>code pairs instead of "magic numbers"
static $ERROR_CODES = array(
"WRONG_PASSWORD"=>1,
"WRONG_EMAIL"=>2
);
switch ($log) {
case LoginClass::$ERROR_CODES["WRONG_PASSWORD"]:
break;
case LoginClass::$ERROR_CODES["WRONG_EMAIL"]:
break;
//etc....
}
You can use INI Files
write your bugs in an ini file:
1 = "Error"
2 = " Technical"
3 = "Network"
...
And save it into and ini file. Then use this code:
<?php
$array = parse_ini("er.ini");
echo $array[$log];
?>

Categories