Christian Rodriguez
Christian Rodriguez

Reputation: 690

php multiple variables single string

I'm trying to send some encrypted data via AJAX to my server, and since I already have things working without encryption, I just want to encrypt the data string that contains all the variables. The question is, how can I extract the variables from this single string in PHP? Right now I've got something like this (generic POST):

$var1 = $_POST['var1'];
$var2 = $_POST['var2'];
$var3 = $_POST['var3'];

And I want to extract the same variables from a string like this:

"var1='value1'&var2='value2'&var3='value3'";

I know I can do it with explode(), but is there an easier form? Using explode I'd have to separate by & and then by = and it can get tedious when dealing with hundreds of variables.

Upvotes: 0

Views: 83

Answers (1)

CarlosCarucce
CarlosCarucce

Reputation: 3569

You can do it by using parse_str.

For example:

$str = "first=1&second=2";

parse_str($str);
echo $first; //Outputs 1
echo $second; //Outputs 2

Documentation here

Beware: parsr_str will overwrite variables with the same names

Upvotes: 3

Related Questions