是否可以直接使用ajax发送php会话变量?

时间:2011-07-26 15:03:32

标签: php ajax session

我在index.php

中有这个
    <?php

    include_once '..\connect.php';

    session_start();

    if (isset($_SESSION['username'])){
        $player_name = $_SESSION['username'];

    } else {    
        header( 'Location: http://localhost/Inventory/index.php' ) ;
        exit;
    }

    ?>

我正在向request.php发出ajax请求

    <?php
    //connect to databate and check for errors
    $con = mysql_connect ("localhost","root","");
    if (!$con) {
        die ('Could not connect to database: ' . mysql_error());
    }

    //select database and check selection
    if (!mysql_select_db ("GotA", $con)) {
        die ('Could not select database: ' . mysql_error());
    }

//I have to create this if not it doesnt find the sessions $player_name variable
    $player_name = $_POST['name']; 

    //***Create Player Array**//
    $player_info = "SELECT * from players where id = $player_name";
    $player_info2 = mysql_query($player_info) or die ('Couldnt get players name');
    $player_info3 = mysql_fetch_array($player_info2);

使用javascript发送的变量从数据库中检索数据似乎不安全,有没有办法直接使用index.php(会话部分)中的变量? 或者用javascript传递信息是否安全?

3 个答案:

答案 0 :(得分:3)

为什么不在request.php中再次检索会话?

而不是:

$player_name = $_POST['name']; 

使用:

$player_name = $_SESSION['username']; 

此前请务必使用session_start()

答案 1 :(得分:2)

根据我之前使用jQuery的经验,会话仍然可以使用ajax请求,只要您调用脚本顶部的session_start(),您就应该能够访问会话变量。

答案 2 :(得分:1)

您的AJAX请求虽然来自JavaScript,但仍可以访问浏览器的会话状态。您还可以回退到POSTed变量:

<强> request.php

<?php
session_start();

// Set $dbuser and $dbpass in a secure configuration file
$dbh = new PDO('mysql:host=localhost;dbname=GotA', $dbuser, $dbpass);

if (isset($_SESSION['username']))
    $player_name = $_SESSION['username'];
else
    $player_name = $_POST['name'];

$stmt = $dbh->prepare('SELECT * from players where id = :playername');
$stmt->execute(array(':playername' => $player_name));

$result = $stmt->fetchAll();

另一件事是,如果您正在运行多个异步请求,那么异步会话感知请求可能会导致竞争条件。有关信息,请参阅this article。只要您只读取会话变量而不是编写它们(或明确结束会话),那么您应该没问题。 (如果有人对之前的陈述有明确的答案,请分享评论)