Is there a way to execute required php file once per session? - php

I am new to php and have just written a basic index.php that will display family tree information for an individual based on input id.
The index.php includes a file called "xml-people-list.php" which loads the information from the family tree and creates a sorted list of people.
My problem is that every time you click on a person to display their details, the included php is reloaded which causes the read from file and creation of sorted list to happen again.
Is there a way to only run this code once per session to avoid multiple loads?
I tried to look at session variables but wasn't sure if they would help or how to use them in this case or if there is another way?
Contents of "xml-people-list.php:
<?php require 'xml-load-person.php';
if (file_exists('people.xml'))
{
$people = simplexml_load_file('people.xml');
foreach ($people->person as $person)
{
$person_list[(string)$person['ID']] = strtoupper($person->FamilyName) . ", " . $person->GivenNames;
}
asort($person_list);
}
else
{
exit('Failed to open people.xml.');
}
?>
Thanks for any help!

Yes, you could use session variables. If you wanted to only parse the list once per visitor, and then "cache" the result into a session variable, you could do something like this (for a simple example):
if (!empty($_SESSION['person_list'])) {
// Here we fetch and decode the the ready list from a session variable, if it's defined:
$person_list = json_decode($_SESSION['person_list']);
}
// Otherwise we load it:
else {
require 'xml-load-person.php';
if (file_exists('people.xml'))
{
$people = simplexml_load_file('people.xml');
foreach ($people->person as $person)
{
$person_list[(string)$person['ID']] = strtoupper($person->FamilyName) . ", " . $person->GivenNames;
}
asort($person_list);
// Here we assign the ready list to a session variable (as a JSON string):
$person_list = json_encode($person_list);
$_SESSION['person_list'] = $person_list;
// Here we revert the JSON-encoded (originally SimpleXML) object into a stdClass object.
$person_list = json_decode($person_list);
}
else
{
exit('Failed to open people.xml.');
}
}
You will need to call session_start() in your file (either this one, or any other file including it, but importantly before any output is sent to the browser). Homework: Read up on sessions in PHP.
Update: Since SimpleXML objects can't be serialized, and since adding an object to $_SESSION causes serialization, I've updated the answer to json_encode/decode the object. Yes there's a bit of processing, but that'd be the case with the default serialization as well, and json_en/decode is fairly light-weight. Certainly heaps lighter than parsing XML on each page load!
Be aware that the returned object will be a stdClass object, not a SimpleXML object. I'm assuming it won't be a problem in your use case.

Maybe try require_once() function

1) First of all, try to see if your buttons are anchor tags then be sure that the href attribute is directing to # example: <a href="#">
2) try to use include_once instead of requiring
3) if you tried this and these couple solutions didn't work for you you can send the id of a person using the global $_GET variable
//this should be you URL http://localhost/projectname/index.php?person_id=1
// your href of each person should appoint to their URL
// <a href="index.php?person_id=1">
you can use this $_GET['person_id'] and store it into a variable so it will give you the id of person.

Related

How to unserialize codeigniter session data from database

I wan to use CI session in a external script and I got following data from database.
__ci_last_regenerate|i:1446535049;ci_UserID|s:1:"2";ci_UserName|s:24:"example#xyz.com";logged_in|b:1;
I have tried unserialize and unserialize(base64_decode($data)) but I am fail yet.
Please help to extract this data.
I got the solution here
So I have used session decode
session_decode('__ci_last_regenerate|i:1446535049;ci_UserID|s:1:"2";ci_UserName|s:24:"example#xyz.com";logged_in|b:1;');
So session decode stored all the encrypted data in normal php session.
Which I can access using: echo $_SESSION['ci_UserID'];
Well guys thanks for the help
If this is a session variable, you can use CodeIgniter's own session library. Consider the following code (in a controller):
$this->load->library('session'); // load the session library
$session_data = $this->session->all_userdata(); // get all session data
print_r($session_data); // print and get the corrresponding variable name, e.g. "item"
$var = $this->session->userdata('item'); // pick one that suits your needs, e.g. item
Sorry, I have read "the external script" only after having posted the code. This obviously only works in the CI framework.
For an external script you may need to have a closer look. The variables are separated by ";" and "|" and then serialized, so this might work (not tested):
$row = explode(';', '__ci_last_regenerate|i:1446535049;ci_UserID|s:1:"2";ci_UserName|s:24:"example#xyz.com";logged_in|b:1;'); // load the database row
$userid = explode('|', $row[1]);
$userid = unserialize($userid[1]); // now $userid holds the value "2"

Create a variable in one function and pass it to another in PHP

