-1

我尝试使用 php 会话。
创建会话:

<?php
function loginGeoserver($username, $password) {

$geoserverURL = "http://localhost:8080/geoserver/j_spring_security_check";

$post = http_build_query(array(
        "username" => $username,
        "password" => $password,
));

$context = stream_context_create(array("http"=>array(
    "method" => "POST",
    "header" => "Content-Type: application/x-www-form-urlencoded\r\n" .
            "Content-Length: ". strlen($post) . "\r\n",
    "content" => $post,
)));

$page = file_get_contents($geoserverURL, false, $context);


for($i = 0; $i < sizeof($http_response_header); $i++){

    $headerLine = $http_response_header[$i];

    $pos = strpos($headerLine, 'Set-Cookie');

    if ($pos === 0) {
            $str = explode("=",$headerLine);
            $value = explode(";",$str[1]);
            $cookieValue = $value[0];
            break;
    }

}

$cookieName = "JSESSIONID";
$cookieDomain = "http://localhost:8080";
$cookiePath = "/geoserver";
$cookieExpiration = 0;

setcookie($cookieName,$cookieValue,$cookieExpiration,$cookiePath);
return $cookieValue;
}
//loginGeoserver('new_user','123456');

这工作很好。
现在我尝试从另一个文件中调用它:

<?php
// newSession.php <user name> <password>
require_once "bootstrap.php";
require_once "geoserv.session.php";
$username = $argv[1];
$password = "plain:".$argv[2];
$user = $entityManager->find('Users', $username);
$pass = $user->getPassword();
if($pass == $password){
    echo "Auth successful\n";
    echo loginGeoserver($username,$password)."\n";
}else{
    echo "Access denied";
}

并获得输出:

D:\xampp\htdocs\doctrine2-tutorial>php geoserv.auth.php new_user 123456
Auth successful

Warning: Cannot modify header information - headers already sent by (output star
ted at D:\xampp\htdocs\doctrine2-tutorial\geoserv.auth.php:10) in D:\xampp\htdoc
s\doctrine2-tutorial\geoserv.session.php on line 41
12e19vgpggha2

发生什么事了?为什么我会收到警告?

4

2 回答 2

2

您的脚本在设置标头之前输出数据,这是一个禁忌。

您可以看到这一点,如第 10 行的错误所示:

echo "Auth successful\n";

然后第 11 行loginGeoserver()被调用,它设置了标题。

尝试交换第 10 行和第 11 行,看看会发生什么:)

于 2013-09-20T10:51:24.107 回答
2

在尝试重定向用户之前,您在代码中输出数据。

if($pass == $password){
    echo "Auth successful\n";
    // ^^ this is the no-no line.
    echo loginGeoserver($username,$password)."\n";

如果您已向客户端发送任何内容,则不能使用重定向等标头。

如果你删除那条线,它应该很有魅力。

于 2013-09-20T10:51:33.633 回答