How to handle error from php handler file - php

If there is an error in the js/send_to_telegram.php file, then the error script will work. How to do it?
jQuery("form").submit(function () {
var form_data = jQuery(this).serialize();
jQuery.ajax({
type: "POST",
url: "js/send_to_telegram.php",
data: form_data,
success: function (result) {
donemodal.style.display = "block";
},
error: function (jqXHR, exception) {
errormodal.style.display = "block";
}
});
});
in js/send_to_telegram.php the following code:
$token = "5306003979:AAEPK2NhlxW";
$chat_id = "497358";
$txt = htmlspecialchars($_POST["text"]);
$sendToTelegram = fopen("https://api.telegram.org/bot{$token}/sendMessage?chat_id={$chat_id}&parse_mode=html&text={$txt}","r");
Now, even if you enter the wrong token in $sendToTelegram, it returns success. How to get error if token is wrong?

Short answer: It doesn't use API response status code unless you tell him does that. What if we sent multiple HTTP requests and got different status codes? Which of them should be used?
Solution: This is what you need:
<?php
function post($url, $fields = []) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
if (is_array($fields) && count($fields)) {
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($fields));
}
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
curl_close($ch);
return json_decode($result);
}
$response = post("https://api.telegram.org/bot{$token}/sendMessage", [
'chat_id' => $chat_id,
'text' => $txt,
]);
if ($response->ok) {
echo '{"message": "ok"}';
} else {
http_response_code(500);
echo '{"message": "Something went wrong"}';
}

Related

PHP Curl and json post error false

I'm a newbie when it comes to using PHP curl and ajax
I've been asked to do the following (an image is attached for your consideration).. there are the requirements
initially I tried sending request with jquery ajax but it was not working here is the code:
function sendAPI(){
$.ajax({
url: "https://someurl.com/api/page/index",
headers: {
'x-api-key':"[API KEY GIVEN BY THE COMPANY]",
'Content-Type':'application/json'
},
method: 'POST',
dataType: 'jsonp',
data: {
id: "7001345730",
recordNo: "1000000000",
recordDate: "2017-12-12",
phone: "+966555555555",
extension: "1234",
email: "feras#test.com",
managerName: "Amjad",
managerPhone: "+966555555555",
managerMobile: "+966555555555"
},
success: function(data){
console.log('lllk');
console.log('succes: ' + data);
},
error: function(XMLHttpRequest, textStatus, errorThrown){
console.log("textStatus: ", textStatus);
console.log("errorThrown: ", errorThrown);
}
});
}
sendAPI();
I get the following error message displayed on my console
Please note: I tried both json and jsonp dataType but same result
textStatus: error
errorThrown: error
Afterwards I tried php curl but I am getting the error on that too.
here is php curl code:
$id ="7001345730";
$recordNo = "1000000000" ;
$recordIssueDate = "2017-12-12" ;
$phone = "+966555555555" ;
$extension = "1234" ;
$email = "feras#test.com" ;
$managerName = "Adeel Essa" ;
$managerPhone = "+966555555555" ;
$managerMobile = "+966555555555";
$data = array(
"id" => $id,
"recordNo" => $recordNo,
"recordIssueDate" => $recordIssueDate,
"phone" => $phone,
"extension" => $extension,
"email" => $email,
"managerName" => $managerName,
"managerPhone" => $managerPhone,
"managerMobile" => $managerMobile,
);
$ch = curl_init('https://someurl.com/api/page/index');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
"x-api-key: 56DAAC8KAD-SFOL9267B-B97E1A9E"
]);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
$result = curl_exec($ch); //get return String
echo json_encode($result);
if (curl_error($ch)) {
$error_msg = curl_error($ch);
}
curl_close($ch);
if (isset($error_msg)) {
print_r($error_msg);
}
When I execute the above code I get the following error:
false
Failed to connect to wasl.elm.sa port 443: Timed out
In the end my only question is:
If I am doing right or there is something is missing in my code.
On both JQuery and PHP CURL codes.
If so what do I need to change.
Requirements are also mentioned in the above image
Please Help

