I was working on a web project which allows users to create their own sub domains dynamically.
Before creating a subdomain they should be logged in to the website.
And now was wondering how to set session variable of a user active even on the subdomains which he visits.
Tried with lot of functions like
session_set_cookie_params(0, '/', '.example.com');
**ini_set('session.cookie_domain', '.example.com' );**
but all in no wain. No function works .
So please do suggest me how to handle this.
here is my code which starts the session as soon as the user log's in:
checkusrlog.php
<?php
//for session to be active on subdomain
session_set_cookie_params(0, '/', '.xyz.com');
session_start(); // Start Session First Thing
error_reporting(E_ALL);
ini_set('display_errors', '1');
include_once "connectiontomysql.php"; // Connect to the database
$dyn_www = $_SERVER['HTTP_HOST'];
//------ CHECK IF THE USER IS LOGGED IN OR NOT AND GIVE APPROPRIATE OUTPUT -------
$logOptions = ''; // Initialize the logOptions variable that gets printed to the page
$newMessage = '';
// If the session variable and cookie variable are not set this code runs
if (!isset($_SESSION['idx'])) {
if (!isset($_COOKIE['idCookie'])) {
$logOptions = 'Register Account
|
Log In';
}
}
// If session ID is set for logged in user without cookies remember me feature set
if (isset($_SESSION['idx'])) {
$decryptedID = base64_decode($_SESSION['idx']);
$id_array = explode("p3h9xfn8sq03hs2234", $decryptedID);
$logOptions_id = $id_array[1];
} else if (isset($_COOKIE['idCookie'])) {// If id cookie is set, but no session ID is set yet, we set it below and update stuff
$decryptedID = base64_decode($_COOKIE['idCookie']);
$id_array = explode("nm2c0c4y3dn3727553", $decryptedID);
$userID = $id_array[1];
$userPass = $_COOKIE['passCookie'];
// Get their user first name to set into session var
$sql_uname = mysql_query("SELECT username, email FROM siteMembers WHERE id='$userID' AND password='$userPass' LIMIT 1");
$numRows = mysql_num_rows($sql_uname);
if ($numRows == 0) {
// Kill their cookies and send them back to homepage if they have cookie set but are not a member any longer
setcookie("idCookie", '', time()-42000, '/');
setcookie("passCookie", '', time()-42000, '/');
header("location: index.php"); // << makes the script send them to any page we set
exit();
}
while($row = mysql_fetch_array($sql_uname)){
$username = $row["username"];
$useremail = $row["email"];
}
$_SESSION['id'] = $userID; // now add the value we need to the session variable
$_SESSION['idx'] = base64_encode("g4p3h9xfn8sq03hs2234$userID");
$_SESSION['username'] = $username;
$_SESSION['useremail'] = $useremail;
$_SESSION['userpass'] = $userPass;
$logOptions_id = $userID;
?>
Note: all subdomains are managed with only single piece of code where the data which belogs to that particular subdomain is dump from database dynamically based on the subdomain.
In between am working on a shared hosting service and using *.streamicon.com as Root domain. Using *.streamicon.com as my root domain as it allows me to create 'n' number of subdomains dynamically.
Related
I have this problem which keeps me from pushing towards my login page. I know that when you log in you can create a security by means of cookies and session and so i did. But using this EditThisCookie add on in google chrome, if i delete my cookies then I must update my database status to inactive. But im stucked on how to do it. Can some one help me regarding this problem. My code below.
$user = $_SESSION["user_id"];
$sesskey = $_SESSION['sesskey'];
$firstname = $_SESSION['firstname'];
if(count($_COOKIE) > 0) {
} else {
$sqlupses = "UPDATE credentials set loginkey = '', access_status = 'inactive' where user_id = '$user'";
die($sqlupses);
$ressess = mysql_query( $sqlupses, $dbhandle );
session_unset();
session_destroy();
header('location:index.php?lvs=8');
exit();
}
I have an issue where some of my pages take an extended period to load due to communications with various external APIs. I noticed that when I change to a different page or reload the current page before it has finished loading, it seems to drop my session and logs me out.
For example, if loading page about.php and then I click a link to load profile.php before about.php has loaded fully, it logs me out and drops me back at the login screen.
I don't know what to search for this but have not been able to find any information on similar problems. Can anyone shed light on what would be causing this?
Top of each page:
sec_session_start();
if(login_check($dp_conn) == false)
{
header("location:../login.php?error=1");
}
sec_session_start() function:
function sec_session_start()
{
$session_name = 'sec_session_id'; // Set a custom session name
$secure = false; // Set to true if using https.
$httponly = true; // This stops javascript being able to access the session id.
ini_set('session.use_only_cookies', 1); // Forces sessions to only use cookies.
$cookieParams = session_get_cookie_params(); // Gets current cookies params.
session_set_cookie_params($cookieParams["lifetime"], $cookieParams["path"], $cookieParams["domain"], $secure, $httponly);
session_name($session_name); // Sets the session name to the one set above.
session_start(); // Start the php session
session_regenerate_id(); // regenerated the session, delete the old one.
}
login_check() function:
function login_check($db)
{
// Check if all session variables are set
if(isset($_SESSION['user_id'], $_SESSION['username'], $_SESSION['login_string']))
{
$user_id = $_SESSION['user_id'];
$login_string = $_SESSION['login_string'];
$username = $_SESSION['username'];
$user_browser = $_SERVER['HTTP_USER_AGENT']; // Get the user-agent string of the user.
$query = "SELECT password FROM users WHERE id = " . $user_id . " LIMIT 1";
$result = mysql_query($query, $db);
if (mysql_num_rows($result) == 1)
{
// If the user exists
$row = mysql_fetch_row($result);
$password = $row[0];
$login_check = hash('sha512', $password.$user_browser);
if($login_check == $login_string)
{
// Logged In!!!!
return true;
}
else
{
// Not logged in
return false;
}
}
else
{
// Not logged in
return false;
}
}
else
{
// Not logged in
return false;
}
}
I will add an answer as this can help others.
So using sec_session_start() will use different SESSION ID on every page request, particularly
session_regenerate_id();
If your site loads a page very slow and user opens a another link on you page while first page is not loaded fully SESSION ID will be lost hence causing a problem.
Just remove session_regenerate_id(); from sec_session_start function.
function User_CustomValidate(&$usr) {
$appKey = "xxxxx";
$safeurl = 'https://safe.xxxx.com/login/sso/SSOService?app=playbooks';
// first call back after safe login - POST is set
if ($_POST && isset($_POST['digest']))
{
$digest = $_POST["digest"];
// set the session variables ...
$_SESSION['username'] = $_POST["firstname"]." ".$_POST["lastname"];
$_SESSION['firstname'] = $_POST["firstname"];
$_SESSION['lastname'] = $_POST["lastname"];
$_SESSION['email'] = $_POST["email"];
$_SESSION['uid'] = $_POST["uid"];
// Needed for key
$uid = $_POST["uid"];
$time = $_POST["time"];
// Read the property file with the key and URL so this won't go into the main code ...
// this sets $appKey and $safeurl
$mykey = "".$uid.$time.$appKey;
$mydigest = md5($mykey);
}
// session is not initialized as we never got the post above to set session vars
// call now the safe login to get the post to set the session vars ...
if (!isset($_SESSION['uid']) || empty($_SESSION['uid']))
{
// Read the property file with the key and URL so this won't go into the main code ...
// this sets $appKey and $safeurl
header("Location: ".$safeurl);
}
$usr = $_SESSION['uid'];
$this->setCurrentUserName($usr);
return TRUE;
}
I am creating a SSO function that is supposed to carry over the SSO digest data to my applications. I am having an issue with a variable that I cannot figure out. All of my SESSION variables are working and I can clearly see their results on all of my pages. So when I echo $_SESSION['uid'] I can see whatever uid that is passed from our SSO. But I am getting nothing from $usr. I have the statement $usr = $_SESSION['uid'] and it returns nothing. However when I set $usr to '888888' it returns that static uid and everything works. How can I get the session uid passed right?
I am thinking this is a syntax issue but I have tried it a few different ways. PHP 5.4.16 running on IIS 6 (these are not my choices).
I cannot get $usr to be set to $_SESSION['uid']. I ran a dump right after setting it and I see the uid info for the session data but NULL for $usr. Syntax wrong? What do you think is going on?
function User_CustomValidate(&$usr, &$pwd) {
session_start(); // Initialize Session data
ob_start(); // Turn on output buffering
$appKey = "pwssssssssssssss";
$safeurl = 'https://safe.ssssss.com/login/sso/SSOService?app=playbooks';
// first call back after safe login - POST is set
if ($_POST && isset($_POST['digest']))
{
$digest = $_POST["digest"];
// set the session variables ...
$_SESSION['usernames'] = $_POST["firstname"]." ".$_POST["lastname"];
$_SESSION['firstname'] = $_POST["firstname"];
$_SESSION['lastname'] = $_POST["lastname"];
$_SESSION['email'] = $_POST["email"];
$_SESSION['uid'] = $_POST["uid"];
// Needed for key
$uid = $_POST["uid"];
$time = $_POST["time"];
// Read the property file with the key and URL so this won't go into the main code ...
// this sets $appKey and $safeurl
$mykey = "".$uid.$time.$appKey;
$mydigest = md5($mykey);
}
// session is not initialized as we never got the post above to set session vars
// call now the safe login to get the post to set the session vars ...
if (!isset($_SESSION['uid']) || empty($_SESSION['uid']))
{
// Read the property file with the key and URL so this won't go into the main code ...
// this sets $appKey and $safeurl
header("Location: ".$safeurl);
}
$usr = $_SESSION['uid'];
var_dump($usr, $_SESSION['uid']);
$this->setCurrentUserName($usr);
return TRUE;
}
So var_dump shows $usr = NULL and $_SESSION['uid'] with proper employee ID passed by SSO.
Have you verified that your POST data is correct? I think the issue may be, without seeing the surrounding code, that the code inside your if statements are not being executed. You need to confirm that your POST variable "digest" is set. Or for testing if before that if statement you set $_POST['digest'] and $_POST['uid'] then you will find i think that the var_dump will not be null.
function User_CustomValidate($usr, $pwd) {
session_start(); // Initialize Session data
ob_start(); // Turn on output buffering
$appKey = "pwssssssssssssss";
$safeurl = 'https://safe.ssssss.com/login/sso/SSOService?app=playbooks';
// first call back after safe login - POST is set
$_POST['digest'] = 'test';
$_POST['uid'] = 1234;
if ($_POST && isset($_POST['digest'])) {
$digest = $_POST["digest"];
// set the session variables ...
$_SESSION['usernames'] = $_POST["firstname"]." ".$_POST["lastname"];
$_SESSION['firstname'] = $_POST["firstname"];
$_SESSION['lastname'] = $_POST["lastname"];
$_SESSION['email'] = $_POST["email"];
$_SESSION['uid'] = $_POST["uid"];
// Needed for key
$uid = $_POST["uid"];
$time = $_POST["time"];
// Read the property file with the key and URL so this won't go into the main code ...
// this sets $appKey and $safeurl
$mykey = "".$uid.$time.$appKey;
$mydigest = md5($mykey);
}
// session is not initialized as we never got the post above to set session vars
// call now the safe login to get the post to set the session vars ...
if (!isset($_SESSION['uid']) || empty($_SESSION['uid']))
{
// Read the property file with the key and URL so this won't go into the main code ...
// this sets $appKey and $safeurl
header("Location: ".$safeurl);
}
$usr = $_SESSION['uid'];
var_dump($usr, $_SESSION['uid']);
$this->setCurrentUserName($usr);
return TRUE;
}
Another attempt at designing a user membership. Got to log in successfully, finds the data in the database. But in my index file, after logging in, it should check if I'm logged in and display links to my account instead of register and login. Here's the code:
<?php
session_start(); // Must start session first thing
// See if they are a logged in member by checking Session data
$toplinks = "";
if (isset($_SESSION['id'])) {
// Put stored session variables into local php variable
$userid = $_SESSION['id'];
$username = $_SESSION['username'];
$toplinks = '' . $username . ' •
Account •
Log Out';
} else {
$toplinks = 'Register • Login';
}
?>
And here is the login form code, where I think the problem is because it's not storing my session id:
<?php
if ($_POST['email']) {
//Connect to the database through our include
include_once "connect_to_mysql.php";
$email = stripslashes($_POST['email']);
$email = strip_tags($email);
$email = mysql_real_escape_string($email);
$password = preg_replace("[^A-Za-z0-9]", "", $_POST['password']);
// filter everything but numbers and letters
$password = md5($password);
// Make query and then register all database data that -
// cannot be changed by member into SESSION variables.
// Data that you want member to be able to change -
// should never be set into a SESSION variable.
$sql = mysql_query("SELECT * FROM users WHERE email='$email' AND password=
'$password'AND emailactivated='1'");
$login_check = mysql_num_rows($sql);
if($login_check > 0){
while($row = mysql_fetch_assoc($sql)){
// Get member ID into a session variable
$userid = $row["id"];
$_SESSION['id'] = $userid;
// Get member username into a session variable
$username = $row["username"];
$_SESSION['username'] = $username;
// Update last_log_date field for this member now
mysql_query("UPDATE users SET lastlogin=now() WHERE id='$userid'");
// Print success message here if all went well then exit the script
header("location: member_profile.php?id=$userid");
exit();
} // close while
} else {
// Print login failure message to the user and link them back to your login page
print '<br /><br /><font color="#FF0000">No match in our records, try again
</font> <br/>
<br />Click here to go back to the login page.';
exit();
}
}// close if post
?>
Once again I'm following someone's tutorial and trying to implement it to my website and this would be perfect if it worked. Please advice why the $toplinks aren't being set after logging in.
I think the problem is, that you have to include the session_start() in every file where you want to use your session. Otherwise its working in the file like a normal array but not global. In your form i can't see that you start your session.
Edit: You need this only if you have 2 files. When you have only one file and include the other page its working when you include in once on top.
If you want to log out, then you should create a logout file, and include
session_destroy();
probably add also a href to get redirection link by doing something like:
header('location:index.php'); // will return you to index as soon as you logout.