Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
150 views
in Technique[技术] by (71.8m points)

php - Making POST request using Curl, not working

I want to make a POST request to get schedule of a train number from this page: http://www.indianrail.gov.in/train_Schedule.html

I'm using this code but it is NOT working. The resulting error shown in attachment below. What could be the problem?
PS: I've got the cgi path and arguments as in $data using Firebug

$data = array('lccp_trnname' => '14553', 'getIt' => 'Get Schedule');

    $ch = curl_init();
    $useragent= "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:9.0.1) Gecko/20100101 Firefox/9.0.1";
    curl_setopt($ch, CURLOPT_USERAGENT, $useragent); // set user agent
    curl_setopt($ch, CURLOPT_URL, 'http://www.indianrail.gov.in/cgi_bin/inet_trnnum_cgi.cgi');
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);

    $txResult = curl_exec($ch);

    print "$txResult
";

enter image description here:

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Assuming you have permission to programatically consume the data on that site......

The problem is the way you pass the post data to cURL.

CURLOPT_POSTFIELDS

The full data to post in a HTTP "POST" operation. To post a file, prepend a filename with @ and use the full path. The filetype can be explicitly specified by following the filename with the type in the format ';type=mimetype'. This parameter can either be passed as a urlencoded string like 'para1=val1&para2=val2&...' or as an array with the field name as key and field data as value. If value is an array, the Content-Type header will be set to multipart/form-data. As of PHP 5.2.0, files thats passed to this option with the @ prefix must be in array form to work.

http://php.net/manual/en/function.curl-setopt.php

Try encoding the post data yourself and passing it as a string:

$data = array('lccp_trnname' => '14553', 'getIt' => 'Get Schedule');

$fields_string = '';
foreach($data as $key=>$value) { $fields_string .= urlencode($key).'='.urlencode($value).'&'; }
rtrim($fields_string,'&');

Then set the option:

curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...