Temporary array? - php

It's a long story that I'm fighting with, so I'm not going to extend to much for now, but and if not possible I will detail the problem.
I'm using Laravel framework. From an ajax call I send data from an upload form (plupload) to a function inside a controller.
Let's say I have the following functions in my controller:
function action_tempupload()
{
$temp = array();
$temp[] = Input::all();
return true;
}
function action_upload($news_id)
{
global $temp;
$input = $temp;
echo "<pre>";
//print_r($news_id);
print_r($input);
echo "</pre>";
exit();
}
function action_save($parameters = array())
{
// create news record in database and
// have a variable containing the news id sent to:
$this->upload($mysql->news_id);
}
Is it possible to have an temporary array, that saves each POST of the form for the image upload and call the array later in another function?

If they're are separate requests, then you can just store the array in a $_SESSION and unset all the created sessions in the last action method.
Click on the link of you need to know more about $_SESSIONS. The usage is pretty straight forward.

Related

How to add and access array from session in PHP

I am new with php. I want store multidimensional associative array in session and also fetch the value of array from session. But I am not able to do this properly.
Below is my code. Thanks.
$myArray = array();
if ((!isset($_SESSION['game']))) {
echo 'the session is either empty or doesn\'t exist';
} else {
$myArray = unserialize($_SESSION['game']);
}
array_push($myArray, new MapResult($keyId, $colorCode, 'NP', $highlow, 'NP', $evenOdd, 'NP'));
session_start();
$_SESSION['game'] = serialize($myArray);
?>
You can't access $_SESSION variables before calling session_start. Also, your serializing of the data is probably pointless. Session data is stored server-side. Serializing would be used if you wanted to dump the session state to a file or to a database or something.
A word of advice...
Instead of littering your code with $_SESSION references, it helps to wrap access in reusable functions. Your code will look nicer and you'll be free to change how session data is stored/accessed at any time without having to refactor your entire app.
// must be called before reading/writing $_SESSION
session_start();
function session_is_initialized() {
return isset($_SESSION['game']);
}
function session_setup() {
$_SESSION['game'] = [/* some initial data */];
}
function session_add_item($item) {
array_push($_SESSION['game'], /* more data */);
}
Now you can write nice clean code
if (!session_is_initialized()) {
session_setup();
}
session_add_item(['some', 'data']);

Sign up with multiple forms

I'm using Laravel and in my website I need to make a registration throw many steps. There is a first view where the user enter his information and a profile picture then a second view to choose the account type and a third view to pay the inscription fee with Paypal.
I want to get all the information in the final view by using Input::all(), I hope there is an easy way to do that
I solved this myself by creating a php class which stores all this data and then create an object of this class and store that in a session.
class data{
public $data1;
public $data2;
public $data3;
//must checks if the data is complete
function checkdata(){
if(condition){
return true;
}else{
return false;
}
}
}
//Store data in session or load existing data from session.
if(isset($_SESSION["data"]){
$data = $_SESSION["data"];
}else{
$data = new data();
$_SESSION["data"] = $data;
}
//do with the data whatever needs to be done. change the variables if needed etc.
$data->$data1 = $_POST["data1"];
//once all data is complete send and save it where it needs to be saved and unset the session
if($data->checkdata()){
saveorsenddata($data);
unset($_SESSION["data"]);
}//else do nothing

CodeIgniter form validation using session variables

How do I get the CodeIgniter form validation to validate the $_SESSION if there is no passed form data? I tried manually setting the $_REQUEST variable, but it doesn't seem to work.
i.e. I have a function search in the controller which validates the form input passed, and either returns you to the previous page with errors, or else moves you onto the next page. But I want this function to also work if you previously filled out this page, and the info is stored in the $_SESSION variable.
function search () {
$this->load->library("form_validation");
$this->form_validation->set_rules("flightID", "Flight Time", "required|callback_validFlightID");
$this->form_validation->set_rules("time", "Flight Time", "required|callback_validFlightTime");
$this->setRequest(array("flightID", "time"));
// adding session check allows for inter-view navigation
if ($this->form_validation->run()) {
// some application logic here
$this->load->view("seats", $data);
} else {
$this->logger->log($_REQUEST, "request");
// redirect back to index
$this->index();
}
}
function setRequest () {
// make sure none of the parameters are set in the request
foreach ($vars as $k) {
if (isset($_REQUEST[$k])) {
return;
}
}
foreach ($vars as $k) {
if (isset($_SESSION[$k])) {
$_REQUEST[$k] = $_SESSION[$k];
}
}
}
You can store the form post info in a session using the following codeigniter functions
$formdata = array(
'flightID' => $this->input->post('flightID'),
'time' => $this->input->post('time')
);
$this->session->set_userdata($formdata);
and the information can be retrieved with the following
$this->session->userdata('flightID')
$this->session->userdata('time')
form_validation works directly with $_POST, so use that instead of $_REQUEST.
What you're trying to do is setting Post values manually which is not natively
supported by CodeIgniter. So what we're doing first is extending the core.
Create a new file (MY_Input.php) and paste the following contents into it:
class MY_Input extends CI_Input{
function set_post($key, $value)
{
$_POST[$key] = $value;
}
}
That's a very basic implementation of your purpose but it's enough to test around. You might want to extend it to make it fit your needs (f.e. allowing the input of arrays).
So now. In your controller you can check if something has been posted by a user. If not you'll be just setting the post variable manually with your new method of the Input class.
class Some_Controller extends CI_Controller{
public function index()
{
// The user hasn't filled out a field?
if(!$this->input->post('a_key'))
{
// Let's set the postfield to the value of a session key
$this->input->set_post('a_key', $this->session->userdata('mystoredkey'));
}
}
}
After having set your postfield manually, it can be handled by the form validation library as it is meant to be.
That should be your way to go :)
You can really do some pretty things if you're not afraid of hacking the core. Many people are, don't be one of them!
Happy coding

