PHP ajax session does not work

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • ajaxphp
    New Member
    • Mar 2008
    • 3

    #1

    PHP ajax session does not work

    hello, all:

    I am having trouble to make ajax work for my tiny php app.

    I have a index.php file, which is
    [php]<?PHP
    session_start() ;
    $_SESSION['ajaxKey'] = md5(uniqid(rand (), TRUE));
    ?>
    <script src="clienthint .js"></script>
    <script>
    var ajaxKey = '<?PHP echo $_SESSION['ajaxKey']; ?>';
    </script>
    </head>
    <body onLoad="showres ult(ajaxKey);">
    <p>result: <span id="txtHint"></span>
    </body>
    </html>

    I have a ajax jS file, the relavant part is

    function showresult(str)
    {

    if (str.length==0)
    {
    document.getEle mentById("txtHi nt").innerHTML= ""
    return;
    }

    xmlHttp=GetXmlH ttpObject();
    if (xmlHttp==null)
    {
    alert ("Browser does not support HTTP Request");
    return;
    }

    var url = "read.php";
    url=url+"?q="+s tr;

    xmlHttp.onready statechange=sta teChanged;
    xmlHttp.open("G ET",url,true) ;
    xmlHttp.send(nu ll);
    }

    I have the read.php,

    <?php

    $q=$_GET["q"];

    if ($q == $_SESSION['ajaxKey'])
    {
    $filename = "myfile.txt ";

    $fp = fopen($filename , "rb") or die("Couldn't operate properly");

    $buffer = fread($fp, filesize($filen ame));

    echo $buffer;

    }

    else
    {

    echo "terminated".$_ SESSION['ajaxKey'];
    }

    ?>
    [/php]
    The idea is:
    1: index.php generate a session key
    2: index.php call read.php
    3: read.php check if session exists, if yes, then read it, if not, then it is a forging attempt

    Basically, I plan to use session key to defeat forging. But in read.php, the session key is always empty.

    Can anyone help me please?
    Last edited by ronverdonk; Mar 4 '08, 10:51 AM. Reason: code tags
  • ronverdonk
    Recognized Expert Specialist
    • Jul 2006
    • 4259

    #2
    Before we are able to help you, it would be nice to be able to read some orderly listed code. So enclose any code within the appropriate code tags. See the Posting Guidelines on how to do that.

    moderator

    Comment

    • eddierosenthal
      New Member
      • Jan 2008
      • 11

      #3
      do you have session_start() in each file ?
      also why not use session_id for the key?
      also why not use POST instead of get?
      hth
      Last edited by ronverdonk; Mar 4 '08, 06:00 PM. Reason: edit code

      Comment

      • ajaxphp
        New Member
        • Mar 2008
        • 3

        #4
        Thanks.

        I have added the session_start, and have changed to POST. and it worked.

        The problem is that I returned a Javascript function, and used eval(); but it seems that the script scope is wrong, I cannot use the function.

        Comment

        Working...