0

Today I have an interesting problem, where I need to take data stored in $_SESSION['form'][$key] and convert it to a local variable.

For example, lets say $_SESSION['form'] contains the following session keys:

$_SESSION['form']['name']
$_SESSION['form']['email']
$_SESSION['form']['age']

How can I convert these $_SESSION variables to:

$name
$email
$age

I was thinking that a for loop would work well for this, but I am not sure how to do that properly for this situation.

Thank you for your help!

2
  • 2
    you can work with $_SESSION['form']['name'] in just the same way as $name so are you sure you need to do this ? Commented Aug 26, 2014 at 4:30
  • extract($_SESSION['form']) ? (But be careful - read warnings) Commented Aug 26, 2014 at 4:31

3 Answers 3

2

You need to use the PHP extract function.

in your case it should be

<?php

$name = "its existing variable"; \\ note this existing variable ;)

extract($_SESSION['form'], EXTR_PREFIX_SAME, "from_session");

echo "$from_session_name, $email, $age, $name\n";

?>
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you very much! Just one question: Does $name already need to be existing like you had done in the example?
No I just tried to demonstrate what it will do if there is a conflict in variable names.. for example here the "name" was an existing variable so it appended the prefix.
0

The way to solve you problem is simple:

extract($_SESSION['form'])

However, this is not the BEST way to do it. There is no reason to absolutely need to have the variables defined as their associative index. You can just access the associative array with the subscript.

1 Comment

So then what is the best way to do it?
0

I had the same issue porting an application that relied on POST or GET variables treated as local from old PHP versions (it will work for any associative array as _COOKIE or _SESSION as well).

When upgrading the OS, no script worked at all, so I made a workaround that did the trick. For this, I did a small php script (i.e. "convertirVarsLocales.php") with the following code:

<?
$keys = array_keys($_GET); 
$values = array_values($_GET);
for($i=0;$i<count($_GET);$i++) { 
        $$keys[$i] = $values[$i];
  }
$keys = array_keys($_POST);
$values = array_values($_POST);
for($i=0;$i<count($_POST);$i++) {
        $$keys[$i] = $values[$i];
}
?>

and included this file:

include("convertirVarsLocales.php");

on every script that relied on this functionality. This is NOT a secure option, but it seems to work ok on secured environments (users with a billing system on closed network). Hope this helps. Regards

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.