PHP IF Statement Problems With isset & !empty - php

I am just stuck today at a wall of confusion and I'm hoping someone will be able to assist :)
I have a database full of basic projects, and within that table are attributes like Project Name, Project Number, Project Image, etc. I am able to enter new projects / display existing projects / etc. without issue.
My problem seems to come up when I want to Edit a project. My thoughts were that I would have to create an IF statement to find out if there's a new file uploaded or not, and either set the new file name in the database if there is, or keep the old in the database if there isn't.
I've been playing around with this for days, and I think I started off a bit too far ahead of myself. I've started breaking down to basics and I'm getting stumped with my IF statement, it feels like it's backwards? Does this make sense?
Examples:
if (isset($_COOKIE["OldProjectImage1"])){$OldProjectImage1 = $_COOKIE["OldProjectImage1"];}
if(isset($OldProjectImage1)){
echo 'Your Browser Cookies are not enabled';
} else if(isset($_FILES['ProjectImage1']['name'])){
echo 'Image1 FILES isset';
} else if(!empty($_FILES['ProjectImage1']['name'])){
echo 'Image1 FILES empty';
}
Now in searching StackExchange I found that we have to do the statement on the COOKIE portion instead of the Variable as I did above, but it also similarly fails.
if (isset($_COOKIE["OldProjectImage1"])){$OldProjectImage1 = $_COOKIE["OldProjectImage1"];}
if(!empty($_COOKIE['OldProjectImage1'])){
echo 'Your Browser Cookies are not enabled';
} else if(isset($_FILES['ProjectImage1']['name'])){
echo 'Image1 FILES isset';
} else if(!empty($_FILES['ProjectImage1']['name'])){
echo 'Image1 FILES empty';
}
And I've also tried with isset
if (isset($_COOKIE["OldProjectImage1"])){$OldProjectImage1 = $_COOKIE["OldProjectImage1"];}
if(isset($_COOKIE['OldProjectImage1'])){
echo 'Your Browser Cookies are not enabled';
} else if(isset($_FILES['ProjectImage1']['name'])){
echo 'Image1 FILES isset';
} else if(!empty($_FILES['ProjectImage1']['name'])){
echo 'Image1 FILES empty';
}
I've tried both with my script, and they're both behaving similarly. Perhaps I am just confused at the overall process?
When I run my tests with and without cookies enabled, it always seems to skip the first part of the IF statement (with both isset and !empty) and jump to the next section. Then, similarly, it feels like the IF statement is backwards (if that makes any sense) - if I set a file to upload which populates ProjectImage1, I get "Image1 FILES empty". If I set no file to upload and submit the form, I get "Image1 FILES isset".
I thought it would essentially be, in plain English,
If cookie is empty then echo "Your Browser Cookies are not enabled"
Else if ProjectImage1 Name is set, echo "Image1 FILES isset"
Else if ProjectImage1 Name is Empty, echo "Image1 FILES empty"
but it's feeling to me like it's backwards? Am I understanding this wrong?
Thanks in advanced for any responses!

Problem lays with:
if(isset($_COOKIE['OldProjectImage1'])){
echo 'Your Browser Cookies are not enabled';
}
You check if the cookie exist, and if it does, then you say that cookies are not enabled. A bit weird. Add ! before the isset. Then the if-statement and the text are correct.
I think, but I can only assume, you want this in the end:
if (isset($_COOKIE["OldProjectImage1"])){
// I believe the variable below can also be put between the else { and } down below
$OldProjectImage1 = $_COOKIE["OldProjectImage1"];
}
if(!isset($_COOKIE['OldProjectImage1'])){
echo 'Your Browser Cookies are not enabled';
} else if(!isset($_FILES['ProjectImage1']['name'])){
echo 'Image1 FILES is not set';
} else if(empty($_FILES['ProjectImage1']['name'])){
echo 'Image1 FILES is empty';
}else {
// upload file here
}

I think you want to check the browser cookie is enabled or not?
Detect if cookies are enabled in PHP
Answer by Shiplu Mokaddim:
session_start();
if (isset($_GET['check']) && $_GET['check'] == true) {
if (isset($_COOKIE['foo']) && $_COOKIE['foo'] == 'bar') {
// cookie is working
// get back to our old page
header("location: {$_SESSION['page']}");
} else {
// show the message "cookie is not working"
}
} else {
// save the referrer in session. if cookie works we can get back to it later.
$_SESSION['page'] = $_SERVER['HTTP_REFERER'];
// set a cookie to test
setcookie('foo', 'bar', time() + 3600);
// redirecting to the same page to check
header("location: {$_SERVER['PHP_SELF']}?check=true");
}
Detect cookie in Javascript
Check if cookies are enabled
So, combine with your code and my own explanation:
<?php
session_start();
//check if a cookie test is started
if (isset($_GET['check']) && $_GET['check'] == true) {
//cookie test is started
if (isset($_COOKIE['foo']) && $_COOKIE['foo'] == 'bar') {
//cookie test success, go back to the previous page
header("location: {$_SESSION['page']}");
} else {
//cookie test fail, echo the message and continue
echo 'Your Browser Cookies are not enabled';
}
} else {
//start cookie test if a cookie test wasn't done
//check if a cookie test was done.
if (!isset($_COOKIE['foo']) && $_COOKIE['foo'] == 'bar') {
//start a cookie test if a cookie test wasn't done
$_SESSION['page'] = $_SERVER['HTTP_REFERER'];
setcookie('foo', 'bar', time() + 3600);
header("location: {$_SERVER['PHP_SELF']}?check=true");
}
}
if(!isset($_COOKIE['OldProjectImage1'])){
echo "OldProjectImage1 doesn't exists in cookies.";
} else if(!isset($_FILES['ProjectImage1']['name'])){
echo "Image1 FILES is not set";
} else if(empty($_FILES['ProjectImage1']['name'])){
echo "Image1 FILES is empty";
}
?>

Related

Why my cookies are not saving?

