This would seem an easy task, but I can't get it to work.
I need to access some data publicly provided by the Bank of Mexico. The data is available through a form you can find at the link: http://www.banxico.org.mx/SieInternet/consultarDirectorioInternetAction.do?accion=consultarCuadro&idCuadro=CP5&locale=es
You can see an example of the data I need by clicking on the button "html" on the top left section. Once that table is opened I know how to fetch the data I need and work with them. However, I'd like to have this as an automated task so that the script can check regularly when new data is available.
So, I am trying to use file_get_contents() along with stream_context_create() to post the parameters I need and open the result page, so I can work with it.
I tried a few different ways (first I was using http_post_fields() ), but nothing seems to work.
Right now my code is this:
<?php
$url = 'http://www.banxico.org.mx/SieInternet/consultarDirectorioInternetAction.do?accion=consultarSeries';
$data = array(
'anoFinal' => 2015,
'anoInicial' => 2015,
'formatoHTML.x' => 15,
'formatoHTML.y' => 7,
'formatoHorizontal' => false,
'idCuadro' => 'CP5',
'locale' => 'es',
'sector' => 8,
'series' => 'SP1',
'tipoInformacion' => '',
'version' => 2
);
$postdata = http_build_query($data);
$opts = array('http' =>
array(
'method' => 'POST',
'header' => 'Content-type: application/x-www-form-urlencoded',
'content' => $postdata
)
);
$context = stream_context_create($opts);
$result = file_get_contents($url, false, $context);
//returns bool(false)
?>
What am I missing? I noticed that the page does in fact return nothing if wrong parameters are sent (as you can see by opening simply http://www.banxico.org.mx/SieInternet/consultarDirectorioInternetAction.do?accion=consultarSeries without any post data: nothing is returned), thus I'm not sure whether the post is successful but nothing is returned because some parameters are wrong, or if the code is wrong.
The posted data should be fine, as I copied them directly from a successfull query I made manually.
What am I missing?
It turns out cURL is a better way to do this, thanks to CBroe for the advice.
Here is the fixed code I am using, if someone else needs it:
<?php
//$url and $data are the same as above
//initialize cURL
$handle = curl_init($url);
//post values
curl_setopt($handle, CURLOPT_POST, true);
curl_setopt($handle, CURLOPT_POSTFIELDS, $data);
//set to return the response
curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);
//execute
$response = (curl_exec( $handle ));
?>
Related
I am having the following code to make a GET statement to the REST API of Parse server using PHP:
$query = json_encode(
array(
'where' => array( 'userid' => "8728792347239" )
));
echo $query;
$ch = curl_init('https://*hidden*.herokuapp.com/parse/classes/computers?'.$query);
curl_setopt(
$ch,
CURLOPT_HTTPHEADER,
array(
'X-Parse-Application-Id: *hidden*',
'X-Parse-REST-API-Key: *hidden*',
'Content-Type: application/json'
)
);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($ch);
print_r($response);
However I am getting the following error:
{"code":102,"error":"Invalid parameter for query: {\"where\":{\"userid\":\"8728792347239\"}}"}
What am I doing wrong?
without having read the documentation, i bet it's supposed to be url-encoded, not json-encoded -OR- that the data is supposed to be in the POST body, not the URL query.
if guess #1 is correct, then your problem is that you're using json_encode instead of http_build_query eg
$query = http_build_query(
array(
'where' => array( 'userid' => "8728792347239" )
));
if guess #2 is correct, then your problem is that you're adding the data to the url query instead of adding it to the request body, eg
$ch = curl_init('https://*hidden*.herokuapp.com/parse/classes/computers');
curl_setopt($ch,CURLOPT_POSTFIELDS,$query);
i have a register page for allow users to register. before register i need to validate their phone number. i have given a web-service address along with its parameters.
the parameters i have given:
http://*********
Method:POST
Headers:Content-Type:application/json
Body:
the following in:
{
"mobileNo":"0*********",
"service":"****",
"Code1":"*****",
"content":"hi",
"actionDate":"2017/09/26",
"requestId":"1"
}
and here the code i found in the Internet:
$data = array(
'mobileNo' => '****',
'service' => '***',
'Code1' => '*****',
'content' => '55',
'actionDate' => '2017/09/26');
$options = array(
'http' => array(
'method' => 'POST',
'content' => json_encode( $data ),
'header'=> "Content-Type: application/json" .
"Accept: application/json"
)
);
$url = "******";
$context = stream_context_create( $options );
$result = file_get_contents( $url, false, $context );
$response = json_decode( $result );
and here is error i face with when i test local:
file_get_contents(http://********/sms-gateway/sms-external-zone /receive): failed to open stream: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond.
and there is no error and no result(receive SMS) in response when i test online(cpanel server)
According to the given parameters, where do i wrong?
thanks in advance.
According to your Error, it seems your service did not respond. Have you tried to open it in a browser, to check if any response there?
Maybe the service you try to call requires you to provide a Static IP from your Webserver, as they only grant access on a IP based level. Means, your IP is blocked until they allow it.
I suggest you use cURL to do your request. This way you get future data to use for debugging, if anything fails. Still here, if the service does not respond, you want get any other information.
$data = array(
'mobileNo' => '****',
'service' => '***',
'Code1' => '*****',
'content' => '55',
'actionDate' => '2017/09/26');
$url = "******";
$ch = curl_init( $url );
// set data as json string
curl_setopt( $ch, CURLOPT_POSTFIELDS, json_encode($data));
// define json as content type
curl_setopt( $ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
// tell curl to fetch return data
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
// follow location if redirect happens like http to https
curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, 1);
// send request
$result = curl_exec($ch);
// gives you the result - most of the time you only want this
var_dump($result);
// for debugging purpose, gives you the whole connection info
var_dump(curl_getinfo($ch));
// gives back any occurred errors
var_dump(curl_error($ch));
curl_close($ch);
Edit: I added the CURLOPT_FOLLOWLOCATION, as a request may gets redirected. We want to catch that as well. And I added the curl_close at the end. If it is closed, error or info data can be fetched.
I'm trying to send simple push notifications with pushbullet just through using the email and sending those to the linked account to avoid needing account data. (see reference here: https://docs.pushbullet.com/#pushes)
Therefore I'm using a non cURL-method in php that I (not only) found here:
How do I send a POST request with PHP?
Unfortunately I get back an error as following:
<br />
<b>Warning</b>: file_get_contents(https://api.pushbullet.com/v2/pushes): failed to open stream: HTTP request failed! HTTP/1.0 401 Unauthorized
in <b>/path/to/function.php</b> on line <b>42</b><br />
bool(false)
Option to use urls for file_get_contents is set to "on".
My code:
$pushdata = array(
"email" => $email,
"type" => "link",
"title" => "Demo Pushbullet Notification",
"body" => "You have new comment(s)!",
"url" => "http://demo.example.com/comments"
);
//Post without cURL
$options = array(
'http' => array(
'header' => "Content-type: application/x-www-form-urlencoded\r\n"."Authorization: Bearer <xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx>\r\n",
'method' => 'POST',
'content' => http_build_query($pushdata),
),
);
$context = stream_context_create($options);
$result = file_get_contents("https://api.pushbullet.com/v2/pushes", false, $context, -1, 40000);
var_dump($result);
EDIT: Altered the code to christopherhesse's response, still doesn't work. It also shouldn't require access-tokens as I understand that pushing. I understand it as pushing notification from neutral to an linked email. Maybe I'm wrong, but the access-token doesn't fix it.
EDIT(solved): An access-token IS needed to push notifications and as it doesn't work with this method, it does work with cURL.
You need to be using cURL for this so you can pass the API key as a header defined in the documentation: https://docs.pushbullet.com/#http.
<?php
$curl = curl_init('https://api.pushbullet.com/v2/pushes');
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, ['Authorization: Bearer <your_access_token_here>']);
curl_setopt($curl, CURLOPT_POSTFIELDS, ["email" => $email, "type" => "link", "title" => "Demo Pushbullet Notification", "body" => "You have new comment(s)!", "url" => "http://demo.example.com/comments"]);
// UN-COMMENT TO BYPASS THE SSL VERIFICATION IF YOU DON'T HAVE THE CERT BUNDLE (NOT RECOMMENDED).
// curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
$response = curl_exec($curl);
print_r($response);
THIS CODE IS COMPLETELY OFF THE TOP OF MY HEAD AND HASN'T BEEN TESTED
I have broken the options up so you can see them easily but you can combine them into an array and pass them via curl_setoptarray($curl, []);
Sounds like you're missing the access token for your user account. You can find it on https://www.pushbullet.com/account . You should include it in a header like 'Authorization': 'Bearer ACCESS_TOKEN_HERE'.
I know this is an old post but I was having the same problems with sendgrid that uses the same Authorization: Bearer APIKEY method as your website.
I finally got it to work using raw php post using the following code
$url = "your url";
$post_data = 'yourdata';
// Set the headers
$options = array('http' =>
array(
'method' => 'POST',
'header' => "Authorization: Bearer APIKEY\r\n" . 'Content-Type: application/x-www-form-urlencoded',
'content' => $post_data
)
);
// Send the POST data
$ctx = stream_context_create($options);
$fp = fopen($url, 'rb', false, $ctx);
// Read the POST data
$result = json_decode(stream_get_contents($fp));
echo "done";
It seems like switching the order of the header and leaving out the \r\n at the end seemed to work. I spent like an hour on this trying different combinations so I thought I would post this for others.
Note if your using the sendgrid api make sure to set the 'Content-Type: application/json' and make sure your $post_data is in json
Posting to a file using Curl
I'm trying to post to a file as soon as user enters a website assuming they have clicked from an ad.
Example url = http://myFabSite.com/?tr=213
This is what I'm trying but its not capturing the tr URL variable or the referrer:
if($_GET['tr']){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://myFabSite.com/actions/tracksAds.php");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, true);
$data = array(
'referrer' => $_SERVER['HTTP_REFERER'],
'track_code' => $_GET['tr']
);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$output = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);
}
trackAds.php:
$mysqli = dbConnect();
$referrer = $mysqli->real_escape_string(urldecode(trim($_REQUEST['referrer'])));
$track_code = $mysqli->real_escape_string($_REQUEST['track_code']);
$query = "insert into ad_tracking ( tracking_code, referrer ) VALUES ( '$track_code', '$referrer' )";
$result = $mysqli->query($query);
Anything obvious?
UPDATE
This is from print_r($data);
Array
(
[referrer] => none
[track_code] => fb1
)
This is $query from trackAds.php
insert into ad_tracking ( tracking_code, referrer ) VALUES ( '', '' )
So, the array is not being passed, either at all or correctly, to trackAds.php
You're missing quotes in $_GET[tr] on the first line. Change it to $_GET['tr'].
Also, use $_POST instead of $_REQUEST in trackAds.php. There's a great chance here that you are inadvertently getting a cookie value instead of a POST value, or simply have the wrong data in $_REQUEST. See this page in the documentation.
Actually found a different method which works ok, still no clue why the other doesn't.
This assumes PHP 5+
$url = 'http://myFabSite.com/actions/tracksAds.php';
$data = array('referrer' => $_SERVER['HTTP_REFERER'], 'track_code' => $_GET['tr']);
// use key 'http' even if you send the request to https://...
$options = array(
'http' => array(
'header' => "Content-type: application/x-www-form-urlencoded\r\n",
'method' => 'POST',
'content' => http_build_query($data),
),
);
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
Hi I'm trying to send post values using a PHP script to an external website and get the result. My code is as follows
$postdata = http_build_query(
array(
'drpservice' => 091,
'drpdirection' => 1,
'drpbusstop' => 18051
)
);
$opts = array('http' =>
array(
'method' => 'POST',
'header' => 'Content-type: application/x-www-form-urlencoded',
'content' => $postdata
)
);
$context = stream_context_create($opts);
$result = file_get_contents($url, false, $context);
echo $result;
However, it won't return the required results unless I can manage to send in the hidden _VIEWSTATE value.
Anyone able to help?
You need to first get the form page using a GET request, and then you can parse the page to get the _VIEWSTATE value using a regular expression.
Then when doing the POST pass the value you got for it.