XAMPP php executing both if and else parts - php

It is strange. My php code is executing both if and else parts. Following code starts where $_SESSION['abc'] is not set yet.
//echo $_SESSION['abc'];
if(!isset($_SESSION['abc'])){
echo "not showing this echo";
$_SESSION['abc'] = "new";
} else {
echo " why it jumps here, in XAMPP?";
}
My actual code was more complex so I did it simpler as above. The above code is not echoing "not showing this echo"; even when $_SESSION['abc'] is not set. If I comment out the statement $_SESSION['abc'] = "new"; it echoes "not showing this echo".
What I found out by now:
It is happening only in XAMPP, at production server same is working fine.
It happens when I make the else condition true in the if block. And that condition is setting a session variable.
I myself thought the code is executing twice or something but it is not.
And more importantly "if" condition is true, if you uncomment first line echo $_SESSION['abc'];, it will show undefined index error.
The weirdest feeling for me is, when it reaches $_SESSION['abc'] = "new"; in "if" block, it jumps to "else", ignoring the echo line before it.
Weird!! Am I missing something or it is a XAMPP bug. Yes, the code is working as expected, on production server.
EDIT:
I would like to add that only for this behavior I also reinstalled XAMPP (for the latest version).
And as to "how do I know if it sets session variable, while not echo the line before it", it prints echo $_SESSION['abc']; in else-block, but it shows undefined index error if I uncomment first line echo $_SESSION['abc'];
Code with echo line added in else-block.
//echo $_SESSION['abc'];
if(!isset($_SESSION['abc'])){
echo "not showing this echo";
$_SESSION['abc'] = "new";
} else {
echo " why it jumps here, in XAMPP?";
echo $_SESSION['abc'];
}
UPDATE 2018-06-03
I was doing the above code in Laravel. I tried the above code out of Laravel framework in a plain PHP file and it worked in XAMPP, as it should. So the new information is, this is not working in Laravel-XAMPP combination. Versions: Laravel 5.4 and XAMPP 7.2.5
NOW??

I'm not sure what you want to achieve. It looks like you are testing $_SESSION before you assign a value to your session key.
Do a print_r ($_SESSION) to become clear when which value is assigned. And which value is stored after you reload your session. You can also printout your statement to see the result like echo (!isset(value)) as an example.
session_start ();
print_r ($_SESSION);
if (!isset ($_SESSION ['whatever'])){
echo "not set";
print_r ($_SESSION);
}
else {
echo "set";
print_r ($_SESSION);
}
Also try to change the first statement to be true if set and assign your new value in the else block
session_start ();
print_r ($_SESSION);
if (isset ($_SESSION ['whatever'])){
echo "set";
print_r ($_SESSION);
}
else {
echo "not set";
print_r ($_SESSION);
$_SESSION['whatever'] = "new value";
}
Hopefully it helps to find the faulty place
Edit
Be sure to use
session_start()
at very first line
or to set
session.auto_start = 1
in your php.ini

Related

Store time in a session

I have a code that works just fine but I have a few questions about it. I don't understand the logic of something. The code is:
<?php
session_start();
if(!isset($_SESSION['t0']))
{
$_SESSION['t0']=time();
echo $_SESSION['t0']."if<br />"; //why this is never printed?
}
else
{
if(time()>=($_SESSION['t0']+3))
{
echo $_SESSION['t0']."else-ul";
$culoare="rgb(".rand(0,255).",".rand(0,255).",".rand(0,255).")";
$_SESSION['t0']=time();
}
}
?>
The questions would be:
1. Why the first echo is never printed?
2. Why (time()>=($_SESSION['t0']+3)) isn't always true since $_SESSION['t0'] is updated every second because of session[t0]=time() ?
Thank you!
First echo statement does get executed, but it happens only on very first time. Once you had your session started value for $_SESSION['t0'] is always set, so the if condition will always return false.
time()>=($_SESSION['t0']+3) condition is true when 3 seconds has passed after execution of the code. So if you reload your page after 2 seconds it will not get executed.

