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.
Related
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]);
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.
I'm having trouble accessing a $_SESSION variable on an external page.
Basically, I have a form on a drupal node, which when submitted, POSTS to an external php file which saves the value to a $_SESSION variable like so:
//Bootstrap Drupal so we can use the SESSION variables, where we store the calling number for the
//duration of the logged in session
define('DRUPAL_ROOT', $_SERVER['DOCUMENT_ROOT']);
$base_url = 'http://'.$_SERVER['HTTP_HOST'];
require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_SESSION);
//Save number as the calling number for the session
$_SESSION['calling-number']=$_REQUEST['calling-number'];
That works fine.
When I later try and access the $_SESSION variable from an external page using:
//Bootstrap Drupal so we can use the SESSION variables, where we store the calling number for the
//duration of the logged in session
define('DRUPAL_ROOT', $_SERVER['DOCUMENT_ROOT']);
$base_url = 'http://'.$_SERVER['HTTP_HOST'];
require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_SESSION);
echo $_SESSION['calling-number'];
I get nothing. If I look at the $user on this new page, I can see that it is because it is running under an anonymous user session (uid = 0), instead of the logged in user ID which set the $_SESSION variable, and thus it can't find it.
Any ideas why I'm not using the session of the logged in user?
EDIT
Not sure why this is, but as long as the two external files are in different directories, this works fine. If they are in the same directory, it seems to start a new session and not access the existing one. No idea why though.
If I understand correctly, you submit a form from Drupal, where there is an authenticated user, to an external PHP file. When you try accessing the session from an external page, which bootstraps Drupal, the session doesn't contain the previously saved value, and the user is reported to be an anonymous user, and not the authenticated user who previously committed the form.
This normally happens because:
Drupal doesn't find the cookies whose names are session_name(), and substr(session_name(), 1).
In this case, drupal_session_initialize() executes the following code.
// Set a session identifier for this request. This is necessary because
// we lazily start sessions at the end of this request, and some
// processes (like drupal_get_token()) needs to know the future
// session ID in advance.
$GLOBALS['lazy_session'] = TRUE;
$user = drupal_anonymous_user();
// Less random sessions (which are much faster to generate) are used for
// anonymous users than are generated in drupal_session_regenerate() when
// a user becomes authenticated.
session_id(drupal_hash_base64(uniqid(mt_rand(), TRUE)));
if ($is_https && variable_get('https', FALSE)) {
$insecure_session_name = substr(session_name(), 1);
$session_id = drupal_hash_base64(uniqid(mt_rand(), TRUE));
$_COOKIE[$insecure_session_name] = $session_id;
}
Drupal doesn't find a record in its sessions database table for a sid (or ssid) equal to the value of the $sid argument passed to its session read callback (_drupal_session_read()). This could also happen if the session has expired.
if ($is_https) {
$user = db_query("SELECT u.*, s.* FROM {users} u INNER JOIN {sessions} s ON u.uid = s.uid WHERE s.ssid = :ssid", array(':ssid' => $sid))->fetchObject();
if (!$user) {
if (isset($_COOKIE[$insecure_session_name])) {
$user = db_query("SELECT u.*, s.* FROM {users} u INNER JOIN {sessions} s ON u.uid = s.uid WHERE s.sid = :sid AND s.uid = 0", array(
':sid' => $_COOKIE[$insecure_session_name],
))
->fetchObject();
}
}
}
else {
$user = db_query("SELECT u.*, s.* FROM {users} u INNER JOIN {sessions} s ON u.uid = s.uid WHERE s.sid = :sid", array(':sid' => $sid))->fetchObject();
}
Drupal always save the session for the current user when PHP shutdowns, through _drupal_session_write(). It is done also when the current user is an anonymous user.
if (!drupal_save_session()) {
// We don't have anything to do if we are not allowed to save the session.
return;
}
// Check whether $_SESSION has been changed in this request.
$last_read = &drupal_static('drupal_session_last_read');
$is_changed = !isset($last_read) || $last_read['sid'] != $sid || $last_read['value'] !== $value;
// For performance reasons, do not update the sessions table, unless
// $_SESSION has changed or more than 180 has passed since the last update.
if ($is_changed || !isset($user->timestamp) || REQUEST_TIME - $user->timestamp > variable_get('session_write_interval', 180)) {
// Either ssid or sid or both will be added from $key below.
$fields = array(
'uid' => $user->uid,
'cache' => isset($user->cache) ? $user->cache : 0,
'hostname' => ip_address(),
'session' => $value,
'timestamp' => REQUEST_TIME,
);
// Use the session ID as 'sid' and an empty string as 'ssid' by default.
// _drupal_session_read() does not allow empty strings so that's a safe
// default.
$key = array(
'sid' => $sid,
'ssid' => '',
);
// ...
db_merge('sessions')
->key($key)
->fields($fields)
->execute();
}
For those who have the same problem when using an external page:
You just have to put some more parameters to the code
In fact, you have to precise your drupal directory.
Ex. for a page which is in the directory before your drupal directory
// Definine the path to "DRUPAL_ROOT" which is used throughout bootstrap.inc
define('DRUPAL_ROOT', getcwd() . '/your_drupal_directory');
// you could write like this too
// define('DRUPAL_ROOT', $_SERVER['DOCUMENT_ROOT'] . '/your_drupal_directory');
// Define the $base_url which will be used by Drupal to make sure we are on the same domain
$base_url = 'http://'.$_SERVER['HTTP_HOST']. '/your_drupal_directory';
require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_SESSION);
echo $_SESSION['calling-number'];
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.
I use the following piece of code in an include file. Because it it used in two instances within my code, I wanted to separate it into another include file and use with require_once() where it is needed. However, I noticed that if I do that, the cookies won't set. Everything else seems to work though. Is this a bug or this just can't be done this way.
I have been learning PHP only for two weeks so please take it easy on me.
Thank you!
if(mysqli_num_rows($checklogin) == 1)
{
// set variables
$row = mysqli_fetch_array($checklogin);
$email = $row['Email'];
// create login sessions
$_SESSION['UserName'] = $username;
$_SESSION['Email'] = $email;
$_SESSION['LoggedIn'] = 1;
$cbxRememberMe = $_POST['cbxRememberMe'];
// if remember me is checked
if(isset($cbxRememberMe) && $cbxRememberMe == '1')
{
$row = mysqli_fetch_array($checklogin);
// create cookies for autologin
$expire = time() + AUTO_LOGIN_DURATION;
$cookie_un = sha1(sha1($row['UserName']));
$cookie_pass = sha1(sha1($row['Password']));
setcookie('user', $cookie_un, $expire);
setcookie('pass', $cookie_pass, $expire);
}
// get user's IP address
$lastloginip = $_SERVER['REMOTE_ADDR'];
// DB QUERY: update database activity
// ------------------------------------------------------------------
$updateactivity = mysqli_query($conn,"UPDATE users SET LastLoginDate = NOW(), LastActivityDate = NOW(), LastLoginIP = '$lastloginip' WHERE UserName = '$username'")
or die($updateactivity_error);
// ------------------------------------------------------------------
// redirect back to login to refresh
header('Location: login.php');
}
A require()/include()'d file will execute exactly the same as if its contents had been embedded in the file doing the require/include. A cookie header looks exactly the same whether it's directly in a file, or done via an inclue.
I'd look at whether you've actually done a mysqli query before the require once line, since you've wrapped the entire include with that if (mysqli_num_rows(... business. Perhaps you should move the query definition/execution business into the include file as well.