Let me first say I've spent a day reading three google pages of articles on this subject, as well as studied this page here.
Ok, here's my dilemma. I have two functions. Both called upon via AJAX. This first one assigns a value to the variable and the second one uses that variable. Both functions are triggered by two separate buttons and need to stay that way. The AJAX and the firing off of the functions work fine, but the variable isn't passed. Here is my code:
if( $_REQUEST["subjectLine"] ) //initiate first function
{
$CID = wpCreateChimpCampaign();
echo $CID; //this works
}
if( $_REQUEST["testEmails"] ) //initiate second function
{
echo $CID; //does not return anything but should contain "apple"
wpSendChimpTest($CID);
}
function wpCreateChimpCampaign () //first function
{
$CID = "apple";
return $CID;
}
function wpSendChimpTest ($CID) //second function
{
echo $CID; //does not return anything but should contain "apple"
}
I'm open to using a class but I haven't had much luck there either. I was hoping to solve this issue without using classes. Thanks for the help in advance!
If you are making 2 separate calls to this file, it may be helpful for you to visualise this as being 2 functions in 2 totally separate files. Although they exist in the same PHP file, because they used called in different calls, they don't retain the value of the variable $CID. Once the file has run, the variable is destroyed and when you call the file again, the value is null again.
So you need to store that variable between calls. You can either store it in a database or store it in a session variable.
So call session_start(); at the beginning of the file, then rather than use $CID, just use $_SESSION['CID'];
I'm not sure where the hold up is. The code you have will work:
$CID = wpCreateChimpCampaign(); // returns 'apple'
wpSendChimpTest($CID); // echos 'apple'
The code looks fine, but are you certain that all requirements are being met so both functions execute?
In other words are you supplying values for both $_REQUEST["subjectLine"] and $_REQUEST["testEmails"]?

Detecting History Change using PHP?

Here is what I would do in JavaScript. Is there any way to do it in php?
I am working on a project that needs this functionality but cannot use JavaScript.
setInterval ( "checkHistory()", 1000 );
function checkHistory() {
if (oldHistLength != history.length) {
removegateway();
oldHistLength = history.length;
}
}
Sorry to say that it's not possible to do that using PHP. Your only option is to use JavaScript somewhere.
You can however achieve what I believe you're trying to do with another technique - PHP Sessions and Request URIs.
This involves storing the user's accessed URLs into a variable (or you could use MySQL) which can be referenced anywhere on the website within that current session.
Here's an (untested) example:
<?php
session_start();
// Retrieve/create the current list
if( isset($_SESSION['history']) ) {
$history = $_SESSION['history'];
} else {
$history = new array();
}
// Add the current URL to the history array
array_push($history, $_SERVER['REQUEST_URI']);
// Do anything else you want to here
// Store the array again
$_SESSION['history'] = $history;
?>
In your code, you can keep an array containing the values of $_SERVER['php_self'], serialize() it, and store it in a session variable. This may not be sufficient for what you are trying to do though. I'm not sure what removegateway() does, but is this code attempting to prevent the back button from being used?
If you prevent the pages from being cached, you might be able to compare the second to the last value in your array to the current page, and if they match, you detected a back button. This would only be possible if there's no way to go back to the previous page on the front end.
Preventing the back button is generally considered a Bad Thing, so it might be better to reconsider the way you are doing things and come up with a better solution.

PHP GET variables pass along while browsing

My site is organized into topics. Users can switch between topics on any page, at any time. I would like to be able to pass this topic along from page to page. I am guessing this should be done in a php post or get variable. I can grab the topic from the post or get variable and then run the rest of my site. However, this seems like it requires a form on every page to pass along this variable. As of now, the only way I have passed post or get variables was from forms on the previous page. I have never passed along these variables over several pages. Will I need a form on every page to pass these variables? Also, is this the standard way of doing this?
You should probably use GET, because it sounds like you're just trying to display different information, and POST is supposed to be for performing changes or actions.
If you decide to use GET variables, all you have to do is append them to the end of the link's href:
MORE BANANAS
the least overhead method of doing this would be to add some javascript that sets a cookie each time someone navigates to a new topic. This would assume you can select somehow all links that match topics (presumably trough classes)
A better method - because of compatibility,reliability and overhead - but not necessarily feasible, if a large number of links needs changing, is to use GET requests, as another poster suggested
You can create a helper function to generate your anchor tags and just append any existing query string to it, so instead of this:
Foobar
you would do this:
<?php echo anchor('page2.php','Foobar'); ?>
where your function would look like this:
/**
* Function creates an anchor tag and optionally
* appends an existing query string
* #param string $url
* #param string $txt
* #param bool $attach_qs Whether or not to follow a query string
*/
function anchor($url, $txt, $attach_qs = true)
{
$qs = '';
if ($attach_qs === true) {
$qs = (!empty($_SERVER['QUERY_STRING'])) ? '?' . $_SERVER['QUERY_STRING'] : '';
}
return '' . $txt . '';
}
Kolink's suggestion of placing the topic in via a PHP echo statement for every URL would certainly work. There is however, another option that I am surprised hasn't come up yet.
You could use PHPs Session Manager to store the variable. It is similar to using cookies; however, it is only temporary (limited to the session). Where a cookie can be persistent over multiple sessions.
<?php
// use this code before the page is generated, before the topic is decided.
session_start();
if (isset($_GET['topic']) && $_GET['topic'] != $_SESSION['topic']) {
// GET['topic'] is set, session variable does not match
// you may want to sanitize or limit what can be passed via ?topic=
$_SESSION['topic'] = $_GET['topic'];
} else if (isset($_SESSION['topic'])) {
// Session topic is not empty, run code to display appropriate content
} else {
// No topic is set, display default
}
?>
It's by no means the only solution, but it does give you an extra option.

