Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

I\'m taking intermediate web programming (PHP). Text book: PHP Programming with

ID: 3678908 • Letter: I

Question

I'm taking intermediate web programming (PHP). Text book: PHP Programming with MySql 2nd Ed. Gosselin Et. al. Having difficulty using $_SESSSION. My problem: Create a set of Web pages that registers users for a professional conference. use a session to track users as they navigate through the Web pages. Include three separate web pages that contain forms: the first form gathers the user's name and contact information, the second form gathers the user's company information, and the third form prompts users to select the seminars they want to attend at the conference. Include a fourth page that displays the submitted information. The fourth page should include links that allow users to edit the submitted data, along with a Submit button that saves the information to a database. A fifth page should display a confirmation that the information was successfully saved. Include code based on reading e-mail addresses that prevents the same user from registering twice.

Thus far, I've set up the first three .php files, each producing a form page, and I can click "next" and "back" buttons between theses pages. But when I do I lose the data I just entered. I've been studying $_SESSION variables but I'm still unsure how to use $_SESSION properly in this particular case.

So my first question is: How to properly use $_SESSION is this case.

My second question: how to click "back" button on, say, page 2 and see my inputed data on page 1? Might it have something to do with "hidden" form fields?

I hope I'm being clear. Thank you!

Explanation / Answer

Q 1) I recommend reading these articles the first is a website that will help a lot (compiled from the web http. // W w w .c o m w3schools /)

PHP Sessions

A session is a way to store information (in variables) to be used across multiple pages.

Unlike a cookie, the information is not stored on the users computer.

What is a PHP Session?

When you work with an application, you open it, do some changes, and then you close it. This is much like a Session. The computer knows who you are. It knows when you start the application and when you end. But on the internet there is one problem: the web server does not know who you are or what you do, because the HTTP address doesn't maintain state.

Session variables solve this problem by storing user information to be used across multiple pages (e.g. username, favorite color, etc). By default, session variables last until the user closes the browser.

So; Session variables hold information about one single user, and are available to all pages in one application.

Tip: If you need a permanent storage, you may want to store the data in a database.

Start a PHP Session

A session is started with the session_start() function.

Session variables are set with the PHP global variable: $_SESSION.

Now, let's create a new page called "demo_session1.php". In this page, we start a new PHP session and set some session variables:

Example

<?php
// Start the session
session_start();
?>
<!DOCTYPE html>
<html>
<body>

<?php
// Set session variables
$_SESSION["favcolor"] = "green";
$_SESSION["favanimal"] = "cat";
echo "Session variables are set.";
?>

</body>
</html>

Note: The session_start() function must be the very first thing in your document. Before any HTML tags.

Get PHP Session Variable Values

Next, we create another page called "demo_session2.php". From this page, we will access the session information we set on the first page ("demo_session1.php").

Notice that session variables are not passed individually to each new page, instead they are retrieved from the session we open at the beginning of each page (session_start()).

Also notice that all session variable values are stored in the global $_SESSION variable:

Example

<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>

<?php
// Echo session variables that were set on previous page
echo "Favorite color is " . $_SESSION["favcolor"] . ".<br>";
echo "Favorite animal is " . $_SESSION["favanimal"] . ".";
?>

</body>
</html>

Another way to show all the session variable values for a user session is to run the following code:

Example

<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>

<?php
print_r($_SESSION);
?>

</body>
</html>

How does it work? How does it know it's me?

Most sessions set a user-key on the user's computer that looks something like this: 765487cf34ert8dede5a562e4f3a7e12. Then, when a session is opened on another page, it scans the computer for a user-key. If there is a match, it accesses that session, if not, it starts a new session.

Modify a PHP Session Variable

To change a session variable, just overwrite it:

Example

<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>

<?php
// to change a session variable, just overwrite it
$_SESSION["favcolor"] = "yellow";
print_r($_SESSION);
?>

</body>
</html>

Destroy a PHP Session

To remove all global session variables and destroy the session, use session_unset() and session_destroy():

Example

<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>

<?php
// remove all session variables
session_unset();

// destroy the session
session_destroy();
?>

</body>
</html>

Q 2) I Compiled from the website http: // w w w. c odeproject. c o m / this is a common problem for programmers so here we have a solution for this:

Browser Back Button Issue After Logout

Introduction

Generally when any user logs into any web application, we store some value in session. The session continues the user existence until logout. After logout, we clear/abandon the session and redirect to login page. In that state, the user is out of website and the secret information is now secure or nobody is authorized to view/access the information.

But the problem is now, from this redirect login page if user clicks the back button of browser, it again goes to the previous visited page although the page is already logged out. The main reason is the browser’s cache. This is because while user logs out the session, the session is abandoned in the server side. But after clicking the back button of the browser, the previous page is not postback, the client side just opens from cache. It only works if the back page refreshes/reloads, because in that period the page becomes postback.

The common problem has many solutions but each and every solution has some limitations. Let’s see the existing solutions that we can find easily in searching.

Existing Solution 1: Clear Cache/No-Cache

