PHP Curl wont send POST request - php

i have a html page that submits 2 forms(formone & formtwo) via ajax on one button click.
formone is submitted to formone.php and if it was succesfully sent formtwo is submitted to formtwo.php.
Everything works fine. Except i need to send data via POST to another php script (on another server, but for now i'm testing it on the same server).
I tried it with the following code but it wont work (i don't get any errors though).
Curl code i used!
function transferData()
{
//Set up some vars
$url = 'test.php';
$user = 'sampletext';
$pw = 'sampletext';
$fields = array(
'user'=>urlencode($user),
'pw'=>urlencode($pw)
);
// Init. string
$fields_string = '';
// URL-ify stuff
foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
rtrim($fields_string,'&');
//open connection
$ch = curl_init();
//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_POST,count($fields));
curl_setopt($ch,CURLOPT_POSTFIELDS,$fields_string);
//execute post
$result = curl_exec($ch);
//close connection
curl_close($ch);
}
This is the code for my ajax form submission:
function submitforms()
{
FormSubmissionOne();
function FormSubmissionOne()
{
//Form 1
var $form = $('#formone');
$.ajax(
{
type: 'POST',
url: $form.attr('action'),
data: $form.serialize(),
success: function (msg)
{
FormSubmissionTwo();
},
error: function(msg)
{
alert(msg);
}
});
}
function FormSubmissionTwo()
{
//Form 2
var $form2 = $('#formtwo');
$.ajax(
{
type: 'POST',
url: $form2.attr('action'),
data: $form2.serialize(),
success: function (msg)
{
alert(msg);
//redirection link
window.location = "test.php";
}
});
}
}
This is test.php (receiving script from curl function)
$one = $_POST['user'];
$two = $_POST['pw'];
echo "results:";
echo $one;
echo "\r\n";
echo $two;
echo "\r\n";

There are a few issues, firstly, CURLOPT_POST is for a boolean not a count.
So change this:
curl_setopt($ch,CURLOPT_POST,count($fields));
to
curl_setopt($ch,CURLOPT_POST, 1); // or true
Secondly, you need to tell CURL that you want the returned data. You do that using CURLOPT_RETURNTRANSFER
So your curl related code should look like this:
//open connection
$ch = curl_init();
//set the url, number of POST vars, POST data
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);
//execute post
$result = curl_exec($ch);
print_r($result); // just see if result
//close connection
curl_close($ch);

Related

How to handle error from php handler file

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"}';
}

How can I make this api post request in PHP?

I made a post request for an api using ajax. I wonder how I can do the same in php.
<script type="text/javascript">
var cbIntegrationId = "xxxxxx"; // I have it
var clientId = "xxxxxxx"; //I have it
var clientSecret = "xxxxx"; //I have it
var tableName = "Test_Database";
//Get access token
$.post(
"https://" + cbIntegrationId + ".caspio.com/oauth/token",
{
grant_type: "client_credentials",
client_id: clientId,
client_secret: clientSecret
},
function(cbAuth){
//Run POST call
$.ajax({
url: "https://" + cbIntegrationId + ".caspio.com/rest/v2/tables/" + tableName + "/records?response=rows",
type: 'POST',
'data': JSON.stringify({"UniqueID":"988"}), //Define record values
headers: {
"Authorization": "Bearer " + cbAuth.access_token, //Extracts the access token from the initial authorization call
"Content-Type": "application/json", //Required, otherwise 415 error is returned
"Accept": "application/json"
},
dataType: 'json',
success: function (data) {
console.log(data.Result); //Check the console to view the new added row
},
error: function(data) {
console.log(data.responseJSON); //Check the console to view error message if any
}
});
}
);
</script>
I did some research but couldn't find anything that would solve my problem. I really need your help.
You can use cURL to call an API using PHP.
So according to your case you are sending data using POST method. So, we can use cURL as follows with some headers,
$apiURL = "https://yourURL";
$uniqueID = "UniqueID:988";
$postData = json_encode($uniqueID); // Encode the data into a JSON string
$authorization = "Authorization: Bearer " . $token; // Prepare the authorization token
$curl = curl_init();
curl_setopt($curl, CURLOPT_HTTPHEADER, array($authorization, 'Content-Type: application/json', 'Accept : application/json')); // Inject the token into the header
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); // To get actual result from the successful operation
curl_setopt($curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); // Specify HTTP protocol version to use;
curl_setopt($curl, CURLOPT_POST, 1); // Specify the request method as POST
curl_setopt($curl, CURLOPT_URL, $apiURL); // Pass the API URL
curl_setopt($curl, CURLOPT_POSTFIELDS, $postData); // Set the posted fields
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); // This will follow any redirects
$response = curl_exec($curl); // Here you will get the response after executing
$error = curl_error($curl); // Return a string containing the last error for the current session
curl_close($curl); // Close a cURL session
Hope this helps you!

Send JSON by cURL always returns "No access"

