On my website, I allow users to view a users information by simply clicking their name. Once they click the persons name, they can schedule the person to come to an event. When the user clicks "schedule me" I take the them full name from the "user_id" and send it as a "$_SESSION['speaker']" to the next file that pretty much checks if the user came from the last file and takes the name and uses it as the input value for the calendar. The problem I am having is that when the user didn't "click schedule" from the other file and goes to the calendar website alone, the name from the previous person they clicked stays there and I want it to be blank in case they want to put a different name. So pretty much i would access the calendar website just by typing the URL and the name would still be in the session. I want to clear the session without logging the user out so they don't see the name of the previous person they clicked. Here is some of my code
First file
$_GET['speaker'] = $_SESSION['speaker_id'];
$speaker_id = $_GET['speaker'];
$stmtSpeaker = $handler->prepare("SELECT * FROM formdata WHERE user_id= :speaker_id");
$stmtSpeaker->bindParam(':speaker_id', $speaker_id, PDO::PARAM_INT);
$stmtSpeaker->execute();
$formData = $stmtSpeaker->fetch();
if(isset($_POST['schedule_me'])){
$_SESSION['admin'] = $adminBoolean;
$_SESSION['speaker'] = $formData['fullname'];
$_SESSION['speaker_came'] = true;
header("Location: admincalendar.php");
exit;
}
Second file
$adminBoolean = $resultChecker['admin'];
if($_SESSION['speaker_came'] = true){
$speaker = $_SESSION['speaker'];
}else{
$speaker = "";
}
Unset will destroy a particular session variable whereas session_destroy() will destroy all the session data for that user.
It really depends on your application as to which one you should use. Just keep the above in mind.
unset($_SESSION['name']); // will delete just the name data
session_destroy(); // will delete ALL data associated with that user.
You can unset session variable
$adminBoolean = $resultChecker['admin'];
if($_SESSION['speaker_came'] = true){
$speaker = $_SESSION['speaker'];
}else{
unset($_SESSION['speaker']);
unset($_SESSION['speaker_came']);
$speaker = '';
}
You need to first get the tempkey of the element and then unset it. Try this:
if(($tempkey = array_search($speaker_id, $_SESSION['speaker'])) !== FALSE)
unset($_SESSION['speaker'][$tempkey]);
Related
First I log in with one user and then I open a second tab and log in with other user.
Now the problem is that when I go to the tab where I logged in first and refresh it, the username from the second tab overlaps the first one.
I have seen that the two different users have different cookies, but is the second one overlapping the first one, because I try to log in with more than one user on a single machine..My theory is that I am only getting the last session and it sets it everyhwere.So I am wondering how can I make them independent.
This is my PHP code for the session of each user:
`
<?php
session_start();
if(isset($_SESSION["user_id"]))
{
$mysqli = require __DIR__ . "/databaseCon.php";
$sql = "SELECT * FROM users
WHERE user_id = {$_SESSION["user_id"]}";
$result = $mysqli->query($sql);
$user = $result->fetch_assoc();
$getSessions = $mysqli->query("SELECT sessionName FROM sessions");
}
This is my login script. Once logged in, they will be sent to different pages determined by the roles(student or a teacher):
<?php
$is_invalid = false;
#if we opened the page its set to GET, when we submit POST
if ($_SERVER["REQUEST_METHOD"] === "POST")
{
$mysqli = require __DIR__ . "/databaseCon.php";
$sql = sprintf("SELECT * FROM users
WHERE email = '%s'",
$mysqli->real_escape_string($_POST["mail"]));
$result = $mysqli->query($sql);
$user = $result->fetch_assoc();
if ($user)
{
if(password_verify($_POST["passw"], $user["password_hash"]))
{
session_start();
session_regenerate_id();
$_SESSION["user_id"] = $user["user_id"];
$_SESSION["firstName"] = $user["firstName"];
$_SESSION["privilege"] = $user["privilege"];
header("Location: /Controllers/sessionInit.php");
exit;
}
}
$is_invalid = true;
}
?>
`
When your php program feeds its session cookie to the browser, the browser then uses it, immediately, for all its tabs. So starting a session for Bob disconnects your browser from the session for Alice.
It's common during debugging to want to have two user sessions going at once. When I do that, I do one of three things
Use different browsers for different sessions (Chrome, Firefox, Edge etc).
Use a browser's anonymous mode for the second session.
Set up multiple user profiles in the browser, and use the different profiles for different sessions. This can be clunky, however.
In my page, I have:
1. Registration Page
2. Login Page
3. Successful Registration Page
4. Referral Form
In my registration Page, User can register through this.
In my Log-in page, I have two types of user, Applicant and Employee
In my Successful Registration Page, there is a button directs to Referral Form.
In my Referral Form Page, I have a modal there to update referral information provided by the user during the registration.
The following information are:
Referrer ID
Fullname
Current Position
ContactID
Email Address
MObile Number
Member Since
If you created an account on my page, either you are a Applicant or Employee, if you successfully register, my successful registration page will prompt to you and once you have click the button going to Referral Form The following information will be displayed to your referral information based on you supplied during the registration.
If you register as an Applicant, your Referrer ID is always set into 0 and you may edit it through Referral Form Page
or if you register as an Employee, your Referrer ID is based on you provide during the registration.
Example:
Referrer ID (Allowed to edit if you register as an applicant)
Fullname Sherlock Holmes
Current Position (This has no value and may be edit once you created an account)
ContactID CON12344
Email Address SherlockHolmes#gmail.com
MObile Number +987676758857
Member Since 2014-05-06 04:41:21
Here's my problem that I encounter.
I created an account and Successful registration page prompt to me, and I click the button going to Referral Form Page to edit my information. I edit it and Log-it out and try to relog-in, My Information updated and now reflecting on my Information. It works well.
But
When I created an account and promt successful registration page and click the button going to Referral Form Page, If I did not edit my information and tried to log it out and try to re-login, my information becomes having all null values. Like this,
Referrer ID 0
Fullname
Current Position
ContactID
Email Address
MObile Number
Member Since
Which was incorrect because even I did not edit my information, my information should just becomes like this.
Referrer ID 0(You can edit it)
Fullname Sherlock Holmes
Current Position (You can edit it)
ContactID CON12345678
Email Address sherlockholmes#gmail.com (You can edit it)
MObile Number +93456789 (You can edit it)
Member Since 2014-05-06 04:41:21
Problem Occurs when I don't edit my information for a new created account, but when I edit it before I log it out, it's okay.
here is my Successful registration PHp
<?php
include('../include/dbconnection.php');
include('../include/functions.php');
if(!isset($_SESSION))
{
session_start();
}
$empid = $_SESSION['SESS_EMP_ID'];
$conid = $_SESSION['SESS_CONID'];
$fName = $_SESSION['SESS_FIRSTNAME'];
$lName = $_SESSION['SESS_LASTNAME'];
$contactNo = $_SESSION['SESS_CONTACT_NO'];
$mobile = $_SESSION['SESS_MOBILE'];
$email = $_SESSION['SESS_EMAIL'];
$bday = $_SESSION['SESS_BDAY'];
if($conid == '')
{
echo ("<SCRIPT LANGUAGE='JavaScript'>
window.location.href='index.php';
</SCRIPT>");
}
else
{
//Nothing
}
?>
Here is my code in Referral Form
/**** Start Session ****/
session_start();
//Check whether the session variable SESS_EMP_ID is present or not
if(!isset($_SESSION['SESS_EMP_ID']) || (trim($_SESSION['SESS_EMP_ID']) == '')) {
header("Location: LoginPage.php");
exit();
}
/**** End ****/
/**** Redirects automatically to index ****/
header("Refresh: 15 * 60; url=index.php");
/**** End ****/
/**** authentication ****/
//require_once('../function/auth_emp.php');
/**** End ****/
$empid = $_SESSION['SESS_EMP_ID'];
$bdate = $_SESSION['SESS_BDAY'];
/**** Database connection ****/
require_once('../include/config.php');
/**** End ****/
include'../GlobalConstants.php';
include_once ('../refer/updateInfo.php');
mysql_select_db($db_name, $con) or die("ERR_COULD_NOT_SEE_DB");
if($empid == 0)
{
$fname = $_SESSION['SESS_FIRSTNAME'];
$lname = $_SESSION['SESS_LASTNAME'];
$bdate = $_SESSION['SESS_BDAY'];
$pos = $_SESSION['SESS_POSITION'];
$empid = $_SESSION['SESS_EMP_ID'];
$qry= "SELECT vtiger_contactdetails.firstname,
vtiger_contactdetails.contact_no,
vtiger_contactscf.cf_703,
vtiger_contactscf.cf_715,
vtiger_contactscf.cf_717,
vtiger_contactdetails.email,
vtiger_contactdetails.lastname,
vtiger_contactdetails.mobile,
vtiger_contactdetails.contactid,
vtiger_crmentity.createdtime
FROM vtiger_contactdetails
INNER JOIN vtiger_contactscf
ON vtiger_contactdetails.contactid = vtiger_contactscf.contactid
INNER JOIN vtiger_crmentity
ON vtiger_contactdetails.contactid = vtiger_crmentity.crmid
INNER JOIN vtiger_contactsubdetails
ON vtiger_contactsubdetails.contactsubscriptionid= vtiger_contactdetails.contactid
WHERE vtiger_contactdetails.firstname = '".$fname."'
AND vtiger_contactdetails.lastname = '".$lname."'
AND vtiger_contactsubdetails.birthday = '".$bdate."'";
$result = mysql_query($qry);
} else
{
$qry= "SELECT vtiger_contactdetails.firstname,
vtiger_contactdetails.contact_no,
vtiger_contactscf.cf_703,
vtiger_contactscf.cf_715,
vtiger_contactscf.cf_717,
vtiger_contactdetails.email,
vtiger_contactdetails.lastname,
vtiger_contactdetails.mobile,
vtiger_contactdetails.contactid,
vtiger_crmentity.createdtime
FROM vtiger_contactdetails
INNER JOIN vtiger_contactscf
ON vtiger_contactdetails.contactid = vtiger_contactscf.contactid
INNER JOIN vtiger_crmentity
ON vtiger_contactdetails.contactid = vtiger_crmentity.crmid
WHERE vtiger_contactscf.cf_739 = '".$empid."'";
$result = mysql_query($qry);
}
if($result)
{
if(mysql_num_rows($result)> 0)
{
$row = mysql_fetch_assoc($result);
$contact_no = $row['contact_no'];
$fname = $row['firstname'];
$mname = $row['cf_703'];
$lname = $row['lastname'];
$mobile = $row['mobile'];
$pos = $row['cf_715'];
$program = $row['cf_717'];
$email = $row['email'];
$conid = $row['contactid'];
$memberdate = $row['createdtime'];
}
}
$erp = "ERP";
/**** Stores the firstname and lastname in the session ****/
$_SESSION['SESS_EMP_ID'] = $empid;
$_SESSION['SESS_CONID'] = $conid;
$_SESSION['SESS_FIRSTNAME'] = $fname;
$_SESSION['SESS_MIDDLENAME'] = $mname;
$_SESSION['SESS_LASTNAME'] = $lname;
$_SESSION['SESS_MOBILE'] = $mobile;
$_SESSION['SESS_EMAIL'] = $email;
$_SESSION['SESS_POSITION'] = $pos;
$_SESSION['SESS_GEN'] =$erp;
$_SESSION['login_time'] = time();
?>
Do I have problem passing the session variable when the user didn't fill up the information after they created an account?
If user edit and fill up all information and try to re-logout and re-login. It seems okay and works.
But after user created an account, and If I didn't edit the information and log it out and try to re-login, it does not reflect the values.
I won't reflect the value of session when I didn't update the information if I logout and try to re-login. Thanks
Your code is simple to debug.
Try to test it step by step.
Check this variable - $empid
1) When it is 0 then try to output the whole your query on the page and check these conditions.
WHERE vtiger_contactdetails.firstname = '".$fname."'
AND vtiger_contactdetails.lastname = '".$lname."'
AND vtiger_contactsubdetails.birthday = '".$bdate."'";
2) If this whole query outputs correctly (fname, lname, bdate are not empty) then check the result variable. It should return an object and it should not be null.
3) Check the ELSE block. Especially this condition
WHERE vtiger_contactscf.cf_739 = '".$empid."'";
4) If the query is correct (no empty spaces), check the result variable. It must be an object.
I think the issue occurs when you logout the user, you might be flushing all the session values, please add your logout code here so that we can check if their any cause.
There is another this that you can try for this issue.
1) When the user successfully register to you application save the data into temp table with user info along with the non-edited flag.
2) when the user comes on the referral page fetch the current login user data and assign to referral form.
3) If the form get submitted change the flag value.
This will help you to track on the users whose not update their referral form, and you can prompt them on some other pages also, this will make lesser dependency on session, because session will get destroyed eventually when you do logout or might be happen due to server session handling variables also and you will not have any track for those information. Hope this will help you.
I have am creating a Website that showes Visitors Info. Users are able to visit the page and use Textarea to pick a name for their URL, and the name will be saved as a table in mysql database..
I am using the $name variable in my first php file which is a replacement for the text "visitor_tracking". But today I noticed that there is also another php file and more sql codes, and once again I can see that this file also has the "visitor_tracking" text used in the sql code.
But I think I failed big time, because I simply dont know how to replace the "visitor_tracking" text with my the variable name called $name.
<?php
//define our "maximum idle period" to be 30 minutes
$mins = 30;
//set the time limit before a session expires
ini_set ("session.gc_maxlifetime", $mins * 60);
session_start();
$ip_address = $_SERVER["REMOTE_ADDR"];
$page_name = $_SERVER["SCRIPT_NAME"];
$query_string = $_SERVER["QUERY_STRING"];
$current_page = $page_name."?".$query_string;
//connect to the database using your database settings
include("db_connect.php");
if(isset($_SESSION["tracking"])){
//update the visitor log in the database, based on the current visitor
//id held in $_SESSION["visitor_id"]
$visitor_id = isset($_SESSION["visitor_id"])?$_SESSION["visitor_id"]:0;
if($_SESSION["current_page"] != $current_page)
{
$sql = "INSERT INTO visitor_tracking
(ip_address, page_name, query_string, visitor_id)
VALUES ('$ip_address', '$page_name', '$query_string', '$visitor_id')";
if(!mysql_query($sql)){
echo "Failed to update visitor log";
}
$_SESSION["current_page"] = $current_page;
}
} else {
//set a session variable so we know that this visitor is being tracked
//insert a new row into the database for this person
$sql = "INSERT INTO visitor_tracking
(ip_address, page_name, query_string)
VALUES ('$ip_address', '$page_name', '$query_string')";
if(!mysql_query($sql)){
echo "Failed to add new visitor into tracking log";
$_SESSION["tracking"] = false;
} else {
//find the next available visitor_id for the database
//to assign to this person
$_SESSION["tracking"] = true;
$entry_id = mysql_insert_id();
$lowest_sql = mysql_query("SELECT MAX(visitor_id) as next FROM visitor_tracking");
$lowest_row = mysql_fetch_array($lowest_sql);
$lowest = $lowest_row["next"];
if(!isset($lowest))
$lowest = 1;
else
$lowest++;
//update the visitor entry with the new visitor id
//Note, that we do it in this way to prevent a "race condition"
mysql_query("UPDATE visitor_tracking SET visitor_id = '$lowest' WHERE entry_id = '$entry_id'");
//place the current visitor_id into the session so we can use it on
//subsequent visits to track this person
$_SESSION["visitor_id"] = $lowest;
//save the current page to session so we don't track if someone just refreshes the page
$_SESSION["current_page"] = $current_page;
}
}
Here is a very short part of the script:
I really hope I can get some help to replace the "visitor_tracking" text with the Variable $name...I tried to replace the text with '$name' and used also different qoutes, but didnt work for me...
And this is the call that I used in my 2nd php file that reads from my first php file:
include 'myfile1.php';
echo $var;
But dont know if thats correct too. I cant wait to hear what I am doing wrong.
Thank you very much in advance
PS Many thanks to Prix for helping me with the first php file!
first you need to start session in both pages. it should be the first thing you do in page before writing anything to page output buffer.
In first page you need to assign the value to a session variable. if you don't start session with session_start you don't have a session and value in $_SESSION will not be available.
<?php
session_start(); // first thing in page
?>
<form action="" method="post" >
...
<td><input type="text" name="gname" id="text" value=""></td>
...
</form>
<?PHP
if (isset($_POST['submit'])) {
$name = $_POST['gname'];
//...
//Connect to database and create table
//...
$_SESSION['gname'] = $name;
...
// REMOVE THIS Duplicate -> mysql_query($sql,$conn);
}
?>
in second page again you need to start session first. Before reading a $_SESSION variable you need to check if it has a value (avoid errors or warnings). next read the value and do whatever you want to do with it.
<?php
session_start(); // first thing in page
...
if(isset($_SESSION['gname'])){
// Read the variable from session
$SomeVar = $_SESSION['gname'];
// Do whatever you want with this value
}
?>
By the way,
In your second page, I couldn't find the variable $name.
The way you are creating your table has serious security issue and least of your problems will be a bad table name which cannot be created. read about SQL injection if you are interested to know why.
in your first page you are running $SQL command twice and it will try to create table again which will fail.
Your if statement is finishing before creating table. What if the form wasn't submitted or it $_POST['gname'] was emptY?
there are so many errors in your second page too.
Working on a site that displays different content based on a cookie value. For example:
http://peewee.betaforming.com/
vs.
http://peewee.betaforming.com/?cu=10010
That value can be set on any page because I have a functions include on every page. If the cookie is set or already saved, the information for that CU is loaded. If no cookie value is set or a value is passed that doesn't exist in the DB, he site displays default information.
Here's the problem. If you go from no cookie value set to requesting the site with "?cu=10010" attached to any page, the current page doesn't load the current data until it is refreshed.
From what I've read, I need to refresh the page using header("location.... but I'm not sure where I do that given all that I need to do based on that cookie value.
Here's the relevant code in the functions file for setting/retrieving the cookie.
// CU cookies
if (isset($_GET["cu"]) && is_numeric($_GET["cu"])) {
$pass_cu = $_GET["cu"];
// See if passed value returns an active CU record
mysql_select_db($database_peewee, $peewee);
$query_rs_valid_cu = "SELECT * FROM tbl_cus WHERE cu_id = $pass_cu";
$rs_valid_cu = mysql_query($query_rs_valid_cu, $peewee) or die(mysql_error());
$row_rs_valid_cu = mysql_fetch_assoc($rs_valid_cu);
$totalRows_rs_valid_cu = mysql_num_rows($rs_valid_cu);
if ($totalRows_rs_valid_cu != 0) {
// Set cookie
$peewee_cu_querystring = $_GET["cu"];
$expire_month = time()+60*60*24*30; //30 days
//kill current cookie
setcookie("peewee_cu", "", time()-10);
//set new cookie
setcookie("peewee_cu", $peewee_cu_querystring, $expire_month, "/");
}
mysql_free_result($rs_valid_cu);
}
// See of cookie exists
if ((isset($_COOKIE['peewee_cu'])) && $_COOKIE['peewee_cu'] != "") {
$cu_cookie_value = $_COOKIE['peewee_cu'];
// Set values for getting CU record
$colname_rs_cu_data = $cu_cookie_value;
$load_custom_cu = 'true';
} else {
// Set defualt CU value
$colname_rs_cu_data = 10000;
$load_custom_cu = 'false';
}
// Get and Set CU Information (CU specific or default)
mysql_select_db($database_peewee, $peewee);
$query_rs_cu_data = "SELECT * FROM tbl_cus WHERE cu_id = $colname_rs_cu_data";
$rs_cu_data = mysql_query($query_rs_cu_data, $peewee) or die(mysql_error());
$row_rs_cu_data = mysql_fetch_assoc($rs_cu_data);
$totalRows_rs_cu_data = mysql_num_rows($rs_cu_data);
$cu_sidebar_image = $row_rs_cu_data['cu_logo'];
$cu_sidebar_name = $row_rs_cu_data['cu_name'];
$cu_sidebar_link = $row_rs_cu_data['cu_link'];
$cu_sidebar_address = $row_rs_cu_data['cu_address'];
$cu_sidebar_city = $row_rs_cu_data['cu_city'];
$cu_sidebar_state = $row_rs_cu_data['cu_state'];
$cu_sidebar_postal = $row_rs_cu_data['cu_postal'];
$cu_sidebar_phone = $row_rs_cu_data['cu_phone'];
$cu_sidebar_toll = $row_rs_cu_data['cu_phone_toll_free'];
$cu_meta_title = $row_rs_cu_data['cu_name'];
$cu_tab_title = $row_rs_cu_data['cu_name'];
mysql_free_result($rs_cu_data);
// Set default error page for all pages except home page
$default_error_page = 10007;
$default_error_page_home = 10005;
Thanks
Brett
Reloading the page just to read in a cookie whose value you know (because you've just set it) seems a bit redundant.
Instead, all you need to do is set a variable to either the current cookie value as sent by the browser ($_COOKIE['peewee_cu']) or the value you're assigning to that cookie on the current page ($peewee_cu_querystring).
For a really simple way (but note: I don't particularly recommend writing to superglobals, it's better to have your own variable and manage scope properly) see PHP sets COOKIE, changed with JQUERY COOKIE plugin, cannot be edited with php?
Incidentally, you shouldn't need to kill off the old cookie before setting the new one, as any new cookie with the same name, domain, and path will overwrite it automatically.
i want to keep some variable alive so that it is available to all the pages of the site ;
i tried global but that don't work with these kind of problem ;
i use the following code :
while($result1 = mysql_fetch_array( $result))
{
$adm_no = $result1['adm_no'];
$adm_dt = $result1['adm_dt'];
$name = $result1['name'];
$dob = $result1['dob'];
$f_name = $result1['f_name'];
$f_office = $result1['f_office'];
$f_o_no = $result1['f_o_no'];
$m_name = $result1['m_name'];
$m_office = $result1['m_office'];
$addr = $result1['addr'];
$pho_no = $result['pho_no'];
these same variable in another page called tc.php . how can i do that ????
If you want to access all that data again in another page I would recommend storing the information needed to retrieve data from your mysql table in a session rather than the result of the query. This means you don't have a load of trivial data in your session space. For example.
Imagine I have a person table and want to get bits of information for that person on different pages I just store the person_id in a session like so:
//home.php
$_SESSION['personID'] = $personID;
Then on any page I want to retrieve person information on I just get the person id from the session and run the query to get the specific information I need.
//profile.php
$personID = $_SESSION['personID'];
//Get specific information here
If you really cant change the way that you are doing this which I really hope you can as it'll make your life a hell of a lot easier then just changing your code to this:
//make sure that you have started a session at the top of your page before you do anything else
session_start();
while($result1 = mysql_fetch_array($result)) {
$_SESSION['adm_no'] = $result1['adm_no'];
$_SESSION['adm_dt'] = $result1['adm_dt'];
$_SESSION['name'] = $result1['name'];
$_SESSION['dob'] = $result1['dob'];
//etc
}
Use
$_SESSION['myvar']= "your value";
echo $_SESSION['myvar'];
will can access any page
Fetch data again in tc.php - it is the best way in this case I think.
You can also set that data to the session, and in tc.php get it from there.