// Code disables caching by browser. Hence the back browser button

// grayed out and could not causes the Page_Load event to fire

Response.Cache.SetCacheability(HttpCacheability.NoCache);

Response.Cache.SetExpires(DateTime.UtcNow.AddHours(-1));

Response.Cache.SetNoStore();

Limitations

·         Server Side code and for that it does not work without postback.

·         I have to clear my cache by force (I don’t want to clear my cache).

Existing Solution 2: Use Meta Tag for No-Cache

<meta Http-Equiv="Cache-Control" Content="no-cache">

<meta Http-Equiv="Pragma" Content="no-cache">

<meta Http-Equiv="Expires" Content="0">

Limitations

·         This is not possible because Back history is maintained by browser, you will need to close the window.

·         I have to clear my cache by force (I don’t want to clear my cache).

Existing Solution 3: Clears Browser History and Redirects URL

Hide   Copy Code

//clears browser history and redirects url

<SCRIPT LANGUAGE="javascript">

{

     var Backlen=history.length;  

     history.go(-Backlen);  

     window.location.href=page url

}

</SCRIPT>

Limitations

·         Same limitation like solution 1: Does not work in all browsers, moreover I have to clear my history although I don't want to do this.

Existing Solution 4: Call JavaScript from Server Side to Clear Cache

Hide   Copy Code

Page.ClientScript.RegisterStartupScript(this.GetType(),"cle","windows.history.clear",true);

Limitation

·         Server side code, so it does not work without postback again. Moreover I have to clear my history although I don't want to do this.

Alternative Solution

From the above explanation, we can understand that when the user clicks on back button of browser, the client side loads only. Even no postback happens in that period. For that, I handle the problem on the client side. You can think that if we check the session value in client side with JavaScript, then the problem will solve? My answer is: NO. Because when we clear/abandon the session value, its value changed only server side but the value which has already taken with JavaScript variable, it stores on cache as well.

The only one solution is if we can check the server session value from client side on loading moment, then we can overcome this issue.

Analysis of Code

Login Page: Login process is very common like I store a session value while login is successful.

protected void btnSave_Click(object sender, EventArgs e)

{

   // User Name and Password Check here

   //After successful login store a session value

   Session["user"] = "user:Desme-BD";

   Response.Redirect("/frmContentHome.aspx", true);

}

I have stored "user:Desme-BD" in session "user".

Master Page(Server Side): In content page, I have checked the session value or Redirect the page to Login page.

// this is simple method only checking the session value while user login

private void CheckLogin()

{

            string domain = Request.Url.Authority.ToString();

            BaseURL = "http://" + domain + "/";

            //Load menu or Do Any database related work

            if (Session["user"] != null)

            {

                lnkLogin.Text = "Logout";

                lnkLogin.PostBackUrl = BaseURL + "frmLogout.aspx";

            }

            else

            {

                Response.Redirect(BaseURL + "frmLogin.aspx", false);

            }

}

Logout Page: I also clean the session value while logout with those common methods.

Hide   Copy Code

Session.Abandon();

Session.Clear();

Session.RemoveAll();

System.Web.Security.FormsAuthentication.SignOut();

Response.Redirect("frmLogin.aspx", false);<span> </span>

The Method which Checks Server's Session with Client Side

Master Page(Client Side)

On ASPX page, I use the Jquery with JSON and check the Session value with LogoutCheck() WebMethod.

<script type="text/javascript">

        $(document).ready(function () {

            CheckingSeassion();

        });

        function CheckingSeassion() {

            $.ajax({

                type: "POST",

                url: "frmLogout.aspx/LogoutCheck",

                data: "{}",

                contentType: "application/json; charset=utf-8",

                dataType: "json",

                success: function (response) {

                    if (response.d == 0) {

                        window.location = '<%= BaseURL %>' + "frmLogin.aspx";

                    }

                },

                failure: function (msg) {

                    alert(msg);

                }

            });

        }

</script>

The LogoutCheck() WebMethod checks the session value from application server on client side loading moment.

I created this method on frmLogout.aspx page like this:

public static int LogoutCheck()

{

   if (HttpContext.Current.Session["user"] == null)

   {

       return 0;

   }

   return 1;

}

Now, when user logs out the page, it redirects to logout page and clears and abandons the session values. Now when user clicks back button of browser, the client side only loads and in that period the CheckingSession()WebMethod fires in JQuery and it checks the session value LogoutCheck() WebMethod. As the session is null, the method returns zero and the page redirects again in login page. So, I don't have to clear the cache or clear any history of user's browser.

Download the solution-> browse frmLogin.aspx -> give any password and Login-> now Logout-> click back button on your browser and notice.

Advantages

·         Works on client side page load. No need to postback because it's calling with Ajax.

·         No need to remove cache/history

·         No need to disable back button of web browser

Limitations

This tip also has a limitation that when user clicks the back button of the browser, the back page shows for 1 or half second because of executing the WebMethod.

History

·         20-February-2013

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Tip: If you need a permanent storage, you may want to store the data in a database.