我的网站有两个页面,一个叫"new_account.php“,另一个叫"visitor.php”。用户可以选择为自己创建一个新帐户,也可以直接使用访问者帐户。
当用户选择“访问者”时,我向"new_account.php“请求创建一个临时帐户,该帐户使用随机的用户名和密码,在用户完成操作后将其删除。我对请求使用了file_get_contents,因为页面返回了我用来自动登录用户的用户散列。
这是"visitor.php":
$url = getBaseUrl().'new-account.php';
$data = array(
'name' => $tempName,
'character-name' => $tempCharacterName,
'gender' => $tempGender,
'age' => $tempAge,
'parent-email' => $tempParentEmail,
'password' => $tempPassword,
'password-confirmation' => $tempPassword,
'temporary' => TRUE
);
$options = array(
'http' => array(
'header' => "Content-type: application/x-www-form-urlencoded\r\n",
'method' => 'POST',
'content' => http_build_query($data),
),
);
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
var_dump($result);
if($result != "error") {
User::loginUser($result, TRUE, $conn);
User::ifUserLoggedRedirect('game.php',$conn);
}我的问题是,虽然请求成功并且在数据库中插入了一个新的随机用户,但是当User::loginUser尝试使用file_get_contents返回的散列(例如用户图标或用户名)查询用户数据时,我得到的结果集是空的。
User::loginUser是这样的:
public static function loginUser($userHash, $temporary, $conn) {
if(User::isAnyLogged($conn))
User::logout($conn);
User::safeSessionStart();
$result = $conn->prepare('SELECT p.screen_name, pi.url, p.id FROM player as p, player_icon as pi WHERE p.user_hash=? AND pi.id = p.player_icon_id');
$result->bind_param('s',$userHash);
$result->execute();
$res = $result->get_result();
if($res->num_rows == 0) {
die("Invalid user with hash ".$userHash);
}
$user_info = $res->fetch_assoc();
$_SESSION['user'] = new User($userHash, $temporary, $user_info['screen_name'], $user_info['url'], $user_info['id']);
setcookie('userHash',$userHash);
setcookie('temporary',$temporary ? '1' : '0' );
return $_SESSION['user'];
}而且调用总是以无效的散列结束,但是如果我使用散列从phpmyadmin查询用户,那么用户实际上就在那里。通过访问"new_account.php“进行正常注册也是有效的。
我尝试的第一件事是在从file_get_contents获得结果后关闭并重新打开连接,但这不起作用。使用mysqli::refresh也不起作用。我尝试将代码的登录部分移动到"new_account.php“,但显然我也不能使用file_get_contents从请求中设置$_SESSION。
我也可以通过将新的帐户代码复制到访问者页面来解决这个问题,但我宁愿将帐户创建保留在单个页面中。还有什么我可以试一试的吗?
发布于 2015-03-01 19:42:04
您应该使用require_once来包含新的-account.PHP
这样,您就可以使用所包含文件的代码,就像它位于包含它的文件中一样。
https://stackoverflow.com/questions/28791180
复制相似问题