Only one line executed in a false IF - PHP

I'm integrating pagination to a wordpress block, what should happen is whenever i click "older posts" button, the post offset is incremented in another php file (the block file and the increment files are separate files).
Whenever I click the older posts however some magic happens that shouldn't:
The problem is with one of the if statements, what happens is that IF statement evaluates to false, yet that one line that I marked in the code still gets executed (the echo doesn't execute but the $_SESSION["inf"] = 0; does).
Here is the code.
if(isset($_POST["paginate_btn"])){
if(isset($_SESSION["inf"])){
echo "PREVIOUS:".(string)($_SESSION["inf"]);
$_SESSION["inf"] = $_SESSION["inf"] + 5;
echo "<br/> incremented by 5, RESULT:".(string)($_SESSION["inf"]);
}
else{
echo "<br/> isset session inf failed, set to 5";
$_SESSION["inf"] = 5;
}
}
else if(isset($a) and ($a != $url)){
echo "<br/>dif page";
if(isset($_SESSION["inf"])){
echo "<br/> unset";
$_SESSION["inf"] = 0; <----- THIS LINE HERE!
}
else{
echo "<br/>session inf not set and button not pressed";
}
}
else{
echo "<br/> button not pressed, a is not set and is same page";
$_SESSION["inf"] = 0;
}
I've messed around with this for hours and hours, I don't understand what the case is here..
var_dump((isset($a) and ($a != $url)));evaluates false, yet still only that one line of code there gets executed, the echo doesn't, not even the dif page echo before it....
And the funny part, if I comment out that one line, this no longer happens, I've even tried setting it to different variables there so it definitely gets run solo somehow.
Var_dump code after the if statements.
echo "<br/>--1---<br/>";
var_dump((isset($a) and ($a != $url)));
echo "<br/>--2---<br/>";
var_dump((isset($_SESSION["inf"])));
echo "<br/>---<br/>";
echo $_SESSION["inf"];
echo "<br/>---<br/><br/>";
Another part of the code sets $_SESSION["inf"] to 0.
If you don't see the echos, they don't get executed.

How to use $GLOBALS to share variables across php files?

I have a file, index.php that produces a link to a page that I want my user to only be able to access if some $var == True.
I want to be able to do this through the $GLOBALS array, since my $_SESSION array is already being filled with instances of a specific class I want to manipulate further on.
My index.php page:
<?php
$var = True;
$GLOBALS["var"];
echo "<p><a href='next.php'>Click to go to next page</a></p>";
?>
My next.php page:
<?php
if($GLOBALS["var"] == False)
exit("You do not have access to this page!");
else
echo "<p>You have access!</p>";
?>
Currently, next.php is echoing the exit text. Am I accessing/assigning to the $GLOBALS array correctly? Or am I not using it properly?
Thanks!
EDIT:
So I've tried some of the suggestions here. This is my new index.php:
<?php
$GLOBALS["var"] = True;
echo "<p><a href='next.php'>Click to go to next page</a></p>";
?>
My next.php:
<?php
if($GLOBALS["var"] == False)
exit("You do not have access to this page!");
else
echo "<p>You have access!</p>";
?>
However, I'm still running into the same issue where the exit statement is being printed.
It's much better to use sessions for this, since they are more secure and exist for this purpose. The approach I would recommend, is starting a new separate session array.
session_start();
$_SESSION['newSession']['access'] = true;
Then to access it use the same key/value.

else if - what am I doing wrong?

I have the following code which I use in conjunction with a members script which displays a members username the page or asks guests to login or register.
PHP code:
if ($_SESSION['username'])
{
echo "".$_SESSION['username'].", you are logged in.<br><small>Click here to logout</small>";
}
else
echo "Welcome Guest!<br><small>Login or Register</small>";
It works perfectly well, though now I want to modify it so if a user with admin privileges logs in it identifies the username and offers a link to the admin page.
So here's my modified code:
<? php
$validateadmin = $_SESSION['username'];
if ($validateadmin == "admin1" or $validateadmin == "admin2")
{
echo "Hello $validateadmin, you have admin privileges.<br><small>Click here to logout</small>";
}
else if ($_SESSION['username'])
{
echo "".$_SESSION['username'].", you are logged in.<br><small>Click here to logout</small>";
}
else
{
echo "Welcome Guest!<br><small>Login or Register</small>";
}
?>
Any idea's what I'm doing wrong? It either leaves me with a blank page or errors.
I know it's probably a newbie error but for the life of me I don't know what's wrong.
Generally you should use elseif in php not "else if" because the php parser will interpret else if as else { if { .... }} and you can have some weird errors.
Also, it is a great practice to ALWAYS use braces with control statements to avoid dangling clauses.
Also to avoid notices about array indexes don't do checks like if($array[$index]) if the index may not exist. Use any of array_key_exists, isset, empty, etc (they all are slightly different) to check if an array contains a key you are looking for.
try the following
<?php #removed space
session_start(); #you will need this on all pages otherwise remove it if already called
$validateadmin = $_SESSION['username'];
if($validateadmin == "admin1" || $validateadmin == "admin2"){
echo "Hello $validateadmin, you have admin privileges.<br><small>Click here to logout</small>";
}elseif(isset($_SESSION['username'])){ #you should use isset to make sure some variable is set
echo $_SESSION['username'].", you are logged in.<br><small>Click here to logout</small>";
}else{
echo "Welcome Guest!<br><small>Login or Register</small>";
}
?>

Session-cookies: Weird Behaviour? Or Have I not understood something here?

Here is the piece of code:
session_name('somename');
session_start();
echo 'session name:'.session_name();
The above does print the session name as somename.
If I append the code below,
if(isset($_COOKIE['somename'])) {
echo "<br/><br/>"."Cookie somename not yet set";
}
else {
echo "<br/><br/>".var_dump($_COOKIE['somename']);
}
The output is always
Cookie somename not yet set.
Am I using the isset function wrong?
If I just append this:
echo "<br/><br/>".var_dump($_COOKIE['somename']);
Then, the output for the first time is:
session name:somename
Notice: Undefined index: somename in /path/to/file.php on line 12 NULL
If I refresh the page, then the output is
session name:somename
string(26) "367jr029jj17mdu5fgkfgiv0u6"
Isn't the cookie variable supposed to get set before the page content is loaded? or Have I not understood sessions/cookies?
Expanding on Jani Hartikainen's answer
isset() checks to see if $_COOKIE['somename'] is set.
First time through before cookies are set:
// $_COOKIE['somename'] is NOT set so skip to else
if(isset($_COOKIE['somename'])) {
echo "<br/><br/>"."Cookie somename not yet set";
}
else {
// $_COOKIE['somename'] is NOT set so you get an error.
echo "<br/><br/>".var_dump($_COOKIE['somename']);
}
Second time through after cookies are set:
// $_COOKIE['somename'] is set so show message
if(isset($_COOKIE['somename'])) {
echo "<br/><br/>"."Cookie somename not yet set";
}
else {
// $_COOKIE['somename'] is set so skip this part.
echo "<br/><br/>".var_dump($_COOKIE['somename']);
}
A more appropriate use of isset would be something like:
if(isset($_COOKIE['somename'])) {
echo "<br/><br/>".var_dump($_COOKIE['somename']);
}
else {
echo "<br/><br/>"."Cookie somename not yet set";
}
In the last example I use isset to determine if $_COOKIE['somename'] has been set. If so, then I dump it; otherwise, I show the message “Cookie somename not yet set”
Cookies aren't set into $_COOKIE until the browser actually sends them.
It works something like this:
Request 1:
Your script starts
$_COOKIE is empty
session_start()
Your script ends
-> cookies to browser
Request 2:
<- browser sends cookies in request
Your script starts
$_COOKIE contains your cookie
...

Categories