我正在使用 PHP/MariaDB 开发一个新网站。
我用本教程植入了 facebook 登录(https://codeshack.io/implement-facebook-login-php/),效果很好。我现在在 Facebook 方面获得了完全批准,我的连接运行良好,我添加了一个 MariaDB 数据库表来管理用户的连接和未来的个性化。
我的问题是我的会话仅持续 24 分钟,这是 php 中的默认设置。
我已将本地和主 php.ini 文件中的 session.gc_maxlifetime 参数更改为 86400(这是所需的 24 小时以秒为单位)。此后,由于未知原因,我仍然受到默认 24 分钟值的限制,因此我将其添加到我的 php 文件的顶部:
ini_set('session.gc_maxlifetime', 86400);
此后我能够从 :
获得所需的值console.log('<?php echo ini_get("session.gc_maxlifetime"); ?>');
//返回86400;
此后它仍然断开连接,所以我添加了:
session_set_cookie_params(0);
即使使用 0 或 86400,它仍然会提前断开连接。
然后我添加了这个应该有帮助的:
if (isset($_SESSION['LAST_ACTIVITY']) && (time() - $_SESSION['LAST_ACTIVITY'] > 60000)) {
// last request was more than 30 minutes ago
session_unset(); // unset $_SESSION variable for the run-time
session_destroy(); // destroy session data in storage
}
$_SESSION['LAST_ACTIVITY'] = time(); // update last activity time stamp
if (!isset($_SESSION['CREATED'])) {
$_SESSION['CREATED'] = time();
} else if (time() - $_SESSION['CREATED'] > 30000) {
// session started more than 30 minutes ago
session_regenerate_id(true); // change session ID for the current session and
invalidate old session ID
$_SESSION['CREATED'] = time(); // update creation time
}
我现在期待有任何方法可以让我的用户保持连接超过 24 分钟!该连接用于个性化网站选项,因此这里没有大的安全问题。
感谢您伟大社区的帮助!!!
这是我的 oAuth 文件:
<?php
ini_set('session.save_path',realpath(dirname($_SERVER['DOCUMENT_ROOT']) . '../../sessions'));
// server should keep session data for AT LEAST 1 hour
ini_set('session.gc_maxlifetime', 86400);
// each client should remember their session id for EXACTLY 1 hour
session_set_cookie_params(0);
session_start();
if (isset($_SESSION['LAST_ACTIVITY']) && (time() - $_SESSION['LAST_ACTIVITY'] > 60000)) {
// last request was more than 30 minutes ago
session_unset(); // unset $_SESSION variable for the run-time
session_destroy(); // destroy session data in storage
}
$_SESSION['LAST_ACTIVITY'] = time(); // update last activity time stamp
if (!isset($_SESSION['CREATED'])) {
$_SESSION['CREATED'] = time();
} else if (time() - $_SESSION['CREATED'] > 30000) {
// session started more than 30 minutes ago
session_regenerate_id(true); // change session ID for the current session and invalidate old session ID
$_SESSION['CREATED'] = time(); // update creation time
}
include '../scripts/php_connect.php';
// Update the following variables
$facebook_oauth_app_id = 'XXXXXXXX';
$facebook_oauth_app_secret = 'XXXXXXXX';
// Must be the direct URL to the facebook-oauth.php file
$facebook_oauth_redirect_uri = 'XXXXXXXX';
$facebook_oauth_version = 'v19.0';
// If the captured code param exists and is valid
if (isset($_GET['code']) && !empty($_GET['code'])) {
// Execute cURL request to retrieve the access token
$params = [
'client_id' => $facebook_oauth_app_id,
'client_secret' => $facebook_oauth_app_secret,
'redirect_uri' => $facebook_oauth_redirect_uri,
'code' => $_GET['code']
];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://graph.facebook.com/oauth/access_token');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($params));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
$response = json_decode($response, true);
} else {
// Define params and redirect to Facebook OAuth page
$params = [
'client_id' => $facebook_oauth_app_id,
'redirect_uri' => $facebook_oauth_redirect_uri,
'response_type' => 'code',
'scope' => 'email'
];
header('Location: https://www.facebook.com/dialog/oauth?' . http_build_query($params));
exit;
}
if (isset($response['access_token']) && !empty($response['access_token'])) {
// Execute cURL request to retrieve the user info associated with the Facebook account
// Execute cURL request to retrieve the user info associated with the Facebook account
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://graph.facebook.com/' . $facebook_oauth_version . '/me?fields=name,email,picture');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Authorization: Bearer ' . $response['access_token']]);
$response = curl_exec($ch);
curl_close($ch);
$profile = json_decode($response, true);
// Make sure the profile data exists
if (isset($profile['email'])) {
// Store a string into the variable which
// need to be Encrypted
$simple_string = $profile['email'];
// Store the cipher method
$ciphering = "AES-128-CTR";
// Use OpenSSl Encryption method
$iv_length = openssl_cipher_iv_length($ciphering);
$options = 0;
// Non-NULL Initialization Vector for encryption
$encryption_iv = 'XXXXXX';
// Store the encryption key
$encryption_key = "XXXXXXXX";
// Use openssl_encrypt() function to encrypt the data
$encryption = openssl_encrypt($simple_string, $ciphering,
$encryption_key, $options, $encryption_iv);
// Check if the account exists in the database
$stmt = $dbPDO->prepare("SELECT * FROM accounts WHERE email = ?");
$stmt->execute([ $encryption ]);
$account = $stmt->fetch(PDO::FETCH_ASSOC);
// If the account does not exist in the database, insert the account into the database
if (!$account) {
$stmt = $dbPDO->prepare("INSERT INTO XXXXXX (email, name, picture, registered, method) VALUES (?, ?, ?, ?, ?)");
$stmt->execute([ $encryption, $profile['name'], $profile['picture']['data']['url'], date('Y-m-d H:i:s'), 'facebook' ]);
$id = $dbPDO->lastInsertId();
} else {
$id = $account['ID'];
}
// Authenticate the account
session_regenerate_id();
$_SESSION['facebook_loggedin'] = TRUE;
$_SESSION['facebook_id'] = $id;
// Redirect to profile page
//echo $_SESSION['facebook_loggedin'] . $_SESSION['facebook_id'];
header('Location: profile.php');
exit;
} else {
//echo "test";
exit('Could not retrieve profile information! Please try again later!');
}
} else {
exit('Invalid access token! Please try again later!');
}
?>
这是我的示例标题页:
<?php
if ( !isset( $_SESSION ) ) {
ini_set( 'session.save_path', realpath( dirname( $_SERVER[ 'DOCUMENT_ROOT' ] ) . '../../sessions' ) );
// server should keep session data for AT LEAST 1 hour
ini_set('session.gc_maxlifetime', 86400);
session_set_cookie_params(0);
session_start();
}
include 'scripts/php_connect.php';
$permissions = [];
if (isset($_SESSION['LAST_ACTIVITY']) && (time() - $_SESSION['LAST_ACTIVITY'] > 30000)) {
// last request was more than 30 minutes ago
session_unset(); // unset $_SESSION variable for the run-time
session_destroy(); // destroy session data in storage
}
$_SESSION['LAST_ACTIVITY'] = time(); // update last activity time stamp
if (!isset($_SESSION['CREATED'])) {
$_SESSION['CREATED'] = time();
} else if (time() - $_SESSION['CREATED'] > 30000) {
// session started more than 30 minutes ago
session_regenerate_id(true); // change session ID for the current session and invalidate old session ID
$_SESSION['CREATED'] = time(); // update creation time
}
if ( isset( $_SESSION[ 'facebook_loggedin' ] ) ) {
// Get the account from the database
$stmt = $dbPDO->prepare('SELECT * FROM XXXXXX WHERE ID = ?');
$stmt->execute([ $_SESSION['facebook_id'] ]);
$account = $stmt->fetch(PDO::FETCH_ASSOC);
// Retrieve session variables
$facebook_loggedin = $_SESSION['facebook_loggedin'];
// Define the data to encrypt
$data = $account['email'];
// Define the secret key
$key = "XXXXXXXX";
// Define the encryption method
$method = "XXXXXX";
// Generate a random initialization vector (IV)
$iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length($method));
// Decode the encrypted data
$encrypted = base64_decode($data);
// Extract the IV and the encrypted data
$iv = substr($encrypted, 0, openssl_cipher_iv_length($method));
$encrypted = substr($encrypted, openssl_cipher_iv_length($method));
// Decrypt the data
$decrypted = openssl_decrypt($encrypted, $method, $key, 0, $iv);
$user_email = $decrypted;
$user_name = $account['name'];
$facebook_picture = $account['picture'];
$user_id = $account['ID'];
?>
这是服务器配置:
cPanel 版本 110.0(版本 24) 阿帕奇版本 2.4.58 MySQL 版本 10.6.17-MariaDB-cll-lve-log 架构 x86_64 操作系统 linux Perl 版本 5.16.3 内核版本4.18.0-372.16.1.lve.el7h.x86_64
我最终使用编码的 facebook_id 创建了一个持续时间为 24 小时的 cookie,并且成功了。
<?php
ini_set('session.save_path',realpath(dirname($_SERVER['DOCUMENT_ROOT']) . '../../sessions'));
// server should keep session data for AT LEAST 1 hour
//ini_set('session.gc_maxlifetime', 86400);
// each client should remember their session id for EXACTLY 1 hour
session_set_cookie_params(86400);
session_start();
include '../scripts/php_connect.php';
// Update the following variables
$facebook_oauth_app_id = 'XXXXXXXXXXX';
$facebook_oauth_app_secret = 'XXXXXXXXXXXXXXXXXXXXXX';
// Must be the direct URL to the facebook-oauth.php file
$facebook_oauth_redirect_uri = 'https://nou.mycoquebec.org/facebook-login/facebook-oauth.php';
$facebook_oauth_version = 'v19.0';
// If the captured code param exists and is valid
if (isset($_GET['code']) && !empty($_GET['code'])) {
// Execute cURL request to retrieve the access token
$params = [
'client_id' => $facebook_oauth_app_id,
'client_secret' => $facebook_oauth_app_secret,
'redirect_uri' => $facebook_oauth_redirect_uri,
'code' => $_GET['code']
];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://graph.facebook.com/oauth/access_token');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($params));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
$response = json_decode($response, true);
} else {
// Define params and redirect to Facebook OAuth page
$params = [
'client_id' => $facebook_oauth_app_id,
'redirect_uri' => $facebook_oauth_redirect_uri,
'response_type' => 'code',
'scope' => 'email'
];
header('Location: https://www.facebook.com/dialog/oauth?' . http_build_query($params));
exit;
}
if (isset($response['access_token']) && !empty($response['access_token'])) {
// Execute cURL request to retrieve the user info associated with the Facebook account
// Execute cURL request to retrieve the user info associated with the Facebook account
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://graph.facebook.com/' . $facebook_oauth_version . '/me?fields=name,email,picture');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Authorization: Bearer ' . $response['access_token']]);
$response = curl_exec($ch);
curl_close($ch);
$profile = json_decode($response, true);
// Make sure the profile data exists
if (isset($profile['email'])) {
// Store a string into the variable which
// need to be Encrypted
$simple_string = $profile['email'];
// Store the cipher method
$ciphering = "AES-128-CTR";
// Use OpenSSl Encryption method
$iv_length = openssl_cipher_iv_length($ciphering);
$options = 0;
// Non-NULL Initialization Vector for encryption
$encryption_iv = 'XXXXXXXXXXX';
// Store the encryption key
$encryption_key = "XXXXXXXXXXX";
// Use openssl_encrypt() function to encrypt the data
$encryption = openssl_encrypt($simple_string, $ciphering,
$encryption_key, $options, $encryption_iv);
// Check if the account exists in the database
$stmt = $dbPDO->prepare("SELECT * FROM accounts WHERE email = ?");
$stmt->execute([ $encryption ]);
$account = $stmt->fetch(PDO::FETCH_ASSOC);
// If the account does not exist in the database, insert the account into the database
if (!$account) {
$stmt = $dbPDO->prepare("INSERT INTO accounts (email, name, picture, registered, method) VALUES (?, ?, ?, ?, ?)");
$stmt->execute([ $encryption, $profile['name'], $profile['picture']['data']['url'], date('Y-m-d H:i:s'), 'facebook' ]);
$id = $dbPDO->lastInsertId();
} else {
$id = $account['ID'];
}
// Authenticate the account
session_regenerate_id();
$_SESSION['facebook_loggedin'] = TRUE;
$_SESSION['facebook_id'] = $id;
setcookie("facebook_loggedin", "TRUE", time() + (86400 * 1), "/"); // 86400 = 1 day
setcookie("facebook_id", openssl_encrypt($id, $ciphering,
$encryption_key, $options, $encryption_iv), time() + (86400 * 1), "/"); // 86400 = 1 day
// Redirect to profile page
//echo $_SESSION['facebook_loggedin'] . $_SESSION['facebook_id'];
header('Location: profile.php');
exit;
} else {
//echo "test";
exit('Could not retrieve profile information! Please try again later!');
}
} else {
exit('Invalid access token! Please try again later!');
}
?>
以及配置文件:
<?php
if (!isset($_SESSION)) {
ini_set('session.save_path',realpath(dirname($_SERVER['DOCUMENT_ROOT']) . '../../sessions'));
// server should keep session data for AT LEAST 1 hour
//ini_set('session.gc_maxlifetime', 86400);
// each client should remember their session id for EXACTLY 1 hour
session_set_cookie_params(86400);
session_start();
}
/*
if (isset($_SESSION['LAST_ACTIVITY']) && (time() - $_SESSION['LAST_ACTIVITY'] > 60000)) {
// last request was more than 30 minutes ago
session_unset(); // unset $_SESSION variable for the run-time
session_destroy(); // destroy session data in storage
}
$_SESSION['LAST_ACTIVITY'] = time(); // update last activity time stamp
if (!isset($_SESSION['CREATED'])) {
$_SESSION['CREATED'] = time();
} else if (time() - $_SESSION['CREATED'] > 30000) {
// session started more than 30 minutes ago
session_regenerate_id(true); // change session ID for the current session and invalidate old session ID
$_SESSION['CREATED'] = time(); // update creation time
}
*/
// Check if the user is logged in, if not then redirect to login page
if (!isset($_SESSION['facebook_loggedin']) && !isset($_COOKIE["facebook_loggedin"])) {
header('Location: login.php');
exit;
} else {
// Store the cipher method
$ciphering = "AES-128-CTR";
// Use OpenSSl Encryption method
$iv_length = openssl_cipher_iv_length($ciphering);
$options = 0;
// Non-NULL Initialization Vector for decryption
$decryption_iv = 'XXXXXXXXXXXXXXXXXXXXXX';
// Store the decryption key
$decryption_key = "XXXXXXXXXXXXXXXXXXXXXX";
if (isset($_SESSION['facebook_id'])) {
$facebook_id = ($_SESSION['facebook_id'] != "" ? $_SESSION['facebook_id'] : "");
} else {
$facebook_id = ($_COOKIE["facebook_id"] != "" ? openssl_decrypt ($_COOKIE["facebook_id"], $ciphering, $decryption_key, $options, $decryption_iv) : "");
}
// Database connection variables
include '../scripts/php_connect.php';
// Get the account from the database
$stmt = $dbPDO->prepare('SELECT * FROM accounts WHERE ID = ?');
$stmt->execute([ $facebook_id ]);
$account = $stmt->fetch(PDO::FETCH_ASSOC);
// Retrieve session variables
$facebook_loggedin = (isset($_SESSION['facebook_loggedin']) && $_SESSION['facebook_loggedin'] != "" ? $_SESSION['facebook_loggedin'] : $_COOKIE["facebook_loggedin"]);
// Use openssl_decrypt() function to decrypt the data
$decryption=openssl_decrypt ($account['email'], $ciphering, $decryption_key, $options, $decryption_iv);
$user_email = $decryption;
$user_name = $account['name'];
$facebook_picture = $account['picture'];
$user_id = $account['ID'];
$sql = "SELECT Permission, Description FROM accounts_permissions WHERE ID = :userID ORDER BY Description ASC";
$stmt = $dbPDO->prepare($sql);
$stmt->bindParam(':userID', $user_id, PDO::PARAM_STR);
$stmt->execute();
$result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
$result = $stmt->fetchAll();
$stmt->closeCursor();
if ($result) {
foreach($result as $permission) {
$permissions[$permission["Permission"]] = $permission["Description"];
}
} else {
$permissions[1] = 'Accès générale';
}
}
?>
如果这可以帮助别人!