Getting php $_GET value in array - php

Trying to get each $_GET from url string request in an array.
So if user A visits site with www.example.com?user="bob", pass to array 'users'.
Now alice visits with www.example.com?user=alice, pass to array 'users'.
I have tried this:
<html>
<body>
<?php>
$Users = array();
$Member = $_GET['name'];
$Users[] = $Member;
print_r($Users);
?>
</body>
</html>
But I still get only the last value, that is..Array( [0] => "Alice" )
Mmm, so do I need a function, to fill the array?
Thnx

try with SESSION ,
<?php
session_start();
$Users = array();
$Member = $_GET['name'];
$_SESSION['users'][] = $Member;
print_r($_SESSION['users']);
?>
For more informations, you can take a look at the Session Handling https://www.php.net/manual/en/book.session.php section of the manual, that gives some useful informations.

PHP creates new process for every web request. Subsequent requests share no memory or other resources. Each time PHP process is created, new memory pool is initialized for this process. So it is impossible to use memory as a storage for subsequent requests.
You need some kind of permanent storage like file on disk or a database. One process can write to this storage and the other one can read from it.

Related

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

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.

Passing a multi-dimensional array using sessions in PHP

I am currently trying to pass a multidimensional array through sessions while also being able to dynamically add/remove from it (it is a wish-list). The index of the array will be the ID of an item I am adding to the array. I've tried serialization, using variables instead of the actual session and none of it worked properly for me.
My issue is that my array will not pass from page 1 to page 2. Page 1 is what happens when the user clicks any "add to wish-list" button
I searched up on Google and wrote something similar to this:
page 1:
session_start();
$_SESSION['wishlist'] = array();
$id = $_GET['id'];
$imageFileName = $_GET['ImageFileName'];
$title = urldecode($_GET['PictureName']);
$_SESSION['wishlist'][$id]=array("id"=>$id,"title"=>$title,"imageFileName"=>$imageFileName); // Here im making the multidimensional array
$_SESSION['wishlist'] = $_POST; //found this way on Stackoverflow
header('Location:view-wish-list.php'); //move to second page
page 2: trying to start session and print out the array to test:
session_start();
var_dump($_SESSION['wishlist']);
Var Dump gives me array(0) { }
Any help would be appreciated. Thank you.
You have to commit (write) the session before redirection or the second request may occur before the session data is available on the server:
session_write_close();
header('Location:view-wish-list.php'); //move to second page

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"

Push multi-dimensional array with new key

I want each time a file is called, to make a new sub-array. So say if I have a URL like http://example.com?name=[INPUT] , every time it calls it will add a new element to the array. With $users being the main array. EA:
$users[0][name] = "John"
$users[1][name] = "Sally"
Each call to the input will create a new $users[INCRIMENTAL_KEY][name] value.
A simple solution would be
$user[]['name'] = $name;
Although if all you are storing is a single item it would be even simpler to do
$user[] = $name;
Although if you want to keep this information across page executions and not be effected by WHO is running the page, you are going to have to keep the information in a database and just add a new row to a table each time the script is run.
You need a persistent way to track the array's data, whether that be sessions, database or files (depends on how long you want persistence for and whether it should be public or per-user).
Session example:
session_start();
// Initialise an empty array
if (empty($_SESSION['users'])) {
$_SESSION['users'] = [];
}
// Add each name to the session array
if (isset($_GET['name'])) {
$_SESSION['users'][] = ['name' => $_GET['name']];
}
Session would of course be per-user and per-session. You could use cookies and/or sessions for a longer persistence per-user, or use flatfile/database storage for more control and non-ending persistence.

POST data to permanent json file using PHP

using a url, my idea is that any user can post data. For example via
http://myweb.com/index.php?name=Peter&surname=Brown
Using the "jedwards" answer, present here, I am able to create a json and save it to a file.
<?
/* This needs to be at the top of your file, without ANYTHING above it */
session_start();
/* ... */
if(!array_key_exists('entries', $_SESSION))
{
$_SESSION['entries'] = array();
}
$_SESSION['entries'][] = array("name" => $_GET["name"], "surname" => $_GET["surname"]);
$json_string = json_encode($_SESSION['entries']);
My problem is that this is not permanent amongst different session or user. It works only on the same session. On different session the json built start from the beginning.
First of all, don't use GET requests to change the state of the server. GET is only supposed to read (or.. um.. GET) data from the server.
In order to change data, use POST. It's more fitted, slightly more secure, and is great when transferring larger amounts of data.
Now, for the problem at hand. For a more permenant solution, the best option is to enforce user registration, and save the required data on a database, with a reference to the user's ID.
Yes because sessions, as the name imply, are only temporary (and sort of local). When the browser is closed it's gone. Depending on what your demands are you'll have to choose between using a database or textfiles on the server.
Cookies or sessions is not made for this kind of data.
Well if you are looking for a rudimentary solution, see below. If not, use a database as suggested in the other answers.
<?
/* This needs to be at the top of your file, without ANYTHING above it */
session_start();
/* ... */
$file = sys_get_temp_dir() . '/entries.json';
$data = file_get_contents($file);
$entries = (!empty($data)) ? json_decode($data) : array();
$entries[] = array("name" => $_GET["name"], "surname" => $_GET["surname"]);
file_put_contents($file,json_encode($entries),FILE_APPEND);

Categories