cURL Equivalent to xhrFields: {withCredentials: true}

Goal:
Log into processor's site using their API and store the success response into COOKIEs and SESSIONs on my site.
What almost works:
jQuery(document).ready(function($){
$.ajax({
type: 'POST',
url: '{url-to-api-call}',
xhrFields: {
withCredentials: true
},
dataType: 'text',
data: 'Email={email}&GuestSessionToken={token}&Password={pass}&Format=JSON&RememberMe=true',
processData: false,
crossDomain: true,
success: function (res) { console.log('success'); },
error: function (jqXHR, textStatus, ex) {
console.log('error');
}
});
});
Why it doesn't work:
I'm unable to store the response to COOKIEs and SESSIONs.
What I would like to work:
$url = {url-to-api};
$curl = curl_init();
$curl_post_data = array(
'Email' => $fields['user_email'],
'GuestSessionToken' => $_COOKIE['SessionToken'],
'Password' => $fields['user_pass'],
'Format' => "JSON",
'RememberMe' => "true"
);
curl_setopt($curl,CURLOPT_URL,$url);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl,CURLOPT_RETURNTRANSFER,true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $curl_post_data);
curl_setopt($curl,CURLOPT_CONNECTTIMEOUT,5);
curl_setopt($curl, CURLOPT_TIMEOUT, 90);
$content = curl_exec($curl);
curl_close($curl);
$content_array = json_decode($content, true);
if ($content_array['StatusCode'] == 'OK') {
$fields['UserId'] = $content_array['Data']['UserId'];
$fields['SessionID'] = $content_array['Data']['ID'];
$fields['SessionToken'] = $content_array['Data']['Token'];
return true;
} else {
$errors->add( 'error', 'Unable to sign in.' );
return false;
}
Why it doesn't work:
This will return a success response that I can use to set the COOKIEs and SESSIONs, but it will not log the user into the processor's site.
Why I think it doesn't work:
The ajax call wouldn't sign the user in until I added the xhrFields part. I think if I could find a cURL equivalent for the xhrFields part, I would be all set.
Thanks in advance!
My duct tape fix.
<?php
// If signin form is submitted and signin cURL was successful.
echo (isset($fields['signin_script'])) ? $fields['signin_script'] : "";
function processor_signin(&$fields, &$errors) {
$url = '{url-to-api-call}';
$curl = curl_init();
$curl_post_data = array(
'Email' => $fields['user_email'],
'GuestSessionToken' => $_COOKIE['SessionToken'],
'Password' => $fields['user_pass'],
'Format' => "JSON",
'RememberMe' => "true"
);
curl_setopt($curl,CURLOPT_URL,$url);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl,CURLOPT_RETURNTRANSFER,true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $curl_post_data);
curl_setopt($curl,CURLOPT_CONNECTTIMEOUT,5);
curl_setopt($curl, CURLOPT_TIMEOUT, 90);
$content = curl_exec($curl);
curl_close($curl);
$content_array = json_decode($content, true);
if ($content_array['StatusCode'] == 'OK') {
$fields['UserId'] = $content_array['Data']['UserId'];
$fields['SessionID'] = $content_array['Data']['ID'];
$fields['SessionID'] = $content_array['Data']['ID'];
$fields['SessionToken'] = $content_array['Data']['Token'];
// Duct tape fix
$fields['signin_script'] = "
<script>
jQuery(document).ready(function($){
$.ajax({
type: 'POST',
url: '{url-to-api-call}',
xhrFields: {
withCredentials: true
},
dataType: 'text',
data: '
Email=".$fields['user_email']."
&GuestSessionToken=".$_COOKIE['SessionToken']."
&Password=".$fields['user_pass']."
&Format=JSON
&RememberMe=true',
processData: false,
crossDomain: true,
success: function (res) { console.log('signin success'); },
error: function (jqXHR, textStatus, ex) {
console.log('signin error');
}
});
});
</script>
";
return true;
} else {
$errors->add( 'error', 'Unable to sign in.' );
return false;
}
}
?>
Maybe you are logged in but you are not storing the cookies.
So you need to parse the headers and in the end store all cookies. In proceeding requests you need to send back all cookies that you retrieved before.
Here is an example how to retrieve the cookies and other headers from the server:
public function sendRequest(HttpRequest $request)
{
...
curl_setopt($ch, CURLOPT_HTTPHEADER, $request->getHeaders());
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADERFUNCTION, [$this, 'fetchHeader']);
...
$content = curl_exec($ch);
...
}
/**
* #param resource $ch - curl handle
* #param string $header
*
* #return int
*/
private function fetchHeader($ch, $header)
{
$headerParts = explode(': ', $header, 2);
if (2 === count($headerParts)) {
$headerName = strtolower($headerParts[0]);
if ('set-cookie' === $headerName) {
$this->responseHeaders[$headerName][] = trim($headerParts[1]);
return strlen($header);
}
$this->responseHeaders[$headerName] = trim($headerParts[1]);
}
return strlen($header);
}

CURL Form Response

I am having an issue with my form. The issue is that when submit is clicked the jQuery does not work within the response.length > 0 statement but however the form is working and importing data but I need it to update the div and load the thank you page instead of acting like its doing nothing :)
It should be response.length > 0 - then load the errors and update div else go to the thank you page
jQuery:
$('#mountianForm').submit(function(e) { // catch the form's submit event
$.ajax({ // create an AJAX call...
data: $(this).serialize(), // get the form data
type: $(this).attr('method'), // GET or POST
url: $(this).attr('action'), // the file to call
success: function(response) { // on success..
if (response.length > 0) {
$('#mountianFormResponse').html(response); // update the DIV
} else {
window.location.href = 'https://example.com/thank-you/';
}
}
});
e.preventDefault();
});
Process Code:
<?php
error_reporting(E_ALL); ini_set('display_errors', 1);
$url = 'https://id.infusionsoft.com/app/form/iframe/formID';
$userAgent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36';
if (!empty($_GET))
{
$url .= '?'.http_build_query($_GET);
}
$isPOST = !empty($_POST);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
curl_setopt($ch, CURLOPT_USERAGENT, $userAgent);
curl_setopt($ch, CURLOPT_POST, $isPOST);
if ($isPOST)
{
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($_POST));
}
$response = curl_exec($ch);
curl_close($ch);
if(preg_match('/(<ul>.*<\/ul>)/is', $response, $match)){
$match[1];
}else{
$error = "Error";
$file = fopen("mountianProxyerror.php", 'w+'); // Create a new file, or overwrite the existing one.
fwrite($file, $error);
fclose($file);
}
?>
I think you didn't return the response from your process code.
if(preg_match('/(<ul>.*<\/ul>)/is', $response, $match))
{
$match[1];
$resp = array('status' => TRUE,'msg' => 'success','resp' => $response);
}
else
{
$error = "Error";
$file = fopen("mountianProxyerror.php", 'w+'); // Create a new file, or overwrite the existing one.
fwrite($file, $error);
fclose($file);
$resp = array('status' => FALSE,'msg' => 'Failed');
}
echo json_encode($resp);
And in your ajax
$.ajax({ // create an AJAX call...
data: $(this).serialize(), // get the form data
type: $(this).attr('method'), // GET or POST
url: $(this).attr('action'), // the file to call
dataType : 'json',
success: function(response) { // on success..
alert(response.msg);
if (response.status == true) {
$('#mountianFormResponse').html(response.resp);
// Do whatever with the success code
}
else
{
window.location.href = 'https://example.com/thank-you/';
}
}
});

Download File Using Curl in php to a specific folder

