I'm trying to check with Ajax a ReCaptcha V2 from Google. The problem is I keep getting error 500. This is my code.
$response = file_get_contents($url);
$responseKeys = json_decode($response, true);
$success = $responseKeys['success'];
if(!$success) return json_encode(['status' => 'CAPTCHA_ERROR']);
sendMail($request);
$url is fine I double checked and if I do this instead:
$response = file_get_contents($url);
$responseKeys = json_decode($response, true);
return $responseKeys;
And I console.log it in the browser, I get the right response:
{"success":true,"challenge_ts":"2017-10-05T03:30:18Z","hostname":"mysite.com"}
Related
I started my PHP script using file_get_contents(), I'm using an online data base and I can get JSON from it using URL, but sometimes (and I can't help it) I get back some 40* or 50* errors responses code, and I wondered if you guys could tell me what's better to use between cURL and file_get_contents, because basically everytime I'll have to check response code and switch case on it to determine what I do next.
200 => get file
403 => print "error"
502 => print 'bad gateway'
...
Hope I was clear, thanks in advance!
How to get the status of an HTTP response?
Using cURL
The function curl_getinfo() get information regarding a specific transfer. The second parameter of this function allows to get a specific information. The constant CURLINFO_HTTP_CODE can be used to get the HTTP status code of the HTTP response.curl_getinfo() should be called after curl_exec() and is relevant if curl_exec()' return is not false. If the response is false, don't forget to use curl_error() in this case to get a readable string of the error.
$url = 'https://stackoverflow.com';
$curlHandle = curl_init($url);
curl_setopt($curlHandle, CURLOPT_RETURNTRANSFER, true); // required to get the HTTP header
$response = curl_exec($curlHandle);
$httpCode = $response !== false ? curl_getinfo($curlHandle, CURLINFO_HTTP_CODE) : 0;
curl_close($curlHandle);
var_dump($httpCode); // int(200)
Using streams
The function stream_get_meta_data() retrieves header/meta data from streams/file pointers
$url = 'https://stackoverflow.com';
$httpCode = 0;
if ($fp = fopen($url, 'r')) {
$data = stream_get_meta_data($fp);
[$proto, $httpCode, $msg] = explode(' ', $data['wrapper_data'][0] ?? '- 0 -');
}
fclose($fp);
var_dump($httpCode); // int(200)
I'm trying to set up a fb messenger chatbot but don't seem to be able to get the webhook callback url verified. Every time I try to verify it I get this error message - The URL couldn't be validated. Response does not match challenge, expected value = '1596214014', received=''
Here's the screenshot:
Screenshot
Here's the php I'm using -
<?php
$challenge = $_REQUEST['hub_challenge'];
$verify_token = $_REQUEST['hub_verify_token'];
if ($verify_token === 'token_my_token') {
echo $challenge;
}
I've also tried
echo $_GET['hub_challenge'];
and just
echo file_get_contents('php://input');
All of these result in the same error message as above. Basically, as far as I can tell facebook isn't sending a GET request to my server or if it is it doesn't include any data. Can anyone tell if I am doing something wrong or if there is a setting I need to change to ensure facebook is sending the data correctly?
Edit - When checking the access logs this is what I find, which looks like facebook isn't sending any data in the get request.
2a03:2880:1010:dffb:face:b00c:0:8000 - - [19/Apr/2016:20:50:06 +0000] "GET /wp-content/plugins/applications/fbmessenger.php HTTP/1.0" 200 - "-" "facebookplatform/1.0 (+http://developers.facebook.com)
Thanks
just try my code and it's gonna work.
$challenge = $_REQUEST['hub_challenge'];
$verify_token = $_REQUEST['hub_verify_token'];
if ($verify_token === 'Your's app token') {
echo $challenge;
}
//Token of app
$row = "Token";
$input = json_decode(file_get_contents('php://input'), true);
//Receive user
$sender = $input['entry'][0]['messaging'][0]['sender']['id'];
//User's message
$message = $input['entry'][0]['messaging'][0]['message']['text'];
//Where the bot will send message
$url = 'https://graph.facebook.com/v2.6/me/messages?access_token='.$row;
$ch = curl_init($url);
//Answer to the message adds 1
if($message)
{
$jsonData = '{
"recipient":{
"id":"'.$sender.'"
},
"message":{
"text":"'.$message. ' 1' .'"
}
}';
};
$json_enc = $jsonData;
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $json_enc);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
if(!empty($input['entry'][0]['messaging'][0]['message'])){
$result = curl_exec($ch);
}
you have to return Challenges so Facebook can verify its correct Url and Token Match
<?php
$challenge = $_REQUEST['hub_challenge'];
$verify_token = $_REQUEST['hub_verify_token'];
if ($verify_token === 'token_my_token') {
echo $challenge;
}
Facebook Docs Link ( In Node.js ) You can see challenge return after verifying the token
https://developers.facebook.com/docs/messenger-platform/getting-started/webhook-setup
Could you try my API? https://github.com/Fritak/messenger-platform
If you set it like in example, it should work:
// This is just an example, this method of getting request is not safe!
$stream = file_get_contents("php://input");
$request = empty($stream)? $_REQUEST : $stream;
$bot = new \fritak\MessengerPlatform(
['accessToken' => 'token_for_app',
'webhookToken' => 'my_secret_token',
'facebookApiUrl' => 'https://graph.facebook.com/v2.6/me/' //2.6 is minimum
], $request);
if($bot->checkSubscribe())
{
print $bot->request->getChallenge();
exit;
}
If not, problem is somewhere between Facebook and script, not in PHP itself. Go check apache settings etc.
Well issue might be on facebook side, they had some issues over past few days...
Have only this code in your php file: (fbmessenger.php)
<?php
// header('HTTP/1.1 200 OK');
/* GET ALL VARIABLES GET & POST */
foreach ($_REQUEST AS $key => $value){
$message .= "$key => $value ($_SERVER[REQUEST_METHOD])\n";
}
$input = file_get_contents("php://input");
$array = print_r(json_decode($input, true), true);
file_put_contents('fbmessenger.txt', $message.$array."\nREQUEST_METHOD: $_SERVER[REQUEST_METHOD]\n----- Request Date: ".date("d.m.Y H:i:s")." IP: $_SERVER[REMOTE_ADDR] -----\n\n", FILE_APPEND);
echo $_REQUEST['hub_challenge'];
You will have requests saved in a file called "fbmessenger.txt" in the same directory.
Note that for some strange reason you may need to submit few times to
get it approved & saved! (I had to hit "save" 8-9 times before fb
approved link)
Make sure you use https (SSL) connection and once your connection is done, verify your token with "hub_verify_token" to make sure request is coming from fb.
I'm trying to set up a telegram bot with a webhook. I can get it to work with getUpdates, but I want it to work with a webhook.
My site (that hosts the bot php script) has the SSL certificate working (I get the green lock in the address bar):
I set up the webhook with
https://api.telegram.org/bot<token>/setwebhook?url=https://www.example.com/bot/bot.php
And I got: {"ok":true,"result":true,"description":"Webhook was set"}
(I don't know if this matters, but I have given rwx rights to both the folder and the script)
The php bot: (https://www.example.com/bot/bot.php)
<?php
$botToken = <token>;
$website = "https://api.telegram.org/bot".$botToken;
#$update = url_get_contents('php://input');
$update = file_get_contents('php://input');
$update = json_decode($update, TRUE);
$chatId = $update["message"]["chat"]["id"];
$message = $update["message"]["text"];
switch($message) {
case "/test":
sendMessage($chatId, "test");
break;
case "/hi":
sendMessage($chatId, "hi there!");
break;
default:
sendMessage($chatId, "default");
}
function sendMessage ($chatId, $message) {
$url = $GLOBALS[website]."/sendMessage?chat_id=".$chatId."&text=".urlencode($message);
url_get_contents($url);
}
function url_get_contents($Url) {
if(!function_exists('curl_init')) {
die('CURL is not installed!');
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $Url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$output = curl_exec($ch);
curl_close($ch);
return $output;
}
?>
But when I write anything to the bot I receive no answers...
Any ideas why?
Thanks
In your question it's not clear the script location. Seeing your code, it seems that you try to load a request through url_get_contents to retrieve telegram server response. This is the correct method if your bot works without webhook. Otherwise, after setting webhook, you have to process incoming requests.
I.e., if you set webhook to https://example.com/mywebhook.php, in your https://example.com/mywebhook.php script you have to write something like this:
<?php
$request = file_get_contents( 'php://input' );
# ↑↑↑↑
$request = json_decode( $request, TRUE );
if( !$request )
{
// Some Error output (request is not valid JSON)
}
elseif( !isset($request['update_id']) || !isset($request['message']) )
{
// Some Error output (request has not message)
}
else
{
$chatId = $request['message']['chat']['id'];
$message = $request['message']['text'];
switch( $message )
{
// Process your message here
}
}
Here I found readability which parse the data from web page and give information of interest.
But I could not understand how to use it.
https://www.readability.com/developers/api/parser
Request: GET /api/content/v1/parser?url=http://blog.readability.com/2011/02/step-up-be-heard-readability-ideas/&token=1b830931777ac7c2ac954e9f0d67df437175e66e
It gives json response.
I am working on PHP, how to make above request for particular url like http://google.com?
UPDATE1:
<?php
define('TOKEN', "1b830931777ac7c2ac954e9f0d67df437175e66e");
define('API_URL', "https://www.readability.com/api/content/v1/parser?url=%s&token=%s");
function get_image($url) {
// sanitize it so we don't break our api url
$encodedUrl = urlencode($url);
//$TOKEN = '1b830931777ac7c2ac954e9f0d67df437175e66e';
//Also tried with $API_URL = 'http://blog.readability.com/2011/02/step-up-be-heard-readability-ideas'; with no luck
// build our url
$url = sprintf(API_URL, $encodedUrl, TOKEN); //Also tried with $TOKEN
// call the api
$response = file_get_contents($url);
if( $response ) {
return false;
}
$json = json_decode($response);
if(!isset($json['lead_image_url'])) {
return false;
}
return $json['lead_image_url'];
}
echo get_image('http://nextbigwhat.com/');
?>
Any issue with code? gives error - >
Warning: file_get_contents(https://www.readability.com/api/content/v1/parser?url=http%3A%2F%2Fnextbigwhat.com&token=1b830931777ac7c2ac954e9f0d67df437175e66e): failed to open stream: HTTP request failed! HTTP/1.1 403 FORBIDDEN in F:\wamp\www\inviteold\test2.php on line 14
Perhaps something like this:
define('TOKEN', "your_token_here");
define('API_URL', "https://www.readability.com/api/content/v1/parser?url=%s&token=%s");
function get_image($url) {
// sanitize it so we don't break our api url
$encodedUrl = urlencode($url);
// build our url
$url = sprintf(API_URL, $encodedUrl, $token);
// call the api
$response = file_get_contents($url);
if( $response ) {
return false;
}
$json = json_decode($response);
if(!isset($json['lead_image_url'])) {
return false;
}
return $json['lead_image_url'];
}
The code is not tested so you might need to adjust it.
For some reason my CURL isnt working now, all i did was change the url (as before i was using this to call info from the need for speed world servers) and it worked flawlessly, now I am trying to use it with IMDBAPI and it gives me an error.
url i type in:
http://localhost/movie.php?title=The Green Mile
Code:
<?php
$title = $_GET['title'];
//optional comment out or delete
error_reporting(E_ALL);
// The POST URL and parameters
$request = 'http://www.imdbapi.com/?t='.$title.'&r=XML';
// Get the curl session object
$session = curl_init($request);
// Set the POST options.
curl_setopt($session, CURLOPT_HEADER, true);
curl_setopt($session, CURLOPT_RETURNTRANSFER, true);
// Do the POST and then close the session
$response = curl_exec($session);
curl_close($session);
// Get HTTP Status code from the response
$status_code = array();
preg_match('/\d\d\d/', $response, $status_code);
// Check for errors
switch( $status_code[0] ) {
case 200:
// Success
break;
case 503:
die('Service unavailable. An internal problem prevented us from returning data to you.');
break;
case 403:
die('Forbidden. You do not have permission to access this resource, or are over your rate limit.');
break;
case 400:
// You may want to fall through here and read the specific XML error
die('Bad request. The parameters passed to the service did not match as expected. The exact error is returned in the XML response.');
break;
default:
die('Your call returned an unexpected HTTP status of:' . $status_code[0]);
}
// Get the XML from the response, bypassing the header
if (!($xml = strstr($response, '<?xml'))) {
$xml = null;
}
// Output the XML
$movieInfo = simplexml_load_string($xml);
$movieTitle = $movieInfo->movie['title'];
echo "Title: $movieTitle <br />";
?>
Error:
Bad request. The parameters passed to the service did not match as expected. The exact error is returned in the XML response.
I am a noob to CURL so any help is appreciated.
You should urlencode() the $title.
http://www.imdbapi.com/?t=The%20Green%20Mile&r=XML
This one works fine for me. Try to rawurlencode that title
$title = rawurlencode($title);
As Shi said,you need encode the values:
$title = rawurlencode($_GET["title"]);
You can get the http code of your request with:
$status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);