PHP Function Not Being Recognized? - php

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.

Related

unable to check if the user has logged in php

i have a master page where all my menus are in and m unable to check if the user has logged in or no this is what i have so far
functions.php
<?php
ob_start();
function loggedin()
{
if(isset($_SESSION['user_id'])&&!empty($_SESSION['user_id']))
{
return true;
}else
{
return false;
}
}
?>
Masterpage.php
if(!loggedin()){
echo "log out";
}else{
echo "log in";
}
but this doesn't work for some reason i am always shown with the Logout option
i have tried changing the if statement but no success.
you have to start a session with session_start() before checking th session, and to make sure that the session has been opened with the correct name and value.
Also you can optimize your function to:
function loggedin(){
return !empty($_SESSION['user_id']);
}

Having problems building my login-function, cant store sessions (php)

I am a Beginner. Right now I am trying to build a simple Login/Register-System to learn.
It worked once, but not anymore and I cant figure out where im going wrong. Slowly my Code becomes Spaghetti.
What I want:
LOGIN-System that starts a Session after logging in. But the session is not working! Please beware that all the echos are ugly but just for me to check right now!
My HTML CODE:
//Check if class responds
$user->classtest();
session_start();
//Login-Function
if($user->checkSession()) {
echo "Session is okay";
} else {
if(isset($_POST['uname']) && isset($_POST['upass'])) {
$name = $_POST['uname'];
$pass = $_POST['upass'];
if($user->checkPW($name,$pass)) {
$user->startSession($name,$pass);
} else {
echo "Your Login is wrong, please try again";
$user->loginForm();
}
} else {
echo "<br>You are not logged in. Please login!";
$user->loginForm();
}
}
Here are the function from the classes:
Starting the Session:
public function startSession($uname,$upass) {
$userData = $this->getUserData($uname);
session_start();
$_SESSION['username'] = $userData[0]["username"];
$_SESSION['password'] = $userData[0]["password"];
echo "<br>You are logged in and we started the session ";
echo "<br>Username: " . $_SESSION['username'] . "<br>";
echo "<br>Password: " . $_SESSION['password'] . "<br>";
return true;
}
and my function that should check if there is a Session:
public function checkSession() {
if(isset($_SESSION['username']) && isset($_SESSION['password'])) {
return true;
} else {
return false;
}
}
Now, although my startSession function gives me the $_SESSION['username'] correctly after submitting the login-form the checkSession() Function always gives me false.
Sorry for the not perfect code etc. Im a real beginner still figuring things out!
You call checkSession BEFORE you ever call session_start(), which means $_SESSION will be empty, and your isset() calls will fail.
Just init the session with session_start(); on the top of your file.
Or - if necessary - in the construct function of your class:
function __construct() { session_start(); }
Please be aware of having output before initialise Session (or setting cookies also).

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 working properly (echoing a string, simple)

I created a function to allow me to debug PHP scripts so long as a variable ($debug) is set to 1:
function debug($msg) {
if ($debug == 1) {
echo $msg;
} else {
return false;
}
}
That way, at the top of my script (before the functions.php file is called), I write:
$debug = 1;
to enable debugging, then:
debug("Function executed: " . $data);
at certain points so that I know string values/whatever at that point, with the desired response being the message displayed upon the screen.
However, regardless of what the value of the $debug string is, I never see any echo'd statements.
How can this be achieved?
Debug is not available to your function because it is out of scope. You either:
Need to pass it as a parameter
Use the global keyword to include it in your function (discouraged)
.
function debug($msg, $debug){
if($debug==1){
echo $msg;
} else {
return false;
}
}
or
function debug($msg){
global debug;
if($debug==1){
echo $msg;
} else {
return false;
}
}
It's difficult to say because you provided too few data.
The reason can be that your $debug variable is not known inside a function. Because using globals is not adviced, consider using constants define("DEBUG",1);.
EDIT
I presented within another question how I use a class for doing the same thing as class names are also globally accessed.
The global variable is not accessible to functions until you make it so. Eg:
function debug($msg( {
global $debug;
etc...
PS: Please, don't do this. Find a better way. Really.
$debug is your global variable, so it is not accessible in your function
There is also the possibility to declare a const, (and then just insure the namespace is correct), like this:
const debug = true;
function newPrint($msg) {
if (\debug === true) {
echo $msg;
} else {
return false;
}
}
\newPrint("heey");//will print "heey"
so just dont use a variable, but use a const.

PHP: testing session

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.

Categories