简体   繁体   中英

PHP how to separate a query string into variables

I have a paypal form that submits a the value of a custom hidden input. Since I have a few extra pieces of data to parse, I've added them as a query string. ie

<input type="hidden" name="custom" value="payment-type=deposit&user-id=<?php echo $user_id; ?>&user-name=<?php echo $user_name; ?>">

This outputs as:

<input type="hidden" name="custom" value="payment-type=deposit&user-id=1&user-name=admin">

I then have a file called paypal-ipn.php which communicates with paypal and also adds the payment data to my database. I get the values of each of the inputs using the $_POST method, ie

$item_name        = $_POST['item_name']; // wedding name
$booking_id       = $_POST['item_number']; // booking id
$payment_status   = $_POST['payment_status']; // payment status
$payment_amount   = $_POST['mc_gross']; // amount?
$payment_currency = $_POST['mc_currency']; // currency
$txn_id           = $_POST['txn_id']; // transaction id
$receiver_email   = $_POST['receiver_email']; // reciever email i.e. your email
$payer_email      = $_POST['payer_email']; // payer email i.e. client email
$custom_variables = $_POST['custom'];

The last one will (hopefully) return my query string. My question is, how can I separate out my query string into separate variables, ie

$payment_type = PAYMENT TYPE FROM STRING
$user_id = USER ID FROM STRING
$user_name = USER NAME FROM STRING

Is there a way to do this using php?

Here is my latest code that I'm trying based on answers below:

$custom_variables = $_POST['custom'];

parse_str($custom_variables);
echo $payment_type;  
echo $user_id; 
echo $user_name; 

parse_str($str, $output);
$payment_type = $output['payment_type'];
$user_id = $output['user_id'];
$user_name = $output['user_name'];

Use parse string

Parses str as if it were the query string passed via a URL and sets variables in the current scope.

<?php
$str = "first=value&arr[]=foo+bar&arr[]=baz";
parse_str($str);
echo $first;  // value
echo $arr[0]; // foo bar
echo $arr[1]; // baz

parse_str($str, $output);
echo $output['first'];  // value
echo $output['arr'][0]; // foo bar
echo $output['arr'][1]; // baz

?>

http://php.net/manual/en/function.parse-str.php

Updated

parse_str($custom_variables , $output);
$payment_type = $output['payment_type'];
$user_id = $output['user_id'];
$user_name = $output['user_name'];

echo $payment_type;  
echo $user_id; 
echo $user_name; 

You can do something like this:

$string = "payment-type=deposit&user-id=1&user-name=admin";

parse_str($string, $output);
echo $output['payment-type'];
echo $output['user-id'];
echo $output['user-name'];

//Output
deposit1admin

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM