0

I know this question has been asked many times before over the years. However, I am facing the wall after attempting to correctly implement all the potential solutions that others have listed in this post: "https://stackoverflow.com/questions/17242346/php-session-lost-after-redirect".

I know my session variables exist before using "header("location: nextPage.php");" to redirect. As soon as I put the line in the code, the session variables disappear. I am posting all my code because I did tried all the solutions I have seen. So maybe, the problem is my code and someone can find what I am doing wrong.

Thank you in advance.

<?php
session_save_path('/home/myHome/cgi-bin/tmp');
session_start();

$fnameErr = $lnameErr = $ssnErr = $dofbErr = $occpErr = $filstatErr = "";
$fname = $mname = $lname = $ssn = $dofb = $occp = $filstat = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    global $fnameErr, $lnameErr;
    if (empty($_POST["fname"])) {
        $fnameErr = "Your first name is required";
    } else {
        $fname = test_input($_POST["fname"]);
        // check if name only contains letters and whitespace
        if (!preg_match("/^[a-zA-Z-' ]*$/",$fname)) {
            $fnameErr = "Only letters and white space allowed";
        }
    }
    
    if (empty($_POST["lname"])) {
        $lnameErr = "Your last name is required";
    } else {
        $lname = test_input($_POST["lname"]);
        // check if name only contains letters and whitespace
        if (!preg_match("/^[a-zA-Z-' ]*$/",$lname)) {
            $lnameErr = "Only letters and white space allowed";
        }
    }
    
    if (empty($_POST["ssn"])) {
        $ssnErr = "Your social security number is required";
    } else {
        $ssn = test_input($_POST["ssn"]);
        // check if name only contains letters and whitespace
        if (!preg_match("/[0-9]{3}-[0-9]{2}-[0-9]{4}/",$ssn)) {
            $ssnErr = "There is an error in your social security number";
        }
    }
   
    if (empty($_POST["dofb"])) {
        $dofbErr = "Your date of birth is required";
    } else {
        $dofb = $_POST["dofb"];
    }
    
    if (empty($_POST["occp"])) {
        $occpErr = "Your occupation is required";
    } else {
        $occp = test_input($_POST["occp"]);
    }
    
    if (isset($_REQUEST["filstat"]) && $_REQUEST["filstat"] == "disabled selected hidden") {
        $filstatErr = "Your filing status is required";
    } else {
        $filstat = test_input($_POST["filstat"]);
    }
  
    if(isset($_POST['next'])){        
         if ($fnameErr == "" && $lnameErr == "" && $ssnErr == "" && $dofbErr == "" && $occpErr == "" && $filstatErr == "") {
         session_write_close();
         header("location: nextPage.php");
         exit();
         }
    }
}

function test_input($data) {
    $data = trim($data);
    $data = stripslashes($data);
    $data = htmlspecialchars($data);
    return $data;
}

?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8" name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="style.css">
    <script src="https://kit.fontawesome.com/1bd5f284bd.js" crossorigin="anonymous"></script>
    <title>Welcome</title>
</head>
<body>

<div class="grid-container">
<div class="header">
   <h1>someTitle</h1>&nbsp;<h5>subTitle</h5>