I have this JSON data:
$.ajax({
type: "GET",
url: "http://www.example.com/test.php",
data:"code=Sh9QA&token=0982ff3066a3c60dbd3ecf9bcafc801b",
contentType: "application/json; charset=utf-8",
});
To send this data to http://www.example.com/test.php, I have tried with this code:
<?php
//API URL
$url = 'http://www.example.com/test.php';
//Initiate cURL.
$ch = curl_init($url);
//The JSON data.
$jsonData = array(
'data' => 'code=Sh9QA&token=0982ff3066a3c60dbd3ecf9bcafc801b'
);
//Encode the array into JSON.
$jsonDataEncoded = json_encode($jsonData);
//Tell cURL that we want to send a POST request.
curl_setopt($ch, CURLOPT_POST, 1);
//Attach our encoded JSON string to the POST fields.
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonDataEncoded);
//Set the content type to application/json
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
//Execute the request
$result = curl_exec($ch);
?>
But, it always retuns No access.
What are wrong in my code? Can you help me to fix it?
Sorry about my English, it is not good. If my my question is not clear, please comment below this question.
First check http://www.example.com/test.php
Ajax system can't be used with full domain name.
so you should use /test.php
Then checking for an error that occurs in your site or target site.
Then the code becomes:
$.ajax({
type: "GET",
url: "/test.php",
data:"code=Sh9QA&token=0982ff3066a3c60dbd3ecf9bcafc801b",
contentType: "application/json; charset=utf-8",
success: function(data, textStatus) {
alert(data);
data = $.parseJSON(data);
},
error : function(data, textStatus, error){
alert(data + " : "+ textStatus);
}
});
Without the documentation to look out the only thing I can suggest is to remove the data from the array and just make it key code.
<?php
//API URL
$url = 'http://www.example.com/test.php';
$data = "?code=Sh9QA&token=0982ff3066a3c60dbd3ecf9bcafc801b"
//Initiate cURL.
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url . $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
//Execute the request
$result = curl_exec($ch);
?>

AJAX not posting data to PHP in IE only

So I have an AJAX call that I'm using to POST 1 variable to a PHP script I have on a separate server. The PHP takes this variable and returns data based off of what the variable is. This works on all browsers except IE9 and below. IE9 returns data but it's an error saying the variable is missing which to me shows that it isn't sending the data. Below I have the AJAX call I'm making:
(function (jQ) {
var inviteID = '00000000000';
jQ.ajax({
url: 'www.example.com/test.php',
type: 'POST',
dataType: 'json',
cache: false,
data: { classID: inviteID },
error: function (data, status, error) {
jQ('.statusField').append('Failure: ' + data + status + error);
},
success: function (data, status, error) {
jQ('.statusField').append('Success: ' + data);
}
});
})(jQuery);
And below I have the PHP script that's being used:
<?php
//first POST to grab token
function runPost($classID) {
$postdata = array(
'username' => 'username',
'password' => 'password'
);
//open connection
$ch = curl_init();
//set the url, POST data
curl_setopt($ch, CURLOPT_URL, "https://www.example.com/login");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($postdata));
curl_setopt($ch, CURLOPT_USERAGENT, 'example');
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
//execute post
$result = curl_exec($ch);
//close connection
curl_close($ch);
list($message, $time, $token, $userID) = split(',', $result);
list($one, $two, $three, $four, $five) = split('\"', $token);
$four = json_encode($four);
$four = str_replace('"','',$four);
$secondaryPostData = array(
'token' => $four,
'data' => array( 'invitationID' => $classID
));
//open connection
$chu = curl_init();
//set the url, POST data
curl_setopt($chu, CURLOPT_URL, "https://www.example.com/classID");
curl_setopt($chu, CURLOPT_POST, 1);
curl_setopt($chu, CURLOPT_POSTFIELDS, json_encode($secondaryPostData));
curl_setopt($chu, CURLOPT_USERAGENT, 'example');
curl_setopt($chu, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($chu, CURLOPT_RETURNTRANSFER, 1);
//execute post
$secondResult = curl_exec($chu);
//close connection
curl_close($chu);
return json_encode($secondResult);
}
//Grab classID from javascript
echo runPost(trim($_POST['classID']));
?>
Again, this works fine in everything except IE. I've tried several different methods but everything gives me the same error. The network console in IE shows that the Request body does have the classID in it, but I'm guessing it's just not sending the data to the PHP script. I don't know if I'm missing something that IE needs to send this to the PHP script but any help with this would be GREATLY appreciated.
Have you tried using this ?
$("button").click(function(){
$.post("demo_test.php",function(data,status){
alert("Data: " + data + "\nStatus: " + status);
});
});
works for me in chrome and IE.
$.post() is a short hand method for $.ajax();
It does every thing you could do in $.ajax(); when I started having this problem I never used $.ajax(); unless I had to send FormData an entire object off all the field inputs in a form

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