0

I have a form that posts some variables with jquery. I'm having trouble getting the php that processes the form to work as intended and can't figure out what I'm doing wrong.

I want the form to do different things depending on the value of the btn variable but if the user is not logged in (user_session is empty) then a message is returned telling them so. What have I got wrong here?

<?php
session_start();
//Check session is set
if(isset($_SESSION['user_session']) && !empty($_SESSION['user_session'])) { 
    $btn=$_POST['btn']; //Get btn name from form
    if ($btn=="btn_follow") {
        //Do something
    }
    elseif ($btn=='btn_unfollow') {
        //Do something else
    }
echo "You need to be logged in";
}
?>
Ricardo Nuñez
  • 989
  • 1
  • 13
  • 17
JulianJ
  • 1,259
  • 3
  • 22
  • 52
  • isset() and !empty() are redundant, they both check if the value is is defined and not null, empty also checks if the value is loosely equated to false. So depending on your requirements, you only need one or the other. – Devon Bessemer Dec 19 '16 at 18:18
  • where did you set sessions values? – harrrrrrry Dec 19 '16 at 18:18
  • Quite right, I forgot to put it here but it is in the original script. – JulianJ Dec 19 '16 at 18:18
  • 3
    What issue are you having exactly? As a note, you have "You need to be logged in" echoing if the user_session exists. I'm guessing you want that as an `else` condition. – aynber Dec 19 '16 at 18:20
  • I was just about to write what @Dolfa said. Your missing the else statement – Jorn Dec 19 '16 at 18:33

1 Answers1

2

I think you want to do:

<?php
session_start();
//Check session is set
if(isset($_SESSION['user_session']) && !empty($_SESSION['user_session'])) { 
    $btn=$_POST['btn']; //Get btn name from form
    if ($btn=="btn_follow") {
        //Do something
    }
    elseif ($btn=='btn_unfollow') {
        //Do something else
    }
}else{
    echo "You need to be logged in";
}
?>
Dolfa
  • 796
  • 4
  • 21
  • Probably not necessary, he is checking against a value, worst what could happen is that $btn would be null. I don't expect there would be an issue in here. There is similar question here http://stackoverflow.com/questions/7261117/is-there-any-benefit-of-using-null-first-in-php if null should be used on left side of equality condition – Dolfa Dec 19 '16 at 18:58
  • 1
    if it isn't set then you end up with notices about undefined variables - not really an issue since the error message will end up being assigned to a variable as a string. Personally I don't like lazy code that avoids doing things the Right Way because it works anyhow... – ivanivan Dec 19 '16 at 19:02