user61629 user61629 - 1 year ago 276
Javascript Question

How can I send POST data to a phantomjs script

I am working with PHP/CURL and would like to send POST data to my phantomjs script, by setting the postfields array below:

$ch = curl_init();
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookieFile);
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0)");
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postFieldArray);
curl_setopt($ch, CURLOPT_URL, $url);
$output = curl_exec($ch);

The problem is I don't know how to parse a POST request inside the phantomjs script. I am using the webserver module to expose the script.

I suspect may have the answer, but I don't know enough javascript to tell whether post variables are being parsed:

var service = server.listen(port, function(request, response) {

if(request.method == 'POST' &&{
var url =;

request_page(url, function(properties, imageuri){
response.statusCode = 200;

Can someone show me how to parse a POST request here?

sjy sjy
Answer Source

The object contains the body of the POST request. If your $postFieldArray is indeed an array, then (at least according to this answer) PHP should have encoded the array and POSTed it with the content type x-www-form-urlencoded. Actually, according to the PHP documentation:

Passing an array to CURLOPT_POSTFIELDS will encode the data as multipart/form-data, while passing a URL-encoded string will encode the data as application/x-www-form-urlencoded.

Although it is not explicit in the API reference, this GitHub issue suggests that PhantomJS will expose the content of an x-www-form-urlencoded form as properties on the object. That's what seems to be happening in the example ( refers to the form field url). The easiest way to check would be to log the object to the console and see what's in there.

However, the GitHub issue also implies that multipart/form-data is not supported by the PhantomJS webserver. So, unless you're prepared to change to a different web server, it might be easiest just to encode the data with JSON. On the PHP side:

curl_setopt($ch, CURLOPT_POSTFIELDS, urlencode(json_encode($postFieldArray)));

And then on the PhantomJS side:

var data = JSON.parse(;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download