3
votes

py request:

# coding=utf-8
from __future__ import print_function

import requests

headers = {
    # 'content-type': 'application/json',
    'content-type': 'application/x-www-form-urlencoded',
}

params = {
    'a': 1,
    'b': [2, 3, 4],
}

url = "http://localhost:9393/server.php"
resp = requests.post(url, data=params, headers=headers)

print(resp.content)

php recieve:

// get HTTP Body
$entityBody = file_get_contents('php://input');
// $entityBody is: "a=1&b=2&b=3&b=4"

// get POST 
$post = $_POST;
// $post = ['a' => 1, 'b' => 4] 
// $post missing array item: 2, 3

Because I also using jQuery Ajax POST which default content-type = application/x-www-form-urlencoded. And PHP default $_POST only stores value :

An associative array of variables passed to the current script via the HTTP POST method when using application/x-www-form-urlencoded or multipart/form-data as the HTTP Content-Type in the request.

http://php.net/manual/en/reserved.variables.post.php

So, I want to also use Python request the same as jQuery default behavior, What can I do?

1
I don't get it. What's the issue? - FrankBr
I know PHP syntax, the issue is: How can I use Python to send request like @weirdan 's answer in simple way, because I also want to send a more complex JSON with array in it. - vikyd
@Viky - Did you got solution for this in Python? Not sure what weirdan meant by sending data as a=1&b[]=2&b[]=3&b[]=4, does it mean each value needs to be sent as an array? - Shoaib Khan
@ShoaibKhan , Yes, I use Python client sending data to PHP server. I wrote a simple function to convert it now: github.com/vikyd/to_php_post_arr - vikyd

1 Answers

2
votes

PHP will only accept multiple values for variables with square brackets, indicating an array (see this FAQ entry).

So you will need to make your python script to send a=1&b[]=2&b[]=3&b[]=4 and then $_POST on PHP side will look like this:

[ 'a' => 1, 'b' => [ 2, 3, 4] ]