views:

703

answers:

2

Can anyone teach me, preferable show some sample how to do a php + curl HTTP POST?

I want to send data like, username=user1, password=passuser1, gender=1 etc to www.domain.com

And I am expecting a response, e.g "result=OK".

Thanks

+6  A: 

You'll find php/curl examples here: http://curl.haxx.se/libcurl/php/examples/, especially http://curl.haxx.se/libcurl/php/examples/simplepost.html


<?php
//
// A very simple PHP example that sends a HTTP POST to a remote site
//

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL,"http://www.mysite.com/tester.phtml");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,
            "postvar1=value1&postvar2=value2&postvar3=value3");

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

$server_output = curl_exec ($ch);

curl_close ($ch);

// further processing ....
if ($server_output == "OK") { ... } else { ... }

?>
The MYYN
+1 The option `CURLOPT_RETURNTRANSFER` will let `curl_exec()` return the response (to optional further parsing, cf. http://www.php.net/manual/en/function.curl-exec.php#function.curl-exec.returnvalues).
jensgram
thx, edited ...
The MYYN
A: 

If the form is using redirects, authentication, cookies, SSL (https), or anything else other than a totally open script expecting POST variables, you are going to start nashing your teeth really quick. Take a look at Snoopy, which does exactly what you have in mind while removing the need to set up a lot of the overhead.

Anthony