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
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);
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
Related
I am trying to create a form for the user to buy product from my Ruby on Rails website by using their "Scratch Card for Mobile Phones".
The problem is that the service only provides Module code for PHP. So I have to convert it to Ruby to put into my website. Here are the codes I want to convert to Ruby:
$post_field = 'xyz=123&abc=456';
$api_url = "https://www.nganluong.vn/mobile_card.api.post.v2.php";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$api_url);
curl_setopt($ch, CURLOPT_ENCODING , 'UTF-8');
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_field);
$result = curl_exec($ch);
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$error = curl_error($ch);
I have tried to convert them to Ruby code but always got confused. Can anyone help me convert these codes into working Ruby codes? Thanks in advance!
Here is my silly code so far:
RestClient.post($api_url, $post_field, "Content-Type" => "application/x-www-form-urlencoded")
Basically all that I need is a ruby version of the php curl code. I'm a newbie, not an experienced programmer, so please help.
Try something like this:
require 'rest-client'
require 'rack'
post_query = 'xyz=123&abc=456'
api_url = "https://www.nganluong.vn/mobile_card.api.post.v2.php"
query_hash = Rack::Utils.parse_nested_query(post_query)
begin
response = RestClient.post api_url, :params => query_hash
print response.code
print response.body
rescue Exception => e
print e.message
end
All the code is doing is sending a payload xyz=123&abc=456 through a POST request to a specified URL.
You might use e.g. the curb gem for this:
response = Curl.post("https://www.nganluong.vn/mobile_card.api.post.v2.php", {:xyz => 123, :abc => 456})
result = response.body_str
status = response.status
I have a Flask app, with a basic function, where I have exposed app.run() to a public ip, so that it is accessible from an external server;[ using Flask - Externally Visible Dev Server ]
#app.route('/')
def hello_world():
return 'Hello World!'
if __name__ == '__main__':
app.run(host = '0.0.0.0', port = 8080)
The curl request I have written in my php code is:
$signed_url = "http://my-ip-address:8080/";
$ch = curl_init($signed_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, 0);
$data= curl_exec($ch);
echo $data;
I can do a curl request :
curl http://my-ip-address:8080/
from command line. However, when the curl request is embedded within my PHP code, it gives me an error "Connection refused".
Kindly help!
If the PHP code is on another server, but your command line cURL request is on the same server, then you aren't comparing apples to apples.
Two things that might be wrong:
Your Flask server has a firewall that doesn't allow external connections.
You are connecting using an private network IP address rather than a public IP address.
For now your PHP code looks correct, so I would narrow down the problem a little bit. Ignore that PHP code and try to connect using cURL on the command line from the same server you are running your PHP code on.
try to set your port with curl options like this:
curl_setopt($ch, CURLOPT_PORT, 8080);
so your signed url will be:
$signed_url = "http://my-ip-address";
I use this code for my work and worked :)
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://localhost:5000/spmi/api/1');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "{\"teks_analysis\":\"tidak ada skor nol\"}");
curl_setopt($ch, CURLOPT_POST, 1);
$headers = array();
$headers[] = 'Content-Type: application/json';
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);
if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
}
curl_close($ch);
the key is CURLOPT_POSTFIELDS
For testing where should i give the url of the site, can you show me with the example in the above code?
$r = new HTTPRequest("server.php", HTTP_METH_POST);
$r->addPostFields(array('omg' => 'wtf'));
$r->send();
var_dump($r->getResponseCode());
var_dump($r->getResponseBody());
Simply use addHeaders().
The XMLHttpRequest is the value of the X-Requested-With header, so you just have to do:
$r = new HTTPRequest("http://mywebservices.com/somewebserver.php", HTTP_METH_POST);
$r->addHeaders(array('X-Requested-With' => 'XMLHttpRequest'));
Instructions for installing HTTP from PECL: http://www.php.net/manual/en/http.setup.php
phpdev has answered your question very well, and if you install the HTTP extension and do it as according to the answer it will surely work.
$r = new HttpRequest('http://your-required-url-here', HttpRequest::METH_POST);
$r->addPostFields(array('omg' => 'wtf'));
echo $r->send()->getBody();
The urls given by you in the previous comments are not well formed, it seems that you have pasted some random URL.
This is just another way to do it with php CURL.
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://www.openfirms.com/index.php");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, true);
$data = array('omg' => 'wtf');
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$output = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);
print_R($output);
This will output the contents of specified url. Hope it will help
I need to put a string of data like so: '< client>...<\client>' onto an XMl server (example url:'http://example.appspot.com/examples') using PHP.
(Context: Adding a new client's details to the server).
I have tried using CURLOPT_PUT, with a file and with just a string (since it requires CURLOPT_INFILESIZE and CURLOPT_INFILE) but it does not work!
Are there any other PHP functions that could be used to do such a thing? I have been looking around but PUT requests information is sparse.
Thanks.
// Start curl
$ch = curl_init();
// URL for curl
$url = "http://example.appspot.com/examples";
// Put string into a temporary file
$putString = '<client>the RAW data string I want to send</client>';
/** use a max of 256KB of RAM before going to disk */
$putData = fopen('php://temp/maxmemory:256000', 'w');
if (!$putData) {
die('could not open temp memory data');
}
fwrite($putData, $putString);
fseek($putData, 0);
// Headers
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
// Binary transfer i.e. --data-BINARY
curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, $url);
// Using a PUT method i.e. -XPUT
curl_setopt($ch, CURLOPT_PUT, true);
// Instead of POST fields use these settings
curl_setopt($ch, CURLOPT_INFILE, $putData);
curl_setopt($ch, CURLOPT_INFILESIZE, strlen($putString));
$output = curl_exec($ch);
echo $output;
// Close the file
fclose($putData);
// Stop curl
curl_close($ch);
since I haven't worked with cURL so far I can't really answer to that topic. If you'd like to use cURL I'd suggest looking at the server log and see what actually didn't work (so: Was the output of the request really what it's supposed to be?)
If you don't mind switching over to another technology/library I'd suggest you to use the Zend HTTP Client which is really straight forward to use, simple to include and should satisfy all your needs. Especially as performing a PUT Request is as simple as that:
<?php
// of course, perform require('Zend/...') and
// $client = new Zend_HTTP_Client() stuff before
// ...
[...]
$xml = '<yourxmlstuffhere>.....</...>';
$client->setRawData($xml)->setEncType('text/xml')->request('PUT');
?>
Code sample is from: Zend Framework Docs # RAW-Data Requests
Another way to add string body to the PUT request with CURL in PHP is:
<?php
$data = 'My string';
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT'); // Define method type
curl_setopt($ch, CURLOPT_POSTFIELDS, $data); // Set data to the body request
?>
I hope this helps!
I'm trying to create a script that will delete all user properties for a particular individual. I'm able to use an api call to get the users' properties. And I'm trying use a delete api to remove each property. But I'm having an issue doing so. Below is the code:
$delete = "http://www.ourwiki.com/#api/DELETE:users/$user_id/properties/%s";
$xml = new SimpleXMLElement($xmlString);
foreach($xml->property as $property) {
$name = $property['name']; // the name is stored in the attribute
file_get_contents(sprintf($delete, $name));
}
I believe I need to use curl to perform the actual delete. Here is an example of that command (property=something):
curl -u username:password -X DELETE -i http://ourwiki.com/#api/users/=john_smith#ourwiki.com/properties/something
-u Provides external user authentication.
-X Specifies the HTTP request method.
-i Outputs the HTTP response headers. Useful for debugging.
Is this something that I can incorporate right into the existing script? Or is there something else I need to do? Any help would be greatly appreciated.
update:
<?php
$user_id="john_smith#ourwiki.com";
$url=('http://aaron:12345#192.168.245.133/#api/deki/users/=john_smith#ourwiki.com/properties');
$xmlString=file_get_contents($url);
$delete = "http://aaron:12345#192.168.245.133/#api/deki/DELETE:users/$user_id/properties/%s";
$xml = new SimpleXMLElement($xmlString);
function curl_fetch($url,$username,$password,$method='DELETE')
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); // returns output as a string instead of echoing it
curl_setopt($ch,CURLOPT_USERPWD,"$username:$password"); // if your server requires basic auth do this
return curl_exec($ch);
}
foreach($xml->property as $property) {
$name = $property['name']; // the name is stored in the attribute
curl_fetch(sprintf($delete, $name),'aaron','12345');
}
?>
You can use php curl, or shell out to curl using exec.
If curl is already enabled on you web server, go with php curl. If you cant install php-curl copy a command line version of curl and you are good to go.
In php-curl to set the delete method do:
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'DELETE');
edit
Something like this:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://www.ourwiki.com/#api/whatever/url/you/want/or/need");
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'DELETE');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); // returns output as a string instead of echoing it
curl_setopt($ch,CURLOPT_USERPWD,"$username:$password"); // if your server requires basic auth do this
$output = curl_exec($ch);
edit2
stick that above code in a function:
function curl_fetch($url,$username,$password,$method='DELETE')
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); // returns output as a string instead of echoing it
curl_setopt($ch,CURLOPT_USERPWD,"$username:$password"); // if your server requires basic auth do this
return curl_exec($ch);
}
and replace the call to file_get_contents() in your script with the new function.
curl_fetch(sprintf($delete, $name),'aaron','12345');
Done.
looks like you are looking for the curl function calls in php, including curl_setopt
See: http://php.net/curl