Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 4 of 4
  1. #1
    New Coder
    Join Date
    Feb 2007
    Posts
    12
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Cookies, Javascript and PHP

    Hello there, I've been reading these forums for a while, but this is my first post, so forgive me if I make any mistakes or if this is the wrong section, as my question is about both Javascript and PHP.

    -----------

    I've run into a quite serious problem with my website, and I can't find any help or anything related to it.

    Let me describe what I'm trying to accomplish:

    The user has to fill out several forms, which are on separate pages. During the process, he should be allowed to freely browse through the site, without losing what he put in the forms. After finishing, he should go to a final page, where all of the information he entered would be displayed, and he can submit it to be processed (inserted/updated into a database).

    Currently, I'm trying to store all data from the forms in a cookie/session when the user leaves the page with the form, and retrieve it when he gets back to continue working on it, or when he goes to the final page. Here are the important pieces of code:

    Saving data to a cookie/session in the form page, Javascript:

    Code:
      function saveall()
      {
    
        // merge all form data from this page into a string s
        // note: this part is working correctly, I've tested it by alert()-ing s
    
        document.cookie="moves="+s
        alert(document.cookie)    // for testing
      }
    
      window.onunload=saveall
    Reading from the cookie/session in the final page, PHP:

    PHP Code:
    if (isset($_SESSION['moves'])) {
      echo 
    "<p>Session: {$_SESSION['moves']}</p>";
    } else {
      echo 
    "<p>Session not set!</p>";
    }
    if (isset(
    $_COOKIE['moves'])) {
      echo 
    "<p>Cookie: {$_COOKIE['moves']}</p>";
    } else {
      echo 
    "<p>Cookie not set!</p>";

    Well, that's where the problems arise. First, I don't know which one am I actually using: sessions or cookies? From what I understand, sessions are restricted to the current browser window only, and cease to exist after the window is closed. In the documentation, I found that the Javascript function I use should save data as a session, and the behavior confirms that (it is not visible in other browser windows, or after the current window closes). However, the PHP code always outputs that the session value is not set.

    That is not so much of a problem, although I'd prefer using sessions, for security reasons (I read that cookies are less secure, correct me if that's not the case), but the main problem is reading the value itself.

    I open the form page, fill out the form, and go to the final page. The testing alert executes succesfully, showing my cookie among the list. However, the final page reads:

    Code:
    Session not set!
    
    Cookie:
    That is, no more text after that. Only if I reload the page, it is all right:

    Code:
    Session not set!
    
    Cookie: <form entries converted to the string s>
    Also, if I visit any other pages between leaving the form page and entering the final one, it's displayed correctly. My problem is with switching directly from one to the other.

    If anyone can help me, or at least give some insight to what is wrong, I'd be very grateful.

  • #2
    Regular Coder
    Join Date
    Sep 2005
    Posts
    535
    Thanks
    0
    Thanked 0 Times in 0 Posts
    I'm confused (and somewhat worried) about where you are getting your information. A lot of the info. seems to be incorrect. I'd suggest reading the section on sessions in the PHP manual to get a better grasp of what they are.

    For example, sessions can last beyond a user's visit to a site (ie they can close the window and reopen the window while being in the same session). However it depends upon the site's developer as to how long they want a user's session to remain active. Usually sites only want a user's session to remain active as long as they're on the site in order to make consistant transactions. However other sites, like forums and blogs, may keep a user's session active until they actually sign-out (or after a very prolonged period of inactivity has passed). Thus wherever you heard that cookies can last longer than sessions is incorrect.

    I'm thinking that sessions would be the way that you'd want to go (although I'm probably biased since I know more about sessions than I do about cookies). Sessions tend to be more secure than cookies (from your point of view) since the session data is being stored on your server, not on the client's computer. Thus you'd have more control over that data. The only reason they may be less secure is if you are not the only user of the web-server. In that case, the admin. of the server may compromise the data if you are not given exclusive access to those session files.

    Note that the only thing insecure about sessions would be how the session id's are passed between client and server. The least secure would be to pass it in the URL, whereas the most secure would be to use cookies to pass the SID (just set use cookies=1 and use only cookies=1 in the php.ini file). This will automatically create the session cookie to pass the SID from client to server. The only problem would be if the client turned off using cookies, but in that case using cookies over sessions would be just as problematic.

    Is your PHP code the entire page? If so, you are using sessions incorrectly (unless you have set auto_start=1 in the php.ini file -- it's recommended to set that to 0, however).

    A quick test would be something like this.... First, go into the php.ini file and set the two cookie options in the sessions section as described above, as well as setting auto start=0. Also have session handling=files and set a location for those files to be stored in (make sure that PHP has write authority for that folder). Then you can start using sessions:
    Code:
    /* on page 1 */
    <?PHP
    session_start();
    $_SESSION['test']="Hello World";
    ?>
    <html><body>
    <a href='page2.php'>Click here</a>
    </body></html>
    
    /* on page2.php */
    <?PHP
    session_start();
    ?>
    <html><body>
    <h1>
    <?= isset($_SESSION['test'])?$_SESSION['test']:"No session set" ?>
    </h1>
    </body></html>
    The only thing that might give you problems with using sessions is that when a form is presented to the user, it is difficult to get the user's responses stored inside session variables. Remember that PHP is Pre Hypertext Processing. Thus when a page loads, data flow is usually unidirectional: From the server through PHP processing out to the client as an HTML page. Thus you can't have javascript assign values to PHP variables without sending the data back to the server first.

    However, there are ways to make calls back to the server while the form's page is visible to the user (similar to AJAX calls). Using a technique like this allows you to transparently send data back to the server to create those session variables as the user fills in the form. Then the user can browse around the site and when returning to the form-page, use those session variables to fill in the form elements with the previous input.

    Note to forum admin... even though I used a lot of PHP, I do think it'd be a tough call as to whether to move this thread. It's sort of like some AJAX questions since it needs to touch on both sides of the development process. I'd say for now, keep it here; there may be some other thoughts (like using cookies) that would be more along the lines of client dev. If Lord E. decides to go with sessions, then I'd suggest starting a new thread in the PHP section to get more details about how to use php's session functions.
    If you want answers, write a smart question.

    Yes, someone probably does know how...

    Oh, and if you want to learn, STFW!

  • #3
    New Coder
    Join Date
    Feb 2007
    Posts
    12
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Thanks for the reply.

    I'm confused (and somewhat worried) about where you are getting your information. A lot of the info. seems to be incorrect. I'd suggest reading the section on sessions in the PHP manual to get a better grasp of what they are.

    For example, sessions can last beyond a user's visit to a site (ie they can close the window and reopen the window while being in the same session). However it depends upon the site's developer as to how long they want a user's session to remain active. Usually sites only want a user's session to remain active as long as they're on the site in order to make consistant transactions. However other sites, like forums and blogs, may keep a user's session active until they actually sign-out (or after a very prolonged period of inactivity has passed). Thus wherever you heard that cookies can last longer than sessions is incorrect.
    I believe I've read it on http://www.javascriptkit.com/javatutors/cookie.shtml:

    There are two types of JavaSript cookies- permanent, and session-only. The first one stores its information in a physical file on the client's computer called "cookie.txt", with the stored data "permanently" available. Session only cookies, on the other hand, stores information in the browser memory, and is available for the duration of the browser session. In other words, the data stored inside a session cookie is available from the time of storage until the browser is closed. Moving from page to page during this time does not erase the data.
    I know that session data is stored on the server, with only an ID pointing to it on the client. On the other hand, the entire cookie data is stored on the client. Is that right?

    I don't in fact need some very tight security, it's not that I'm transferring credit card numbers or such, it's for an online game, and I don't want users to mess with the data, so I prefer storing it on the server. Again, if I'm completely mistaken by my understanding, please correct me.

    -----------

    Is your PHP code the entire page? If so, you are using sessions incorrectly (unless you have set auto_start=1 in the php.ini file -- it's recommended to set that to 0, however).
    I know how to set/read sessions with Javascript and with PHP (I have a session_start() there, I just posted the reading bit of it), just that I can't get Javascript to write to a session on one page and PHP to read from it on the other. I made two short testing pages to make sure the problem is not elsewhere in my code. This is their full source:

    page1.php

    Code:
    <?php
      session_start();
    ?>
    <html>
    <head>
    <title>Test page 1</title>
    <script type="text/javascript">
    
      function setcookie()
      {
        s=document.getElementById("test").value
        document.cookie="test="+s
        alert(document.cookie)
      }
    
      window.onunload=setcookie
    </script>
    </head>
    <body>
    <input id="test" type="text" style="width:200px"/><br/>
    <a href="page2.php">Page 2</a>
    <?php
      session_write_close();
    ?>
    </body>
    </html>
    page2.php

    Code:
    <?php
      session_start();
    ?>
    <html>
    <head>
    <title>Test Page 2</title>
    </head>
    <body>
    <?php
    if (isset($_SESSION['test'])) {
      echo "<p>Session: {$_SESSION['test']}</p>";
    } else {
      echo "<p>Session not set!</p>";
    }
    if (isset($_COOKIE['test'])) {
      echo "<p>Cookie: {$_COOKIE['test']}</p>";
    } else {
      echo "<p>Cookie not set!</p>";
    }
    ?>
    <input id="test2" type="text" style="width:200px"/><br/>
    
    <script type="text/javascript">
      var c=document.cookie
      var i=c.indexOf("test")+5
      var j=i
      while ((c.charAt(j)!=";") && (j<=c.length)) { j++ }
      document.getElementById("test2").value=c.substring(i,j)
    </script>
    
    <a href="page1.php">Page 1</a>
    </body>
    <?php
      session_write_close();
    ?>
    </html>
    (I know I don't have a doctype or meta tags specified, but I don't think it's a problem, as the original site has them correct and still doesn't work.)

    Again, the behavior is similar: I enter some text in the textbox on page1.php and click the link to page2. Alert box pops up containing "test=Text;" somewhere in the string. Page 2 then displays:

    Code:
    Session not set!
    
    Cookie not set!
    
    [input]Text[input]
    Only after reloading page2, it is correct:

    Code:
    Session not set!
    
    Cookie: Test
    
    [input]Text[input]
    -----------

    The only thing that might give you problems with using sessions is that when a form is presented to the user, it is difficult to get the user's responses stored inside session variables. Remember that PHP is Pre Hypertext Processing. Thus when a page loads, data flow is usually unidirectional: From the server through PHP processing out to the client as an HTML page. Thus you can't have javascript assign values to PHP variables without sending the data back to the server first.

    However, there are ways to make calls back to the server while the form's page is visible to the user (similar to AJAX calls). Using a technique like this allows you to transparently send data back to the server to create those session variables as the user fills in the form. Then the user can browse around the site and when returning to the form-page, use those session variables to fill in the form elements with the previous input.
    I don't need data to be exchanged between client and server while the user is still browsing/filling out the form. Only when he's done and clicks a link to go to another page, I want the data to be sent to the server and stored in a session, to be displayed again when the user goes to the final page.
    Jozef "Lord Emperor" Jirasek

    English is my second language, excuse any mistakes I make.

  • #4
    New Coder
    Join Date
    Feb 2007
    Posts
    12
    Thanks
    0
    Thanked 0 Times in 0 Posts
    I'd like to ask one of the moderators to move this thread into PHP section, maybe someone there will know a solution.

    Put even simpler, I want to know how/if can I set cookie value with Javascript and read it at the next page with PHP.

    Apologise if this is considered too short time to bump up this thread, but it's been on the second page for two days and I still didn't get any solution.
    Jozef "Lord Emperor" Jirasek

    English is my second language, excuse any mistakes I make.


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •