Curl response in php - php

Am using Curl to send sms using a gateway , a, getting 200 when everything is ok and 400 if its not send now , i should get other things from the gateway such as phone number and other information , so am i missing something ?
// if the Form is submited
//if (isset($_POST['PhoneNumber'])) {
if ($_SERVER['REQUEST_METHOD'] == "POST"){
// Fetch Phone Number and escape it for security
$Phone = mysql_real_escape_string($_POST['PhoneNumber']);
// Fetch Text and escape it for security
$Text = mysql_real_escape_string($_POST['Text']);
// Structure the URl
$url = "http://xxxxxxxxxxx:xxxx?PhoneNumber=".urlencode($Phone)."&Text=".urlencode($Text)."&User=xxx&Password=xxx";
// Handeling the Curl
$handle = curl_init($url);
curl_setopt($handle, CURLOPT_RETURNTRANSFER, TRUE);
/* Get the HTML or whatever is linked in $url. */
$response = curl_exec($handle);
/* Check for 404 (file not found). */
$httpCode = curl_getinfo($handle, CURLINFO_HTTP_CODE);
if ($httpCode=="200"){
// if everything is okey , the gateway returns 200 which means OK
echo "Massage Was Sent , Thank you ";
} elseif ($httpCode=="400"){
// if there was an error , the form returns a 400 which means that the sms Failed
echo "Massage was not sent , Please Try Again";
}
// Cloase the Curl Connection
curl_close($handle);
Thank you Best regards,

$response should contain the response, try:
echo '<pre>';
print_r($response);
echo '</pre>';
to show its content

Related

Facebook Messenger API - Can't verify webhook URL (PHP)

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.

How detect if external website working or not?

How can I detect if external website working or not? I have thinked about HTTP ERROR MESSAGE. In general something as:
if ( <<something(url)>> != 200 ) {
// website defined in url working (up)
} else {
// website defined in url not working (down)
}
200 is code that define a success querying url. Just so understood reading here: http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
Try using CURL. The example is adapted from cur_getinfo()
// Create a curl handle
$ch = curl_init('http://stackoverflow.com/');
//Return only headers
curl_setopt($ch, CURLOPT_NOBODY, true);
// Execute
curl_exec($ch);
// Check if any error occurred
if(!curl_errno($ch))
$info = curl_getinfo($ch);
// Close handle
curl_close($ch);
if ( isset($info) && $info['http_code'] == 200 )
echo "Website is up!";
else
echo "Website is down.";

Using cURL, explode and foreach to check for 403 response code

Okay so I'm making a script to check if given website(s) return a 403 or not. I joined some bits and pieces to get this working and it does work if I just check a single website at a time but it doesn't not work with multiple websites.
$url = $_POST['site'];
$many_urls = explode(",", $url);
$handle = curl_init($url);
curl_setopt($handle, CURLOPT_RETURNTRANSFER, TRUE);
/* Get the HTML or whatever is linked in $url. */
$response = curl_exec($handle);
/* Check for 403 (forbidden). */
$httpCode = curl_getinfo($handle, CURLINFO_HTTP_CODE);
foreach ($many_urls as $urls)
{
if($httpCode == 403) {
echo "<h2>$url is <font color='red'>Forbidden.</font><h2>";
} else echo "<h2>$url <font color='green'>Works.</font><h2>";
}
curl_close($handle);
So if I type in for example: google.com,youtube.com,forbiddenwebsite.com
It should return:
google.com Works youtube.com Works forbiddenwebsite.com is Forbidden (on different lines ofcourse)
I'm pretty sure there's a problem with foreach part.
Any help would be appreciated. Thanks.
if you're going to be checking each url independently when in list form, you'll need to have that curl in the loop. otherwise you're checking the headers for "google.com,youtube.com,forbiddenwebsite.com", which isn't a valid address. try this:
/* exploding the url list will give an array with 1 item in the case of only 1 url */
$urls = explode(',', $_POST['site']);
/* wrap the whole thing in the loop, check each url individually */
foreach($urls as $url){
$handle = curl_init($url);
curl_setopt($handle, CURLOPT_RETURNTRANSFER, TRUE);
/* Get the HTML or whatever is linked in $url. */
$response = curl_exec($handle);
/* Check for 403 (forbidden). */
$httpCode = curl_getinfo($handle, CURLINFO_HTTP_CODE);
if($httpCode == 403) {
echo "<h2>$url is <font color='red'>Forbidden.</font><h2>";
} else echo "<h2>$url <font color='green'>Works.</font><h2>";
curl_close($handle);
}
You'll probably want to add some sort of check for the case of an empty string passed in the post vars too.

PHP - How to check if Curl actually post/send request?

I basically created a script using Curl and PHP that sends data to the website e.g. host, port and time. Then it submits the data. How would I know if the Curl/PHP actually sent those data to the web pages?
$fullcurl = "?host=".$host."&time=".$time.";
Any ways to see if they actually sent the data to those URLs on My MYSQL?
You can use curl_getinfo() to get the status code of the response like so:
// set up curl to point to your requested URL
$ch = curl_init($fullcurl);
// tell curl to return the result content instead of outputting it
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
// execute the request, I'm assuming you don't care about the result content
curl_exec($ch);
if (curl_errno($ch)) {
// this would be your first hint that something went wrong
die('Couldn\'t send request: ' . curl_error($ch));
} else {
// check the HTTP status code of the request
$resultStatus = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($resultStatus == 200) {
// everything went better than expected
} else {
// the request did not complete as expected. common errors are 4xx
// (not found, bad request, etc.) and 5xx (usually concerning
// errors/exceptions in the remote script execution)
die('Request failed: HTTP status code: ' . $resultStatus);
}
}
curl_close($ch);
For reference: http://en.wikipedia.org/wiki/List_of_HTTP_status_codes
Or, if you are making requests to some sort of API that returns information on the result of the request, you would need to actually get that result and parse it. This is very specific to the API, but here's an example:
// set up curl to point to your requested URL
$ch = curl_init($fullcurl);
// tell curl to return the result content instead of outputting it
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
// execute the request, but this time we care about the result
$result = curl_exec($ch);
if (curl_errno($ch)) {
// this would be your first hint that something went wrong
die('Couldn\'t send request: ' . curl_error($ch));
} else {
// check the HTTP status code of the request
$resultStatus = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($resultStatus != 200) {
die('Request failed: HTTP status code: ' . $resultStatus);
}
}
curl_close($ch);
// let's pretend this is the behaviour of the target server
if ($result == 'ok') {
// everything went better than expected
} else {
die('Request failed: Error: ' . $result);
}
in order to be sure that curl sends something, you will need a packet sniffer.
You can try wireshark for example.
I hope this will help you,
Jerome Wagner

Checking redirect in PHP before actioning

Is there a way to check if the server responds with an error code before sending a user there?
Currently, I am redirecting based on user editable input from the backend (client request, so they can print their own domain, but send people elsewhere), but I want to check if the URL will actually respond, and if not send them to our home page with a little message.
You can do this with CURL:
$ch = curl_init('http://www.example.com/');
//make a HEAD request - we don't need the response body
curl_setopt($ch, CURLOPT_NOBODY, true);
// Execute
curl_exec($ch);
// Check if any error occured
if(!curl_errno($ch))
{
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); //integer status code
}
// Close handle
curl_close($ch);
You can then check if $httpCode is OK. Generally a 2XX response code is ok.
You could try the following, but beware that this is a seperate request to the redirect, so if something goes wrong in between then a user can still get sent to an erroneous location.
$headers = get_headers($url);
if(strpos($headers[0], 200) !== FALSE) {
// redirect to $url
} else {
// redirect to homepage with error notice
}
The PHP manual for get_headers(): http://www.php.net/manual/en/function.get-headers.php
I don't understand what you mean by making sure the URL will respond. But if you want to display a message you can use a $_SESSION variable. Just remember to put session_start() on every page that will use the variable.
So when you want to redirect them back to the home page. You could do this.
// David Caunt's answer
$ch = curl_init('http://www.example.com/');
// Execute
curl_exec($ch);
// Check if any error occured
if(!curl_errno($ch))
{
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); //integer status code
// My addition
if( $httpCode >= 200 && $httpCode < 300 ) {
// All is good
}else {
// This doesn't exist
// Set the error message
$_SESSION['error_message'] = "This domain doesn't exist";
// Send the user back to the home page
header('Location: /home.php'); // url based: http://your-site.com/home.php
}
// My addition ends here
}
// Close handle
curl_close($ch);
Then on your home page, you'll something like this.
// Make sure the error_message is set
if( isset($_SESSION['error_message']) ) {
// Put the error on the page
echo '<div class="notification warning">' . $_SESSION['error_message'] . '</div>';
}

Categories