Is there any way I can send a variable as an argument to the constructor of a controller in CodeIgniter?

I am new to CodeIgniter. I was just thinking, is there any way I can send any variable to the constructor of a controller, the same way I can do in Java when I create an object?
You can send variables to controller function through URL.
For example, if your URL is www.domain.com/index.php/reports/userdata/35
then your controller function in file controllers/reports.php would look like:
function userdata($userId) {
.....
}
I don't know why you want do this and where you intend to get the variable you are sending from but this does work in this case:
function __construct($f=null) {
parent::__construct();
if($f){
return $f; //Here use the variable for whatsoever you want.
}
}
function testvariable($id) { //Using $id, you could still get the value from url
$myVariable = 3; //Or you could just hard code the value
if($id){
$myVariable = $id;
}
echo $this->__construct($myVariable);
exit;
}
When you run http://localhost/controller/testvariable/54
You'd get the result 54
When you run http://localhost/controller/testvariable
You'd get the result 3
Outside these, the other option would be to define the variable in the construct.

PHP How to implement flash messages

I'm working on a small custom CMS and would like to implement flash messages. I have searched for hours, but I can't find anything that behaves the way I want. And I can't seem to make anything work.
I want to be able to pass a variable (via $_SESSION) to another page and, on that next request, it will be removed. I want to be able to use a keep_flash function, in case I don't want the message to be removed with the next server request.
Can anyone send me in the right direction? I can't really make anything work.
Thanks.
EDIT: Here is some code I am playing with. It sort-of works. When you first visit the page, it sets the $_SESSION and everything is fine. But if you refresh, now it deletes the $_SESSION. If you refresh again, it adds it back...etc. So, if you were to visit the page, refresh, then go to another page the flash message wouldn't be in the $_SESSION. So how can I fix this?
class flash
{
private $current = array();
private $keep = array();
public function __construct()
{
if (isset($_SESSION['flash'])) {
foreach($_SESSION['flash'] as $k=>$v)
{
$this->current[$k] = $v;
}
}
}
public function __destruct()
{
foreach ($this->current as $k=>$v)
{
if (array_key_exists($k,$this->keep) && $this->keep[$k] == $v) {
// keep flash
$_SESSION['flash'][$k] = $v;
} else {
// delete flash
unset($_SESSION['flash'][$k]);
unset($this->current[$k]);
unset($this->keep[$k]);
}
}
}
public function setFlash($key,$value)
{
$_SESSION['flash'][$key] = $value;
}
public function keepFlash($key)
{
$this->keep[$key] = $this->getFlash($key);
}
public function getFlash($key)
{
if (array_key_exists($key,$this->current)) return $this->current[$key];
return null;
}
}
basic idea is to have script always check specific variable in session (usually called 'flash') for content - if not empty display and delete it from session. When message is needed just place is same variable in session and next check would pick it up....
keep_flash in your case would not proceed with delete, or move to other place based on your needs.
for implementation just google it - usually it wrapped in some kind of class - I personally like phpclasses.org or part of framework

Categories