0

My php file looks like this:

<?php
var_dump($_POST);

Python code:

>>> import requests
>>> data = {'test1': 'ok', 'test2': ['Ok','or','wrong']}
>>> print(requests.post('http://localhost:8000/test.php', data=data).text)
array(2) {
  ["test1"]=>
  string(2) "ok"
  ["test2"]=>
  string(5) "wrong"
}
>>> data = {'test1': 'ok', 'test2': {'w1': 'Ok', 'w2': 'or', 'w3': 'wrong'}}
>>> print(requests.post('http://localhost:8000/test.php', data=data).text)
array(2) {
  ["test1"]=>
  string(2) "ok"
  ["test2"]=>
  string(2) "w3"
}

requests is sending only the last element of lists or dictionaries to $_POST.

Expected behavior: $_POST getting the entire dictionary.

Is it a bug, or I'm doing something wrong?

I'm using php server in ubuntu:

php -version
PHP 7.3.11-0ubuntu0.19.10.3 (cli) (built: Feb 12 2020 15:22:33) ( NTS )
Copyright (c) 1997-2018 The PHP Group
Zend Engine v3.3.11, Copyright (c) 1998-2018 Zend Technologies
    with Zend OPcache v7.3.11-0ubuntu0.19.10.3, Copyright (c) 1999-2018, by Zend Technologies

EDIT:

  • Using requestbin.com (as suggested by Slam), I've checked that requests is actually sending all the data.
  • I've made three attempts to grab it from php: (1) php server in my ubuntu (as shown in the original question), (2) a VM (VirtualBox, using Turnkey LAMP), (3) a free hosting site. And none of them gets the data correctly, only the last element of the nested dictionary.
  • So, it's a PHP issue, not a requestsone. But I'm still clueless about what to do. Any help about what php code to use?

On the other hand:

  • Slam has also suggested to use json. This answer explains how to grab it from php: https://stackoverflow.com/a/31865422/12961782 (See "Better solution", at the bottom).
  • The json solution works OK in the three php tests I've made. (So, it's a useful workaround, but the original question is still open).
xavimat
  • 1
  • 2
  • When you visit your php file, can you view the source of the served page and look if it is displayed properly by the browser? – Bijay Regmi Mar 14 '20 at 14:33
  • When visited by a browser, the php file shows: `array(0) { } `, as it should. The entire php file is showed above in my question: ` – xavimat Mar 14 '20 at 15:29

1 Answers1

0

This is definitely on php side, in terms of parsing request.

You can double-check how your requests are formed via smth like https://requestbin.com/

requests.post(..., data={'a': 1, 'b': [2, 3]}) will be sent as body with a=1&b=2&b=3. If you want to have it json-encoded, pass data as requests.post(..., json={'a': 1, 'b': [2, 3]}), which will be sent as {"a": 1, "b": [2, 3]} respectively

Slam
  • 8,112
  • 1
  • 36
  • 44
  • I've used requestbin.com to check. Data is sent but no php test I've done gets it (only requestbin.com does). (Please, see my edit). – xavimat Mar 14 '20 at 14:18