</div>

   <div class="menu">
      <ul>
         <li><a class="active" href="index.php"><i class='fas fa-user-alt'></i>Personal Info</a></li>
         <li><a href="emp_w2.php"><i class='fas fa-city'></i>W-2 Employer info</a></li>
         <li><a href="tp_w2.php"><i class='fas fa-dollar-sign'></i>W-2 Earned Income</a></li>
         <li><a href="tp_cash.php"><i class='fas fa-hand-holding-usd'></i>Cash Income</a></li>
         <li><a href="summary.php"><i class='fas fa-book-reader'></i>Review</a></li>
         <li><a href="insert_data.php"><i class='fas fa-upload'></i>Submit</a></li>
      </ul>
   </div>
 
   <div class="main">
      <h2>Please complete your personal information below</h2>

      <p class="error">* required field</p>     
      <form  action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post">

         <label for="fname">First Name:<span class="error"> * <?php echo $fnameErr;?></span></label>
         <input type="text" id="fname" name="fname" maxlength="40" placeholder="Your name.." value="<?php echo $fname; ?>">

         <label for="mname">Middle Initial:</label>
         <input type="text" id="mname" name="mname" maxlength="1" value="<?php echo $mname; ?>">

         <label for="lname">Last Name:<span class="error"> * <?php echo $lnameErr;?></span></label>
         <input type="text" id="lname" name="lname" maxlength="50" placeholder="Your last name.." value="<?php echo $lname; ?>">    
  
         <label for="ssn">Social Security Number:<span class="error"> * <?php echo $ssnErr;?></span></label>    
         <input type="text" id="ssn" name="ssn" minlength="9" maxlength="11" placeholder="000-00-0000" value="<?php echo $ssn; ?>" onBlur = "myFunc()">
         
         <label for="dofb">Date of Birth:<span class="error"> * <?php echo $dofbErr;?></span></label>
         <input type="date" id="dofb" name="dofb" maxlength="10" min="1930-01-01" max="2000-12-31" value="<?php echo $dofb; ?>">

         <label for="occp">Occupation<span class="error"> * <?php echo $occpErr;?></span></label>
         <input type="text" id="occp" name="occp" maxlength="40" placeholder="Your principal work" value="<?php echo $occp; ?>">

         <label for="filstat">Filing Status:<span class="error"> * <?php echo $filstatErr;?></span></label>
           <select id="filstat" name= "filstat" required>
               <option value="disabled selected hidden">Choose Filing Status</option>
               <option value="Single">Single</option>
               <option value="Married filing jointly">Married filing jointly</option>
               <option value="Head of Household">Head of Household</option>
           </select>

       <input type="reset" value="Reset">    
       <input type="submit" name="next" value="Next">    

    </form>
   </div>

   <div class="instructions">
      <h2>Help Center</h2>
      <p>Instructions to what needs to be done go here.</p>
   </div>

   <div class="footer">
      <p>&#169; Copyright 2020–2021 websiteName &#174; All rights reserved</p>
   </div>
</div>

<script type="text/javascript">
function myFunc() {
       var patt = new RegExp("\d{3}[\-]\d{2}[\-]\d{4}");
       var x = document.getElementById("ssn");
       var res = patt.test(x.value);
       if(!res){
        x.value = x.value
            .match(/\d*/g).join('')
            .match(/(\d{0,3})(\d{0,2})(\d{0,4})/).slice(1).join('-')
            .replace(/-*$/g, '');
       }
    }


</script> 

</body>
</html>
mshifu
  • 9
  • 2
  • 2
    make sure you use `session_start();` on the page you re-directed to. – Erik Sep 09 '21 at 02:47
  • Thank you Erik. session_start(); is on the page I have re-directed to. It is the very first line in that page. Note that if I redirect to this same page, the variables are also lost but only if I use header. – mshifu Sep 10 '21 at 19:35
  • Hi @mshifu, Welcome to SO! Please take the [tour](https://stackoverflow.com/tour), read the [help center](https://stackoverflow.com/help), and [how-to-ask](https://stackoverflow.com/help/how-to-ask) page. I don't see any `$_SESSION[]` variables here. Can you please include the code where you save the sessions? also when you try to retrieve the session value? – NcXNaV Sep 10 '21 at 20:19
  • Thank you @NcXNaV. For full disclosure, this page contains most of what I know about php. You are right, I do not have $_SESSION[] variables. What I am trying to move forward is the input capture through POST until the last page where I enter the values in mysql. – mshifu Sep 11 '21 at 02:10
  • I have been calling this variables with `foreach ($_POST as $key => $value) { $_SESSION['post'][$key] = $value; echo $_SESSION['post'][$key];` I used the echo to see if the variables are there. This worked like a charm...until this header redirection I used because of the input tests. – mshifu Sep 11 '21 at 02:17
  • What I had not done before, but I just did, was to test on my local apache server if the code would work. Some people have reported that locally the code worked but not on the remote server. Mine did not work. I am running macOS BigSur. – mshifu Sep 11 '21 at 02:20
  • Anybody out there?? – mshifu Sep 17 '21 at 00:59
  • Hi @mshfu. Have you try to check all these? [PHP session lost after redirect](https://stackoverflow.com/questions/17242346/php-session-lost-after-redirect) – NcXNaV Sep 17 '21 at 04:15
  • Sorry, I have not had a chance to come back to this project until today. Thanks for the suggestion @NcXNaV, but I have tried all of them. Today, I will strip the code to the bare minimum to see if there is an error somewhere and I have not seen it. If it does not work I will go through all those steps once again. Also, I am working on my local apache server. I do not know if that will make a difference. – mshifu Oct 20 '21 at 16:49

0 Answers0