Search code examples
phpformssessionpoststrpos

php conditional strpos check cant set session variable


Please explain why I cannot get the session variable for "Pistol" to set or $_SESSION['reported'], but it works fine for "Rifle"

THE FORM THAT POSTS THE DATA

<form name="<?=$prodadd?>" id="<?=$prodadd?>" method="post" action="process.php">
<input type="hidden" name="formid" value="addtocart" />
<!-- other input fields here -->
<input type="hidden" name="type" value="<?=$row['Type']?>" />
<input type="hidden" name="weight" value="<?=$row['Weight']?>" />
<!-- other input fields here --> 
</form>

THE SIMPLE CHECK IN process.php TO SET THE SESSION VARIABLE:

if (strpos($_POST[type],"Pistol")) {
session_start();
$_SESSION['pwght'] = $_SESSION['pwght'] + $_POST['weight'];
session_write_close();}

else if (strpos($_POST[type],"Rifle")) {
session_start();
$_SESSION['rwght'] = $_SESSION['rwght'] + $_POST['weight'];
session_write_close();}

$_SESSION['reported'] = $_POST['weight'];

WHAT I HAVE DONE AND TRIED:

I have looked in the Database after both a Rifle item and a Pistol item was sent through the form. Other than normal product differences they are the same. I have checked and verified that in both cases the data is being written to the database and is not blank or missing. I have changed the order of in which the if/else if is performed with same results. I have changed the name of the session names with no change in problem. No matter what I do I cannot get it to set the $_SESSION['pwght'] or $_SESSION['reported']


Solution

  • From the manual for strpos

    Warning

    This function may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE. Please read the section on Booleans for more information. Use the === operator for testing the return value of this function.

    In other words, you want to check whether it returns the boolean false, but not anything else that would evaluate to false when cast to boolean (in this case 0, it matches at the very first character). This is done by:

    if(strpos($haystack,$needle)!==false)