1

I want send post request from php to python and get answer I write this script which the send post

$url = 'http://localhost:8080/cgi-bin/file.py';
$body = 'hello world';
$options = array('method'=>'POST',
'content'=>$body,
'header'=>'Content-type:application/x-ww-form-urlencoded');
$context = stream_context_create(array('http' => $options));
print file_get_contents($url, false,$context);

I'm use custom python server

from http.server import HTTPServer, CGIHTTPRequestHandler
server_address = ("", 8080)
httpd = HTTPServer(server_address, CGIHTTPRequestHandler)
httpd.serve_forever()

And python script which the takes post request

print('Content-type: text/html\n')
import cgi
form = cgi.FieldStorage()
text2 = form.getfirst("content", "empty")
print("<p>TEXT_2: {}</p>".format(text2))

And then I get

write() argument must be str, not bytes\r\n'

How can it be solved? P.S Sorry for my bad english

Krowowd
  • 13
  • 1
  • 4
  • You probably want to use `cURL` [http://php.net/manual/en/book.curl.php], or if your code is built a bit more into classes (perhaps with a framework underneath), then I would look at the `GuzzleHttp` [http://docs.guzzlephp.org/en/latest/] library – AlphaZygma Mar 28 '17 at 22:35
  • Here is a sample on how to use cURL [https://davidwalsh.name/curl-post] – AlphaZygma Mar 28 '17 at 22:38

2 Answers2

4

Check curl extension for php http://php.net/manual/en/book.curl.php

<?php

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL,"http://localhost:8080/cgi-bin/file.py");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,
        "postvar1=value1&postvar2=value2&postvar3=value3");

// in real life you should use something like:
// curl_setopt($ch, CURLOPT_POSTFIELDS, 
//          http_build_query(array('postvar1' => 'value1')));

// receive server response ...
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$server_output = curl_exec ($ch);

curl_close ($ch);
E_p
  • 3,136
  • 16
  • 28
0

You can also use a library like guzzle that may have some other bells and whistles you may want to use.

Example usage can be found on this other answer here:

https://stackoverflow.com/a/29601842/6626810

Community
  • 1
  • 1
sebi
  • 79
  • 6