[英]Creating a PHP session variable after successful AJAX call
I am having problems creating a PHP session following a successful AJAX call.在成功调用 AJAX 后,我在创建 PHP session 时遇到问题。 Here is the AJAX code:这是 AJAX 代码:
function onSignIn(googleUser) {
var profile = googleUser.getBasicProfile();
var id = profile.getId();
var em = profile.getEmail();
var name = profile.getName();
var pic = profile.getImageUrl();
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById('confirm-login').style.display = 'block';
}
};
xhttp.open("GET", "./assets/inc/profile.php?id="+id+"&e="+em+"&n="+name+"&p="+pic, true);
xhttp.send();
}
This part works perfectly.这部分工作完美。 I only include it for completeness sake.为了完整起见,我只包括它。
Here's the contents of profile.php这是profile.php的内容
<?php
$id = $_GET["id"];
$email = $_GET["e"];
$name = $_GET["n"];
$pic = $_GET["p"];
require_once("db.php");
$result = $mysqli->query("SELECT googleid FROM user_tbl WHERE googleid = '$id' LIMIT 1");
if($result->num_rows == 0) {
$sql = "INSERT INTO user_tbl (googleid, email, fullname, pic, loc) VALUES ('$id', '$email', '$name', '$pic', '')";
if (mysqli_query($mysqli, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "" . mysqli_error($mysqli);
}
} else {
echo "already exists";
}
$mysqli->close();
session_start();
$_SESSION['gid'] = $id;
?>
All of this code works except for session_start();
除了session_start();
之外,所有这些代码都有效。 and $_SESSION['gid'] = $id;
和$_SESSION['gid'] = $id;
when I return to another PHP page (which correctly has session_start();
at the very top of the page) the variable has not been created in profile.php当我返回另一个 PHP 页面(页面顶部正确有session_start();
)时,尚未在 profile.php 中创建变量
Any help as to what I'm doing wrong would be much appreicated.任何关于我做错了什么的帮助都会非常感激。
You can't start a session after the script has sent output.在脚本发送 output 后,您无法启动 session。 (There should have been output to that effect; if there wasn't, try changing PHP's warnings.) The session_start() call must come before any echo call that is actually executed. (应该有 output 达到这种效果;如果没有,请尝试更改 PHP 的警告。) session_start() 调用必须在任何实际执行的 echo 调用之前出现。
On an unrelated topic, you will want to learn how to escape your database parameters.在一个不相关的主题上,您将想要学习如何转义您的数据库参数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.