I am new to php. I tried to use session to store the user id. However, the showSession.php print nothing in id part. Did I miss anything in the code? Thanks!
loginfb.php used to access the database
<?php
session_start();
//Load the database configuration file
require("config.inc.php");
//Convert JSON data into PHP variable
$userData = json_decode($_POST['userData']);
if(!empty($userData)){
$oauth_provider = $_POST['oauth_provider'];
//Check whether user data already exists in database
$prevQuery = "SELECT * FROM users WHERE oauth_provider = '".$oauth_provider."' AND oauth_uid = '".$userData->id."'";
try {
$stmt = $db->prepare($prevQuery);
$result = $stmt->execute();
}
catch (PDOException $ex) {
$response["success"] = 0;
$response["message"] = "Database Error!";
die(json_encode($response));
}
$rows = $stmt->fetchAll();
if($rows){
//Update user data if already exists
$query = "UPDATE users SET first_name = '".$userData->first_name."', last_name = '".$userData->last_name."', email = '".$userData->email."', gender = '".$userData->gender."', locale = '".$userData->locale."', picture = '".$userData->picture->data->url."', link = '".$userData->link."', modified = '".date("Y-m-d H:i:s")."' WHERE oauth_provider = '".$oauth_provider."' AND oauth_uid = '".$userData->id."'";
$update = $db->query($query);
$_SESSION["id"] = $rows['id'];
}else{
//Insert user data
$query = "INSERT INTO users SET oauth_provider = '".$oauth_provider."', oauth_uid = '".$userData->id."', first_name = '".$userData->first_name."', last_name = '".$userData->last_name."', email = '".$userData->email."', gender = '".$userData->gender."', locale = '".$userData->locale."', picture = '".$userData->picture->data->url."', link = '".$userData->link."', created = '".date("Y-m-d H:i:s")."', modified = '".date("Y-m-d H:i:s")."'";
$insert = $db->query($query);
$getSession = "SELECT * FROM users WHERE oauth_provider = '".$oauth_provider."' AND oauth_uid = '".$userData->id."'";
try {
$stmt1 = $db->prepare($getSession);
$result1 = $stmt1->execute();
}
catch (PDOException $ex) {
$response["success"] = 0;
$response["message"] = "Database Error!";
die(json_encode($response));
}
$rows1 = $stmt1->fetchAll();
if($rows1){
$_SESSION["id"] = $rows1['id'];
}
}
}
?>
showSession.php used to print out the session id.
<?php
session_start();
echo session_id();
$id=$_SESSION['id'];
echo "Session id is " . $_SESSION["id"] . ".<br>";
echo "Session id is " . $id . ".<br>";
print_r($_SESSION);
?>
login.html is the user interface to let user login with facebook account.
<!DOCTYPE html>
<html>
<style>
form {
border: 3px solid #f1f1f1;
}
input[type=text], input[type=password] {
width: 100%;
padding: 12px 20px;
margin: 8px 0;
display: inline-block;
border: 1px solid #ccc;
box-sizing: border-box;
}
button {
background-color: #4CAF50;
color: white;
padding: 14px 20px;
margin: 8px 0;
border: none;
cursor: pointer;
width: 100%;
}
button:hover {
opacity: 0.8;
}
.registerbtn {
width: auto;
padding: 10px 18px;
background-color: #f44336;
}
.imgcontainer {
text-align: center;
margin: 24px 0 12px 0;
}
img.avatar {
width: 40%;
border-radius: 50%;
}
.container {
padding: 16px;
}
span.psw {
float: right;
padding-top: 16px;
}
/* Change styles for span and cancel button on extra small screens */
@media screen and (max-width: 300px) {
span.psw {
display: block;
float: none;
}
.registerbtn {
width: 100%;
}
}
</style>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<script>
window.fbAsyncInit = function() {
// FB JavaScript SDK configuration and setup
FB.init({
appId : '1537121876329962', // FB App ID
cookie : true, // enable cookies to allow the server to access the session
xfbml : true, // parse social plugins on this page
version : 'v2.8' // use graph api version 2.8
});
FB.Event.subscribe('auth.login', function(){
window.location.href = 'showSession.php';
});
FB.Event.subscribe('auth.logout', function(){
window.location.href = 'login.html';
});
// Check whether the user already logged in
FB.getLoginStatus(function(response) {
if (response.status === 'connected') {
//display user data
getFbUserData();
}
});
};
// Load the JavaScript SDK asynchronously
(function(d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) return;
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/en_US/sdk.js";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
// Facebook login with JavaScript SDK
function fbLogin() {
FB.login(function (response) {
if (response.authResponse) {
// Get and display the user profile data
getFbUserData();
} else {
document.getElementById('status').innerHTML = 'User cancelled login or did not fully authorize.';
}
}, {scope: 'email'});
}
// Fetch the user profile data from facebook
function getFbUserData(){
FB.api('/me', {locale: 'en_US', fields: 'id,first_name,last_name,email,link,gender,locale,picture'},
function (response) {
document.getElementById('fbLink').setAttribute("onclick","fbLogout()");
document.getElementById('fbLink').innerHTML = 'Logout from Facebook';
document.getElementById('status').innerHTML = 'Thanks for logging in, ' + response.first_name + '!';
document.getElementById('userData').innerHTML = '<p><b>FB ID:</b> '+response.id+'</p><p><b>Name:</b> '+response.first_name+' '+response.last_name+'</p><p><b>Email:</b> '+response.email+'</p><p><b>Gender:</b> '+response.gender+'</p><p><b>Locale:</b> '+response.locale+'</p><p><b>Picture:</b> <img src="'+response.picture.data.url+'"/></p><p><b>FB Profile:</b> <a target="_blank" href="'+response.link+'">click to view profile</a></p>';
// Save user data
saveUserData(response);
});
}
// Logout from facebook
function fbLogout() {
FB.logout(function() {
document.getElementById('fbLink').setAttribute("onclick","fbLogin()");
document.getElementById('fbLink').innerHTML = '<img src="fblogin.png"/>';
document.getElementById('userData').innerHTML = '';
document.getElementById('status').innerHTML = 'You have successfully logout from Facebook.';
});
}
// Save user data to the database
function saveUserData(userData){
$.post('loginfb.php', {oauth_provider:'facebook',userData: JSON.stringify(userData)}, function(data){ return true; });
}
</script>
<h2>Login Form</h2>
<form action="loginUser.php" method="post">
<div class="imgcontainer">
<img src="img_avatar2.png" alt="Avatar" class="avatar">
</div>
<div class="container">
<label><b>Username</b></label>
<input type="text" placeholder="Enter Username" name="username" required>
<label><b>Password</b></label>
<input type="password" placeholder="Enter Password" name="password" required>
<button type="submit">Login</button>
<input type="checkbox" checked="checked"> Remember me
</div>
<div class="container" style="background-color:#f1f1f1">
<button type="button" class="registerbtn" onclick="location.href='register.html'">Register</button>
<span class="psw">Forgot <a href="#">password?</a></span>
</div>
</form>
<!--
<div
class="fb-like"
data-share="true"
data-width="450"
data-show-faces="true">
</div>
-->
<!--
<div id="status"></div>
-->
<!-- Facebook login or logout button -->
<a href="javascript:void(0);" onclick="fbLogin()" id="fbLink"><img src="fblogin.png"/></a>
<!--
<div id="userData"></div>
-->
</body>
</html>
2
Answers
It may be because of this part of your program is not executing.
In this cause if
if
condition is not approaching then the data is not going to store insession
. Try to print out a string in the aboveif condition
to see if it is executing.Can you try using below code as I can see some variable naming issues. Hope this will help