我一直面临一些问题,关于 setcookie()
在php中。setcookie()
在本地主机上工作正常,但在实时域名上却不正常,以下是我在本地主机上的设置。
本地主机
setcookie("private_token",$jwt,$expire_claim,"/","",false,true);
領域
setcookie("private_token",$jwt,$expire_claim,"/","domain.com",false,true);
阿贾克斯呼叫
$.ajax({
url: "includes/api/userAPI.php",
type: 'POST',
data: data,
xhrFields: {
withCredentials: true
},
crossDomain: true,
success: function (res, text, code) {
if (code.status == 200) {
window.location.replace("landing.php");
} else {
alert("something went wrong");
}
},
error: function (res) {
if (res.status == 401) {
alert("failed to authorize");
}
}
});
PHP中的页眉
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Credentials: true");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: POST");
header("Access-Control-Max-Age: 3600");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
P.S: 我想我已经搜索了整个网站,但没有发现任何关于这个问题的东西
编辑:这几行是之前的 setcookie
......这些都是在我前面已经提到过的设置头后被切除的。
SELF::$connection = Parent::getConnection();
$str = "select * from user where col=?";
$query = SELF::$connection->prepare($str);
$array = array($user->__get('col'));
$query->execute($array);
$row = $query->fetch(PDO::FETCH_ASSOC);
$session = new session();
$session->set_session($row['id']);
$id = $row["id"];
$username = $row["user"];
$password = $user->__get("pass");
$email = $user->__get("mail");
$hash = $row['pass'];
if(password_verify($password,$hash))
{
$secret_key = "dummy";
$issuer_claim = "THE_ISSUER"; // this can be the servername
$audience_claim = "THE_AUDIENCE";
$issuedat_claim = time(); // issued at
$expire_claim = strtotime('+1 day', $issuedat_claim);; // expire time in seconds
$token = array(
"iss" => $issuer_claim,
"aud" => $audience_claim,
"iat" => $issuedat_claim,
//u "nbf" => $notbefore_claim,
"exp" => $expire_claim,
"data" => array(
"id" => $id,
"username" => $username,
"email" => $email
));
现在,我只是得到以下错误的回应
<b>Warning</b>: Cannot modify header information - headers already sent by (output started at <file directory where setcookie has been called>:74) in <b><file directory where setcookie has been called></b> on line <b>77</b><br />
第74行 "expireAt" => $expire_claim
第七十七行 setcookie("private_token",$jwt,$expire_claim,"/","domain.com",false,true);
setcookie
因为头文件已经发送了,所以无法实际设置cookie。Cookies是在HTTP响应中使用 Set-Cookie
头部。
你的PHP脚本在你的 setcookie
呼叫。如果没有看到你的整个项目,就无法确定具体位置。通常情况下,造成这种情况的原因是在文件末尾关闭PHP标签后,保存的文件中有额外的字符(这是一个常见的问题)。你需要找到并删除这些额外的字符(假设它们是无关的)。否则,你将需要重构你的逻辑,以便于 setcookie
可以提前调用。
唯一的其他选择是启用 输出缓冲. 这将防止输出立即被发送;它将被缓冲在内存中,并在请求完成时发送,除非你明确地提前发送。这在各种情况下都很有用,但实际上只是解决根本问题的一个变通办法。
在您的情况下,由于这只发生在一个环境中,我会从审查任何环境特定的编解码器配置开始(听起来您有这样的配置)。也可能是您的deploymentbuild过程在部署到有问题的环境时添加了额外的字符。