I have a Google Drive File Url suppose for eg.
https://doc-0c-90-docs.googleusercontent.com/docs/securesc/rgh255lj001rts71cq6a0d0fmikln8fe/gg1vds4tn8h88pushsj7s1c1qvsb8nk3/1442404800000/16565899266202741945/16565899266202741945/0B86G8IQ4Uf9ATk5wRW9pdXN6OFE?e=download&gd=true
I want to download it to a specific folder for that i am using curl
function pickerCallback(data) {
if (data[google.picker.Response.ACTION] == google.picker.Action.PICKED) {
var doc = data[google.picker.Response.DOCUMENTS][0];
var fileId=doc[google.picker.Document.ID];
$.ajax({
type: "POST",
url: "files/sample.php",
data: { file_id:fileId,token:oauthToken },
success: function(data)
{
}
});
}
}
sample.php
$upload_path='folder_path';
$fileId = $_POST['file_id'];
$oAuthToken = $_POST['token'];
$getUrl = 'https://www.googleapis.com/drive/v2/files/'. $fileId .'?alt=media';
$authHeader = 'Authorization: Bearer ' . $oAuthToken ;
function get_data($url) {
$ch = curl_init();
$timeout = 5;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
$returned_content = get_data($getUrl);
file_put_contents($upload_path.'/'."55dad26bf4165.jpg", $returned_content);
this is the name of the file that i am downloading 55dad26bf4165.jpg, but it gives following error :
string(379)" { "error"; { "errors":[{
"domain":"usageLimits","reason":dailyLimitExceededUnreg",
message:Daily Limit for Unauthenticated Use Exceeded. Continue use
requires signup.".
"extendedHelp":"https://code.google.com/apisconsole" }], "code":403,
"message":"Daily Limit for Unauthenticated Use Exceeded. Continued
use requires signup."}}"
Please help why this error is occuring.

Login using Curl Php (POST method)

Hi every one,
I have a login form which has mail id and password, on submit it should call an api which inturn generates a auth token. I have used POST method in Php curl but getting the following error.
Apache Tomcat/6.0.36 - Error report
.. some html styles..
The server refused this request because the request entity is in a format not supported by the requested resource for the requested method
and this is my ajax call..
function callapi()
{
data = new Object();
var email= document.getElementById("input01").value;
var pwd=document.getElementById("input02").value;
if(email != ""&& pwd != "")
{
data.Email = email;
data.Pwd = pwd;
}
jQuery.ajax({
url: "http://localhost/stackato/nlogin.php",
type: "POST",
dataType:"json",
data:data,
error: function (data) {
alert('error--'+data);
},
success: function (data) {
if(data=="invalid")
{
}
else
{
window.location.href="finalstackatolists1.html";
}
}
});
}
and this is my curl php page
<?php
header('Content-type: application/json');
$url = $_SERVER['REQUEST_URI'];
$scriptname = $_SERVER['SCRIPT_NAME'];
$queryString = $_SERVER['QUERY_STRING'];
$mail=$_POST["Email"];
$pwd=$_POST["Pwd"];
$action = $_POST["action"];
$nurl = str_replace($scriptname,"...the api...",$url);
//open connection
$ch = curl_init();
$data = array("username" => $mail, "password" => $pwd);
$req_data = json_encode($data);
curl_setopt($ch, CURLOPT_URL, $nurl);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $req_data);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
//execute post
if( ! $result = curl_exec($ch)) {
die(curl_error($ch));
curl_close($ch);
}
if(curl_getinfo($ch, CURLINFO_HTTP_CODE) == '500')
{
header("Status: 500 Server Error");
}
curl_close($ch);
echo $result;
?>
(I tried it in REST-Client and the token has been generating)
Please help me to solve this.. thanks in advance..
You have to specify that the posted data is of type JSON
add this line to your curl code
curl_setopt($ch, CURLOPT_HTTPHEADER, Array("Content-Type: application/json"));

Categories