I have a problem with cookies. In my login script i have the following line of code:
if($_GET['keep'] == "true"){
setcookie('id',$id,time()+3153600);
}
The problem I'm facing is that the cookies are not saving at all ( not even if i don't quit the browser). I'm quite a beginer in this respect and I think I'm not doing it right.
EDIT:
If i print_r all the Cookies it only gives me PHPSESSID after the cookie is set. I printed on index.php and i set the cookie on login.php
SOLUTION: Cookies are saved by default with the path of the file they were created in. To change the path there is another atribute. So by setcookie('id',$id,time()+3153600,'/'); you make the cookie available for the entire domain.
There is no issue in your code
if($_GET['keep'] = "true"){
setcookie('id',$id,time()+3153600);
}
This will may cause to
No data passing to $_GET['keep']
Or if data passing $_GET['keep'] value in not Matched ("true").
Both Works then $id is empty in setcookie method
Improve your code
if(isset($_GET['keep']){
if($_GET['keep'] == "true"){
if(isset($id))
{
#all perpect
$cokkie_id = 'id';
setcookie('id',$id,time()+3153600);
echo "I'm Set. And My value is ".$cokkie_id;
}
else
{
echo "Opzz My ID is also empty";
}
}
else
{
echo 'Get method is Set. But Value is not "true". Actual value is '. $_GET['keep'];
}
}
else
{
echo 'I cant reach Get method Buddy';
}
I think you miss "=" sign
if ($_GET['keep'] == "true") {
if (!isset($_COOKIE['id'])) {
setcookie('id',$id,time()+3153600);
}
}
use isset or ==
if (isset($_GET['keep']) && $_GET['keep'] == "true") {
setcookie('id', $id,time()+3153600);
}else{
echo 'keep is empty';
}

Infinite redirect loop from PHP code in Wordpress

I have a PHP script which I will post below. It is a voting website, and my client only wants one user to be able to vote once based on their cookies and IP address.
After voting once, if the cookie or IP is detected as the same they are redirected to a fake voting pg which allows multiple votes. The browser loops between both the legal and duplicate vote pages.
Here is the code, I only added in the exit and die functions after getting this error and seeing online that might be the cause - however adding those functions made no difference.
$q = mysql_query("SELECT * FROM votelog");
while($row = mysql_fetch_array($q))
{
if(($ip = $_SERVER['REMOTE_ADDR']) == $row['ip'])
{
$duplicateIP = true;
}//end if
if(($row['pollid'] == 8))
{
$duplicatePoll = true;
}//end if
}//end while
//check cookies
if(isset($_COOKIE['poll']))
{
$cookieCheck = true;
}//end if
if((($duplicateIP == true) && ($duplicatePoll == true)) or ($cookieCheck == true))
{
show this pg
}//end if
else
{
echo '<meta http-equiv="refresh" content="0; url=/polls/legit" />'; //redirect to legal pg
exit();
die();
}//end else
Any ideas? The other page is the same except that the if and else are switched, like this:
if((($duplicateIP == true) && ($duplicatePoll == true)) or ($cookieCheck == true))
{
echo '<meta http-equiv="refresh" content="0; url=/polls/dupe" />'; //redirect to duplicate
exit();
die();
}//end if
else
{
show this pg
}//end else
P.S - I'm operating in a Wordpress environment
It is hard to guess whats going on there. But if your code is fine, i would expect that you have an caching issue.
Setting the headers (header()) correct, would help to solve that issue. But be carefull, you can make it more worse with setting wrong headers.
So an easy workaround could be to add an ?time() to your url. So the redirected URL would change each second.
echo '<meta http-equiv="refresh" content="0; url=/polls/dupe?'.time().'" />'; //redirect to duplicate
Just a side note:
exit();
die(); // this will never reached, as exit() and die() is the same
About exit() and die()

php message using sessions

I am try to develop flash message using sessions in php
suppose on successfully delete query I am setting
$_SESSION["msg"]="record deleted successfully";
header("location:index.php");
and I have the following script on all pages which checks if msg variable is available it echo its value as below
if(isset($_SESSION["msg"]) && !empty($_SESSION["msg"]))
{
$msg=$_SESSION["msg"];
echo "<div class='msgbox'>".$msg."</div>";
unset($_SESSION['msg']); //I have issue with this line.
}
if I comment
unset($_SESSION['msg']);
message is being displayed, but with this line message is not being displayed
what am I doing wrong, or any alternative.
You are saying that you have that script on every page. So my guess is that after you make header("location:index.php"); your code continues to run - your message is displayed and unset (you don't see it because of redirect to index.php). When you are redirected to index.php your message is already unset.
Try adding exit; after header("location:index.php");.
Edit: I will add two examples with one working and one not. To test you need access test page with following link - /index.php?delete=1
In this example you will never see message. Why? Because header function does not stop code execution. After you set your session variable and set your redirect your code continues to execute. That means your message is printed and variable unset too. When code finishes only than redirect is made. Page loads and nothing is printed because session variable was unset before redirect.
<?php
session_start();
// ... some code
if ($_GET['delete']==1) {
$_SESSION["msg"] = "record deleted successfully";
header("location: index.php");
}
// ... some code
if (isset($_SESSION["msg"]) && !empty($_SESSION["msg"])) {
$msg = $_SESSION["msg"];
echo "<div class='msgbox'>" . $msg . "</div>";
unset($_SESSION['msg']);
}
// ... some code
?>
But this code probably will work as you want. Note that I have added exit after header line.
You set your message, tell that you want redirect and tell to stop script execution. After redirect your message is printed and unset as you want.
<?php
session_start();
// ... some code
if ($_GET['delete']==1) {
$_SESSION["msg"] = "record deleted successfully";
header("location: index.php");
exit;
}
// ... some code
if (isset($_SESSION["msg"]) && !empty($_SESSION["msg"])) {
$msg = $_SESSION["msg"];
echo "<div class='msgbox'>" . $msg . "</div>";
unset($_SESSION['msg']);
}
// ... some code
?>
You clearly said that you have that code (message printing) on all pages. If your code is similar to my example than adding exit should fix your problem.
Another problem might be that you are doing more than one redirect.
You can simply set your session empty or null instead of unset it. Just do:
$_SESSION['msg']=NULL;
Or
$_SESSION['msg']="";

Page Does Not Recognize SESSION

I have come along something i could not solve for so long.
i have created a script in php that unsets one single session variable, However the page stats the session Here is my code for the page :
<?php
session_start();
require_once("../header.php");
if($_SESSION['user']) {
unset($_SESSION['user']);
echo "you succesfully logged out.";
header("Refresh:5; url=http://www.webmasteroutlet.com");
} else {
echo "you are already NOT LOGGED IN right now.";
}
require_once("../footer.php");
?>
That is the whole code on this page. and it always prints out "you are already NOT LOGGED IN right now." $_SESSION['user'] is assigned true in login.php page and i have session_start(); at the very beginning of the page right after the <?php opening.
The session variable is recognized at all other files with php extension and that is the only single file that it is not working on. I also tried
<?php
session_start();
echo $_SESSION['user'];
?>
and it does not print anything. It simply skips that line and does nothing. What am i doing wrong ?
Thank You very much for your help.
this is the header.php code
<?php
session_start();
require("config.php"); // that only contains connection to the database and it is successful.
if(isset($_SESSION['user'])==1){
echo "<div id=\"topnav\" class=\"topnav\"><span>".$_SESSION['username']."</span> <span>LOGOUT</span></div>";
}
else if ($_SESSION['admin']) {
echo "<div id=\"topnav\" class=\"topnav\">"."<span>".$_SESSION['adminusername']."</span> ";
echo "<span>LOGOUT</span></div>";
}
else if ( !isset($_SESSION['user'])) {
require ($_SERVER['DOCUMENT_ROOT']."/users/login.php");
}
require("search.php");
?>
i think you need the if is set and make sure you pass the sessions data to this page it looks like your unsetting this
Try this:
<?php
session_start();
require_once("../header.php");
if(isset($_SESSION['user'])) {
echo "User.".$_SESSION['user']." you are being logged out";
unset($_SESSION['user']);
header("Refresh:5; url=http://www.webmasteroutlet.com");
} else {
echo "You are not logged or var SESSION doesnt exist";
}
require_once("../footer.php");
?>
If still doesnt work, try deleting the require_once lines(for debug).
Justin, I think you're not setting the $_SESSION['user']. That'd be the reason why you're getting NULL when you vardump.
One other possibility, although I'm limited to the scripts you provided, would be that you made it possible for a person to login through $_SESSION['admin'] as well as $_SESSION['user']. If this is the case you'd have to change the script to:
if(isset($_SESSION['user'])) {
unset($_SESSION['user']);
echo "user succesfully logged out.";
}elseif(isset($_SESSION['admin'])){
unset($_SESSION['admin']);
echo "admin succesfully logged out.";
}else{
echo "you are already NOT LOGGED IN right now.";
}

Check session and cookie not working in PHP

I have this code that makes sure your are logged in, and then making sure you are on the right page by checking a cookie set at login. This code works on a page in a directory underneath the login in script, however in a page in a directory below that it always takes you to accessdenied. Any ideas?
<?php
session_start();
if(!isset($_SESSION['SESS_MEMBER_ID']) || (trim($_SESSION['SESS_MEMBER_ID']) == '')) {
header("location: http://mywebsite.com/member/accessdenied.html");
exit();
}
$_COOKIE["verify"] = $verify;
if( $verify != file_get_contents("name.txt")) {
header("location: http://mywebsite.com/member/accessdenied.html");
} else { }
?>
And it seems like just the bottom part, the part that checks the cookie, isn't working. Again, any ideas?
I think you have your cookie assignment backwards:
$_COOKIE["verify"] = $verify;
Should be
$verify = $_COOKIE["verify"];
And that should be:
$verify = isset($_COOKIE["verify"])?$_COOKIE["verify"]:false;
As if the cookie was not previously set, well it would give a notice error.
<?php
$verify = $_COOKIE["verify"];
if( $verify == file_get_contents("name.txt")) {
echo $verify . 'is equal to the content of name.txt'
} else {
echo $verify . 'is NOT equal to the content of name.txt'
}
?>
Try debugging the code with this. See if the content of your variable is what you want. But I find it unusual that a variable would be a file.
are you sure you always get the content from file_get_contents? I could imagine it's found in one directory but not in the other!
antoher idea: cookies can be set to be relevant for a particular directory only. I just realize, what we're missing here, is the part where you set the cookie in the first place.

Categories