PHP Session variable is not saving

2019-07-21 11:35发布

I've looked through all the problems about the session variable not saving and don't see my problem so I'm going to ask it.

I have a form that once submitted it searches my database for that name. The initial form is on page 1. On page 2 I take the the variable from page 1 and save it like this

    $searchTerm = $_POST['find'];

which is used as the search for the database and it works perfectly. Under that I have my sql statement then I have placed this

    //initialize the session
    if (!isset($_SESSION)) {
      session_start();
    }
    $_SESSION['searchTerm'] = $searchTerm;

I have then tested the $_SESSION['searchTerm'] on page 2 to make sure that it is saving properly, and it does. My issue comes in when I try to go to a 3rd page that is a confirm page for the form from page 2. I have the session start clause at the top of the 3rd page and I even inserted

ini_set('display_errors',1); 
error_reporting(E_ALL); 

to check for errors, no errors were displayed. So my next step was to test the session itself to see if it was refreshing the session id. I found a script on this site www.webassist.com/forums/posts.php?id=5735 to test whether the server could possibly be causing the issue. The script works fine no problems, showing that the server is not the problem. However when I upload my 2nd and 3rd page to the server and put in

    <?php echo session_id(); ?>

the numbers from page 2 and page 3 are completely different therefore making my variable null. I did further research and thought it might be because there was a session_destroy or session_unset but I didn't put one of these on either page. When I tried this on my local machine I got the same session id but still the session variable I set was blank.

Does anyone have any other ideas on how or why this would happen?

**********edit *********************

page 1 has this form

                <form name="search" method="post" action="page2.php">
                    <div>
                    <!-- Search-->
                    <label>Search by Last Name:</label>
                        <div>
                            <table width="100%">
                                <tr>
                                    <td><input type="text" id="" name="find" placeholder=""></td>
                                    <td><button id="submit" type="submit"><span>Search</span></button></td>
                                </tr>
                            </table>
                        </div>
                    </div>
                </form> 

page 2

    $searchTerm = $_POST['find'];


    if(!empty($searchTerm ) && ctype_alpha($searchTerm ))
    {
    $whereclause = "WHERE mytable.lastName = '".$searchTerm ."'";
    }
    else {
    $whereclause = "";
    }

    // sql query is here this one searches it is long and just used the $whereclause above.

    // second sql query that is only submitted if button from the form below is hit is here.

    $insertGoTo = "confirmPage3.php";
      if (isset($_SERVER['QUERY_STRING'])) {
        $insertGoTo .= (strpos($insertGoTo, '?')) ? "&" : "?";
        $insertGoTo .= $_SERVER['QUERY_STRING'] ;

      }
      header(sprintf("Location: %s", $insertGoTo));

    //initialize the session
    if (session_id() == '') {
      session_start();
    }
    $_SESSION['searchTerm'] = $searchTerm;


    // then the form is listed below that with the rest of the html 

page 3

    <?php if(session_id() == '') session_start(); ?> 

    if(!empty($_SESSION['searchTerm']) && ctype_alpha($_SESSION['searchTerm']))
    {
    $whereclause = "WHERE myTable.lastName = '".$_SESSION['searchTerm'] ."'";
    }
    else {
    $whereclause = "";
    }

    // More sql statement here for this one it is only selecting not updating or changing anything.

    // Table below this that is used to hold the items retrieved from the database.

***********edit 2 and my fix**********

so after some back and for with a few of you, Aaron Gong suggested I start with a blank page and go from there. I did this and have finally diagnosed the issue. It was something that I hadn't thought of that I very well should have. I don't like using dreamweaver and now I remember why. When I originally created the page 2 I used dreamweavers insert code to insert my sql statement to do the updating. Well it placed in the code these lines of code.

    $editFormAction = $_SERVER['PHP_SELF'];
    if (isset($_SERVER['QUERY_STRING'])) {
      $editFormAction .= "?" . htmlentities($_SERVER['QUERY_STRING']);
    }

This will completely mess with you if you are trying to send the user to another page to confirm their entries. I commented it out and set the $editFormAction to my page and used that in the header string and viola that immediately fixed my issue. What I hadn't realized is when it was refreshing the page that it was emptying my $_POST variable and found that error finally through the empty pages suggest by Aaron.

