I have to fetch exam results from the page http://cbseresults.nic.in/class1211/cbse122012.htm
Sampleroll number is 4623447.
They are using http post to post the form data.I wrote the following code to post data.But it is not providing the needed results.I am posting the needed cookies and post variables.But still I am not getting the output.What change should I make for send_post function,so that it will be working.Here is my code
echo cbse12_data_extractor(4623447);
function cbse12_data_extractor($regNo) {
$source_url = 'http://cbseresults.nic.in/class1211/cbse122012.asp';
$post_vars = array('regno'=>$regNo);
$cookies = array('_tb_pingSent'=>1);
// $extraHeaders = array('Host'=>'http://cbseresults.nic.in');
return send_post($source_url,$post_vars,$cookies);
}
function send_post( $url, $data ,$cookies='',$extraHeaders = '') //sends data array(param=>val,...) to the page $url in post method and returns the reply string
{
$post = http_build_query( $data );
$header = "Accept-language: en\r\n".
"Content-Type: application/x-www-form-urlencoded\r\n" .
"Content-Length: " . strlen( $post ) .
"\r\nUser-agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)\r\n";
if($extraHeaders) {
foreach($extraHeaders as $headerN => $val) {
$header = $header.$headerN.': '.$val."\r\n";
}
}
if($cookies) {
$cookieArr = array();
foreach($cookies as $cookie => $value) {
array_push($cookieArr,$cookie.'='.$value);
}
$cookieStr = "Cookie: ".implode('; ',$cookieArr)."\r\n";
$header = $header.$cookieStr;
}
$context = stream_context_create( array(
"http" => array(
"method" => "POST",
"header" => $header,
"content" => $post
)
) );
//echo $header;
$page = file_get_contents( $url, false, $context );
return $page;
}
You can' send POST data using file_get_contents. Use CURL for this task
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,your_parameters);
// receive server response ...
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$server_output = curl_exec ($ch);
Related
I need to send data to an API using PHP. The API has a redirect page before showing the final result. The following code shows the content of the redirecting page rather than the final result. How can I wait until the final result?
$url = 'https://example.com/api';
$data = array('text' => "try");
$options = array(
'http' => array(
'header' => "Content-type: application/x-www-form-urlencoded\r\n",
'method' => 'GET',
'content' => http_build_query($data)
)
);
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
if ($result === FALSE) { /* Handle error */ }
echo $result;
P.S. I got this code from one of stackoverflow's questions.
You could use cURL to get the final response, using CURLOPT_FOLLOWLOCATION:
From documentation :
CURLOPT_FOLLOWLOCATION: TRUE to follow any "Location: " header that the server sends as part of the HTTP header (note this is recursive, PHP will follow as many "Location: " headers that it is sent, unless CURLOPT_MAXREDIRS is set).
$url = 'https://example.com/api';
$data = array('text' => "try");
$full_url = $url . (strpos($url, '?') === FALSE ? '?' : '')
. http_build_query($data) ;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $full_url) ;
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-type: application/x-www-form-urlencoded',
]);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($ch);
curl_close ($ch);
var_dump($response) ;
I have tried calling the API using standard URL. All work perfectly directly from the browser. For e.g.:
http://www.worldcat.org/webservices/catalog/search/sru?query=srw.su%3D%22Computer organization%22&startRecord=101&maximumRecords=100&wskey=7Rn7E7osoeJeQURAiEO4GH74HZa6BLdt7eXahgxdvwnfO6Ph7za1OzU9M2zx0e9nuDHVO34b5HfnLuOw
http://www.worldcat.org/webservices/catalog/search/sru?query=srw.su%3D%22Computer engineering%22&startRecord=101&maximumRecords=100&wskey=7Rn7E7osoeJeQURAiEO4GH74HZa6BLdt7eXahgxdvwnfO6Ph7za1OzU9M2zx0e9nuDHVO34b5HfnLuOw
But when I use cURL to do it, I keep on having the error from the API that the wskey is not attached:
function curl_get_contents($url)
{
$ch = curl_init();
d($url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $url);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
d($OCLCqueries);
foreach ($OCLCqueries as $OCLCquery) {
// echo "managed1";
$XMLdata = curl_get_contents($OCLCquery);
// echo "managed2";
}
I defined $OCLCqueries earlier. It is an array that contains the URL calls as values.
d() is a function that I call from an installed library which is a more sophisticated form of var_dump(), basically having the same purpose (serve as breakpoints for debugging) but dumping the data in a more human-readable format.
This is the output I have:
<body><h1>HTTP Status 400 - org.oclc.wskey.api.WSKeyException: WsKeyParam(wskey) not found in request</h1><HR size="1" noshade="noshade"><p><b>type</b> Status report</p><p><b>message</b> <u>org.oclc.wskey.api.WSKeyException: WsKeyParam(wskey) not found in request</u></p><p><b>description</b> <u>The request sent by the client was syntactically incorrect (org.oclc.wskey.api.WSKeyException: WsKeyParam(wskey) not found in request).</u></p><HR size="1" noshade="noshade"><h3></h3></body>
How do I solve this problem?
Initially I thought the most likely reason for the failure was a lack of User-Agent string in the request but found, when testing the code below, that it's existence or not made no difference so I believe the problem is the format of the url used in the cURL request as it is already encoded. By separating the baseurl and the parameters as below it works fine.
$url='http://www.worldcat.org/webservices/catalog/search/sru';
$params=array(
'query' => 'srw.su="Computer organization"',
'startRecord' => 101,
'maximumRecords' => 100,
'wskey' => '7Rn7E7osoeJeQURAiEO4GH74HZa6BLdt7eXahgxdvwnfO6Ph7za1OzU9M2zx0e9nuDHVO34b5HfnLuOw'
);
function curl_get_contents( $url=false, $params=array() ){
if( $url && !empty( $params ) ){
$url = $url . '?' . http_build_query( $params );
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, 0 );
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt($ch, CURLOPT_URL, $url );
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:44.0) Gecko/20100101 Firefox/44.0' );
$data = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);
return (object)array(
'response' => $data,
'info' => $info
);
}
}
$data = curl_get_contents( $url, $params );
print_r( $data->response );
To simplify the call to the main function you could create a simple wrapper function like this.
function getcatalog( $baseurl=false, $term=false, $start=1, $max=1, $key=false ){
if( $baseurl && $term && $key ){
$params=array(
'query' => 'srw.su="'.$term.'"',
'startRecord' => $start,
'maximumRecords' => $max,
'wskey' => $key
);
return curl_get_contents( $baseurl, $params );
}
}
$data = getcatalog( $url, 'Computer organization', 1, 100,'7Rn7E7osoeJeQURAiEO4GH74HZa6BLdt7eXahgxdvwnfO6Ph7za1OzU9M2zx0e9nuDHVO34b5HfnLuOw');
if( $data->info['http_code']==200 ){
print_r( $data->response );
}
I know this topic has been widely discussed but in this instance I cannot get cURL to submit my simple form and I cannot see why, although I am sure it is obvious. I have tried many different cURL POST data examples found on StackOverflow but none seem to work.
My current idea is that my form action in this case is the problem because it is not, as far as I understand, the real action which posts the data. I have tried various tools to intercept the headers but all I see is the form action I currently have.
I am trying to use cURL to submit the contact form here, http://www.alpinewebdesign.co.uk/
Here is my latest attempt (in which I have included all the hidden fields and tried unsuccessfully I think to set a different header type).
//create array of data to be posted
$post_data['mact'] = 'FormBuilder,m62b34,default,1';
$post_data['m62b34returnid'] = '15';
$post_data['page'] = '15';
$post_data['m62b34fbrp_callcount'] = '1';
$post_data['m62b34form_id'] = '4';
$post_data['m62b34fbrp_continue'] = '2';
$post_data['m62b34fbrp_done'] = '1';
$post_data['name'] = 'Name';
$post_data['email'] = 'email#email.com';
$post_data['message'] = 'Message';
$post_data['m62b34fbrp_submit'] = 'Send';
//traverse array and prepare data for posting (key1=value1)
foreach ( $post_data as $key => $value) {
$post_items[] = $key . '=' . $value;
}
//create the final string to be posted using implode()
$post_string = implode ('&', $post_items);
//create cURL connection
$curl_connection =
curl_init('http://www.alpinewebdesign.co.uk');
//set options
curl_setopt($curl_connection, CURLOPT_CONNECTTIMEOUT, 30);
curl_setopt($curl_connection, CURLOPT_USERAGENT,
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)");
curl_setopt($curl_connection, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl_connection, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl_connection, CURLOPT_FOLLOWLOCATION, 1);
$headers = array();
$headers[] = 'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8';
$headers[] = 'Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryM4YWvE6kIZAIC8vY';
curl_setopt($curl_connection, CURLOPT_HTTPHEADER, $headers);
//set data to be posted
curl_setopt($curl_connection, CURLOPT_POSTFIELDS, $post_string);
//perform our request
$result = curl_exec($curl_connection);
//show information regarding the request
print_r(curl_getinfo($curl_connection));
echo curl_errno($curl_connection) . '-' .
curl_error($curl_connection);
//close the connection
curl_close($curl_connection);
Can anyone see the problem?
Thanks
Add
curl_setopt($curl_connection, CURLOPT_POST, true);
Maybe this can help you:
Firstly check if cURL library is enabled on your server:
<?=phpinfo();?>
Then try to prepare CURLOPT options as Array (also prepare the "form-data" query)
function prepareCurlOptions($url, $data, $headers)
{
$boundary = uniqid();
$post_fields = "-----" . $boundary . "\r\n";
$separate = count($data);
foreach($data as $k=>$v)
{
$post_fields .= "Content-Disposition: form-data; name=\"$k\"\r\n\r\n$v\r\n-----" . $boundary;
// add \r\n separator after each field, except last one
if( --$separate > 0 )
{
$post_fields .= "\r\n";
}
}
$post_fields .= "--";
return array(
CURLOPT_URL => $url,
CURLOPT_POSTFIELDS => $post_fields,
CURLOPT_HTTPHEADER => $headers,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_SSL_VERIFYPEER => FALSE,
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
);
}
And then set all additional options by curl_setopt_array, for example:
$url = 'http://www.alpinewebdesign.co.uk';
$post_data = array();
$post_data['name'] = 'Name';
$post_data['email'] = 'email#email.com';
$post_data['message'] = 'Message';
// ...
$headers = array();
$headers[] = 'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8';
// ...
curl_setopt_array($curl_connection , prepareCurlOptions($url, $post_data, $headers));
Renember to make sure that Boundary for headers are the same as for the $post_data fields. For example:
$headers[] = "content-type: multipart/form-data; boundary=---".$boundary"
I am working with twitter digit. my mobile verification works corrccetly. but with auth header information when I call curl then it not working.my curl code
$request=$_REQUEST['someData'];
function oauth_value($headersIndex = [])
{
if(empty($headersIndex)) return 'Invalid Index Number';
$value = explode('=', $headersIndex);
return str_replace('"', '', $value[1] );
}
$headersData = explode(',',$request['headers']);
$ch = curl_init();
$ch = curl_init($request['apiUrl']);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Authorization' => 'OAuth oauth_consumer_key="'.oauth_value($headersData[0]).'",
oauth_nonce="'.oauth_value($headersData[1]).'",
oauth_signature="'.oauth_value($headersData[2]).'",
oauth_signature_method="HMAC-SHA1",
oauth_timestamp="'.oauth_value($headersData[4]).'",
oauth_token="'.oauth_value($headersData[5]).'",
oauth_version="'.oauth_value($headersData[6]).'"'
)
);
$resp = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);
example information that come form $_REQUEST['someData'];
Array
(
[apiUrl] => https://api.digits.com/1.1/sdk/account.json
[headers] =>
OAuth oauth_consumer_key="OybCXYoYTuS0Cw0usZYry6Nlj",
oauth_nonce="3942830480-TILitVHHZGmcczuuFj3nbJtnMm00DHvvgduawMHOybCXYoYTuS0Cw0usZYry6Nlj1445246231940",
oauth_signature="dXHcH%2FsLBIlYOVWBIhEBWSCMLJo%3D",
oauth_signature_method="HMAC-SHA1",
oauth_timestamp="1445246231",
oauth_token="3942830480-TILitVHHZGmcczuuFj3nbJtnMm00DHvvgduawMH",
oauth_version="1.0"
)
What can I do Now?
If you have a URL and header from digits then you can use below code:
$apiUrl = 'https://api.digits.com/1.1/sdk/account.json';
$authHeader = 'OAuth oauth_consumer_key="**********", oauth_nonce="****", oauth_signature="****", oauth_signature_method="HMAC-SHA1", oauth_timestamp="1481554529", oauth_token="*****", oauth_version="1.0"';
// Create a stream
$opts = array(
'http'=>array(
'method'=>"GET",
'header'=>"Authorization: {$authHeader}"
)
);
$context = stream_context_create($opts);
// Open the file using the HTTP headers set above
$file = file_get_contents($apiUrl, false, $context);
$final_output = array();
if($file)
{
$final_output = json_decode($file,true);
}
print_r($final_output);
It will return id_str, phone number etc. You can store those data in your database.
I have a custom function that uses cURL to make a request and then handle the response. I use it in a loop and the function itself works fine. But, when used inside of a loop, the function that is supposed to be executed first often doesn't. Seems like the sequence in which the posts are supposed to occur are totally neglected.
function InitializeCurl($url, $post, $post_data, $token, $form, $request) {
if($post) {
if($form) {
$default = array('Content-Type: multipart/form-data;');
} else {
$default = array('Content-Type: application/x-www-form-urlencoded; charset=utf-8');
}
} else {
$default = array('Content-Type: application/json; charset=utf-8');
}
// Add the authorization in the header if needed
if($token) {
$push = 'Authorization: Bearer '.$token;
array_push($default, $push);
}
$headers = array_merge($GLOBALS['basics'], $default);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.test.com/'.$url);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_HEADER, 0);
if($request) {
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $request);
}
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
if($post) {
if($form === false) {
$post_data = http_build_query($post_data);
}
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
}
$response = curl_exec($ch);
return $response;
}
// Define the token
$token = "sample_token";
$msg = array('msg_1', 'msg_2', 'msg_3', 'msg_4', 'msg_5', 'msg_6', 'msg_7', 'msg_8', 'msg_9', 'msg_10');
for($i=0;$i<count($msg);$i++) {
$post_data = array("content_type" => "text",
"body" => $msg[$i]);
$info = InitializeCurl("send_message/", true, $post_data, $token, false, false);
$decode = #json_decode($info, true);
}
The loop should make it so that each message is posted after one another in order. But, it's totally not. Would adding CURLOPT_TIMEOUT fix this?
Seems you are missing some code, but anyway, you would probably be better off using this CURL class, or rather classes:
http://semlabs.co.uk/journal/multi-threaded-stack-class-for-php
See examples. You will be returned a result with all the URLs. You can loop through to get details of the URL etc. like this:
$urls = array(
1 => 'http://seobook.com/',
2 => 'http://semlabs.co.uk/',
64 => 'http://yahoo.com/',
3 => 'http://usereffect.com/',
4 => 'http://seobythesea.com/',
5 => 'http://darkseoprogramming.com/',
6 => 'http://visitwales.co.uk/',
77 => 'http://saints-alive.co.uk/',
7 => 'http://iluvsa.blogspot.com/',
8 => 'http://sitelogic.co.uk/',
9 => 'http://tidybag.co.uk/',
10 => 'http://felaproject.net/',
99 => 'http://billhicks.com/'
);
$opts = array(
CURLOPT_RETURNTRANSFER => true,
CURLOPT_FOLLOWLOCATION => true
);
$hs = new CURLRequest();
$res = $hs->getThreaded( $urls, $opts, 5 );
foreach( $res as $r )
{
print_r( $r['info'] ); # prints out verbose info and data of URL etc.
print_r( $r['content'] ); # prints out the HTML response
}
But the result will be returned in sequence, so you can also identify the response by index.