Increase cohesion by reusing a PHP function for multiple RSS feeds

My homepage contains weather for three cities around the world as displayed in the image
In the home page I declare 3 variables storing the RSS URL for each city
$newYorkWeatherSource = 'http://weather.yahooapis.com/forecastrss?p=USNY0996&u=f';
$londonWeatherSource = 'http://weather.yahooapis.com/forecastrss?p=UKXX0085&u=c';
$parisWeatherSource = 'http://weather.yahooapis.com/forecastrss?p=FRXX0076&u=c';
I pull identical tags out of the three URL's displayed above and use 3 identical functions apart apart from the variable passed into it.
Below shows the variable being passed into the function. Obviously other functions are used before $weather can be returned.
function new_york_current_weather($newYorkWeatherSource) {
// Get XML data from source
if (isset($newYorkWeatherSource)) {
$feed = file_get_contents($newYorkWeatherSource);
} else {
echo 'Feed not found. Check URL';
}
checkWeatherFeedExists($feed);
$xml = new SimpleXmlElement($feed);
$weather = get_dateTime($xml);
$weather = get_temperature_and_convert($xml);
$weather = get_conditions($xml);
$weather = get_icon($xml);
return $weather;
}
As I mentioned, I current repeat this function 3 times just replacing the $newYorkWeatherSource variable that is passed in the above example. Any ideas how I could reuse this function 3 times but yet pass in different URL to keep my homepage showing weather from the 3 cities? Ofcourse, it's easy to reuse the function if each city was represented on individual pages but the purpose is to keep them together for comparison.
Any ideas?
Thanks in advance.
As I mentioned, I current repeat this function 3 times just replacing the $newYorkWeatherSource variable that is passed in the above example. Any ideas how I could reuse this function 3 times but yet pass in different URL to keep my homepage showing weather from the 3 cities?
Maybe I'm entirely missing the point of your question, but are you asking how to rename the function and variables? Because, if so, it's just a matter of search and replace on the first few lines of the function...
function get_current_weather($rss_url) {
// Get XML data from source
if (isset($rss_url)) {
$feed = file_get_contents($rss_url);
} else {
echo 'Feed not found. Check URL';
}
// ...
Simply replace the city-specific functions with one starting out like this, and call it three times, one time for each specific city RSS feed URL.
From the comments:
but I'm just wondering what I will do with the 3 RSS URL variables because I can't replace rename them all to $rss_url as I will just be overwriting them until eventually the only URL will be Paris
I believe you may be suffering from a misunderstanding about PHP variable scope. Let's take this snippet as an example:
function bark($dog) {
echo 'The dog says ', $dog, ".\n";
}
$cat = 'meow';
bark($cat);
This code will emit The dog says meow. When you call the bark function with a variable, PHP takes a copy of the data* and passes it into the function as the variable name specified in the function. You don't need to name the variable the same thing both inside and outside. In fact, you can't** even see variables defined outside of a function:
function i_see_you() {
echo 'The dog heard the cat say ', $cat, ".\n";
}
$cat = 'meow';
i_see_you();
This code will emit The dog heard the cat say ., as $cat is out of scope here.
Getting back to the problem at hand, we still have three weather URLs.
$newYorkWeatherSource = 'http://weather.yahooapis.com/forecastrss?p=USNY0996&u=f';
$londonWeatherSource = 'http://weather.yahooapis.com/forecastrss?p=UKXX0085&u=c';
$parisWeatherSource = 'http://weather.yahooapis.com/forecastrss?p=FRXX0076&u=c';
All you need to do in order to make things work is:
echo get_current_weather($newYorkWeatherSource);
echo get_current_weather($londonWeatherSource);
echo get_current_weather($parisWeatherSource);
Inside the function, the proper variable with the proper name will have the proper data, and the right thing will happen.
*: PHP uses something called "copy-on-write", which does what you think it might do. It's completely safe to pass around variables containing large data. It will not consume unexpected amounts of memory. There's no need to use references. In fact, forget I ever said anything about references, you don't need them right now.
**: It's possible to see variables from the global scope by using the global keyword. Globals are bad practice and lead to spaghetti code. You might want to read more about variable scope in PHP.

Categories