Hope this helps someone else and I will never trust the code from dreamweaver again. I learned to code by hand and should know better but I was in a hurry and thought oh it won't harm it.

Thanks again to all your suggestions.

7条回答
对你真心纯属浪费
2楼-- · 2019-07-21 11:49

Not sure what your 3rd page looks like but mine would be:

session_start(); // Use session variable on this page. This function must put on the top of page.

if( isset($_SESSION['i_am_in']) ) echo "logged in";

My Page 2:

if ($login_ok) {
    session_start(); // Create session & settings
    $_SESSION['abc123'] = 'whatever';
    header('Location: page3.php');
}
查看更多
家丑人穷心不美
3楼-- · 2019-07-21 11:57

replace

if (!isset($_SESSION)) {
      session_start();
}

with

session_start();

because $_SESSION is super global and its always available.

OR

Try checking for a specific $_SESSION ex. $_SESSION['session'] rather than just a $_SESSION.

查看更多
啃猪蹄的小仙女
4楼-- · 2019-07-21 11:59

session_start()

That should be right at the top of your scripts. No if statements to determine whether to start it or not.

PAGE 2 In the second script, you have header(sprintf("Location: %s", $insertGoTo)); before you have session_start(). Your session would never start if the header location is changed.

Put session_start() at the top. Do not surround it with the if statement.

PAGE 3 Also put session_start() at the top of the third page, without any if statement. You are not understanding session usage. It's not like a regular function. You must start the session first on every page you want to use it. You can't check for the contents of a $_SESSION variable before you call session_start().

Let me know when you've done that and what the results are.

查看更多
SAY GOODBYE
5楼-- · 2019-07-21 12:01

Page 1 is good, Page 2 and Page 3 should look something like this

PAGE 2

//initialize the session and set are $_SESSION variable from the form data
session_start();
$_SESSION['searchTerm'] = $_POST['find'];

//set where condition and check if $_POST['find'] has a value
$whereclause = "";
if(isset($_POST['find'])) {
    $whereclause = "WHERE mytable.lastName = '".$_POST['find']."'";
}

/*execute your statement note: data passed such as $_GET, $_POST, $_SESSION should never 
be directly in your statement, use PDO to prepare and execute your statements to prevent 
SQL injection*/

//then if you wanted to be redirected to page 3 use header after your statement has executed

header('Location:comfirmPage3.php');

PAGE 3

//initialize the session so we can access our $_SESSION variables
session_start(); 

//set where condition and check is $_SESSION['searchTerm'] has a value
$whereclause = "";
if(isset($_SESSION['searchTerm'])) {
    $whereclause = "WHERE myTable.lastName = '".$_SESSION['searchTerm'] ."'";
}
//execute your statement
查看更多
相关推荐>>
6楼-- · 2019-07-21 12:02

make a call to the session_start() function.

session_start()

This call should be in every script that needs to utilise the session data. For example, if you have a script that creates a CAPTCHA image and needs to store the secret word for the session, you will need to put session_start() at the beginning of the script. If you have another script that takes the user input for the form and checks the secret word entered by the user against what you stored earlier, you will also need to put session_start() in that script.

The function session_start() takes no parameters. It always returns TRUE, so you don't have to bother to check its return value. since session_start() sets a cookie via the HTTP cookie header, you must call it before you output anything from your script. It's best to simply call it at the beginning of your script.

Ending Sessions

session_destroy() is used to destroy the data associated with a session. However, this in itself does not clean up everything. For example, the session cookie is not unset. The $_SESSION array is also still available until your script ends.

To remove the cookie, manually delete it using the usual method one uses to delete a cookie in PHP. To get the name of the cookie to delete, call the session_name() function, which returns a string that is also the name of the cookie set by the PHP session handler.

*example code for how you can clean up after a session can be found in the official PHP manual.

查看更多
够拽才男人
7楼-- · 2019-07-21 12:08
if(session_id() == ''){
    session_start();
}

since $_SESSION is always available.

查看更多
登录 后发表回答