Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...