I have had a successful response from SagePay with a registered transaction.
I have filled in all card details, and i know the data is reaching my notificationurl.
but then it stops. Zero response, and nothing is sent.
To simplify things ive stripped out the code and used hard-coded vars to see if anybody can assist.
ob_clean();
if(isset($_POST) && isset($_POST['Status'])){
if(isset($_POST['Status']) && $_POST['Status'] == 'OK'){
$data['Status'] = 'OK';
$data['RedirectURL'] = 'https://www.metano.com/payments/success';
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,'https://test.sagepay.com/gateway/service/vspserver-register.vsp');
curl_setopt($ch,CURLOPT_POSTFIELDS,"Status=OK\nRedirectURL=https://www.metano/payments/success");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_HEADER, 0);
$output = curl_exec($ch);
}
}
Data passed to cURL as a string should be URLencoded. See the page for curl_setopt() and search for CURLOPT_POSTFIELDS.
From php5 upwards, usage of http_build_query is recommended:
Related
I have a problem when I run this script in Google Chrome I got a blank page. When I use another link of a web site, it works successfully. I do not what is happening.
$curl = curl_init();
$url = "https://www.danmurphys.com.au/dm/home";
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$output = curl_exec($curl);
echo $output;
There are some conditions which make your result blank. Such as:
Curl error.
Redirection without response body and the curl doesn't follow the redirection.
The target host doesn't give any response body.
So here you have to find out the problem.
For the first possibility, use curl_error and curl_errno to confirm that the curl wasn't errored when its runtime.
For the second, use CURLOPT_FOLLOWLOCATION option to make sure the curl follows the redirection.
For the third possibility, we can use curl_getinfo. It returns an array which contains "size_download". The size_download shows you the length of the response body. If it is zero that is why you see a blank page when printing it.
One more, try to use var_dump to see the output (debug purpose only). There is a possibility where the curl_exec returns bool false or null. If you print the bool false or null it will show a blank.
Here is the example to use all of them.
<?php
$curl = curl_init();
$url = "https://www.danmurphys.com.au/dm/home";
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
$output = curl_exec($curl);
$info = curl_getinfo($curl);
$err = curl_error($curl);
$ern = curl_errno($curl);
if ($ern) {
printf("An error occurred: (%d) %s\n", $ern, $err);
exit(1);
}
curl_close($curl);
printf("Response body size: %d\n", $info["size_download"]);
// Debug only.
// var_dump($output);
echo $output;
Hope this can help you.
Update:
You can use CURLOPT_VERBOSE to see the request and response information in details.
Just add this
curl_setopt($curl, CURLOPT_VERBOSE, true);
It doesn't need to be printed, the curl will print it for you during runtime.
I'm doing a project and one of the requests is to automatically submit a form to a random site, which is specified from time to time
This is my cURL code :
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url_post);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $dati_post);
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie_file);
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie_file);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
curl_close($ch);
Code to get POST parameters :
foreach ($html->find('form[method=post],form[method=POST]') as $forms_post) {
$n_formPOST++;
$formPOST_action = $forms_post->action;
foreach ($forms_post->find('input') as $input) {
if ($input->type == 'text') {
$dati_testo[$input->name] = "text";
} else if ($input->type == 'email' || $input->name == 'email') {
$dati_random[$input->name] = "emailrandom#gmail.com";
} else if ($input->type == 'hidden') {
$dati_random[$input->name] = $input->value;
} else {
$dati_random[$input->name] = "random";
}
}
foreach ($forms_post->find('textarea') as $textarea) {
if ($textarea->disabled != true) {
$dati_testo[$textarea->name] = "text";
}
}
foreach ($forms_post->find('button') as $bottone) {
if ($bottone->type == 'submit') {
$dati_random[$bottone->name] = "random";
}
}
The problem is that in some sites POST is done correctly and I receive the right answer, which corresponds to the answer I would receive by doing it manually.
On other sites, it seems that the form is not submitted.
I have repeatedly checked the URL that I insert in the cURL and also the data that I pass and if I use them manually it works.
I even tried using online tools that perform POST / GET passing the same URL and the same data that I get in my project and it works.
The url_post is made from url host+form action.
I don't understand if there is something wrong in my curl code, considering I'm pretty sure the data I'm passing to the curl are corrects to complete the POST.
Data :
Site URL : http://www.comune.ricigliano.sa.it/
Form Action : index.php?action=index&p=228
Url_post : http://www.comune.ricigliano.sa.it/index.php?action=index&p=228
POST data :
'qs' => 'something to research'
'Submit2' => 'Cerca'
You need to use the curl_exec() function in order to execute the cURL. It takes the $ch param, like such:
// Execute cURL
curl_exec($ch);
// Close cURL
curl_close($ch);
More info here
We got a couple of apps, utilizing the car2go Rest-API with OAuth 1.0.
All our web apps stopped working 2 days ago. All curl POST requests are failing now with the following error:
400 Bad Request
Your browser sent a request that this server could not understand.
Error code: 53
Parser Error: [Content-Length: -]
I spend a lot of time trying to figure out if the problem is my oauth workflow. But in the end all parameters and signatures and stuff is correct. I successfully fire the POST via Postman (REST-Client)
So my conclusion is that somehow the php code for the curl is suddenly not working anymore.
This is the (very ugly) curl function. A difference to most tutorials about curl POST is, that I'm passing a full URL with all parameters already attached, so I don't need CURLOPT_POSTFIELDS.
function curlAPI($params) {
//open connection
$ch = curl_init();
$url = $params['url'];
curl_setopt($ch,CURLOPT_HEADER,false);
//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION,true);
curl_setopt($ch, CURLOPT_MAXREDIRS,50);
curl_setopt($ch, CURLOPT_TIMEOUT_MS, 5000);
if($params['type'] == 'POST') {
// POST
curl_setopt($ch,CURLOPT_POST, true);
} else if($params['type'] == 'DELETE') {
// DELETE
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE");
} else if($params['type'] == 'PUT') {
$update_json = array();
// PUT
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($ch, CURLOPT_POSTFIELDS,'');
} else {
// GET
curl_setopt($ch,CURLOPT_POST,0);
}
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
//execute post
$result['result'] = curl_exec($ch);
// debug
if (FALSE === $result['result']) {
$result['errorInfo'] = curl_error($ch).' - '.curl_errno($ch);
}
$reponseInfo = array();
$reponseInfo['info'] = curl_getinfo($ch);
$reponseInfo['error'] = curl_error($ch);
//close connection
curl_close($ch);
$result['reponseInfo'] = $reponseInfo;
return json_encode($result);
}
Ok, this is what fixed this nightmare:
curl_setopt($ch,CURLOPT_HTTPHEADER ,array('Content-Length: 0'));
Aparrently it's not ok to send a curl POST without a header.
I am developing a script involving Php Curl to send sms using http://www.gysms.com/freesms.php
The page stores a cookie PHPSESSID and also a hidden field named token is passed during the posting.
I have written a script involving two curl requests. 1st curl request parse the page and obtain the token value .
Here is the code for that:
<?php
$phone = '9197xxxxxxx';
$msg = 'Hi this is curlpost';
$get_cookie_page = 'http://www.gysms.com/freesms.php';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $get_cookie_page);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$sabin = curl_exec($ch);
$html=explode('<input type="hidden" name="trigger" value="',$sabin);
$html=explode('"/>',$html[1]);
//store the token value to $html[0]
?>
Curl post is done using the following code:
<?php
$fields = array(
'trigger'=>urlencode($html[0]), //token value
'number'=>urlencode($phone), //phone no
'message'=>urlencode($msg) //message
);
//posting curl request
foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
rtrim($fields_string,'&');
$url = 'http://www.gysms.com/freesms.php';
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);
curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookie.txt');
curl_setopt($ch, CURLOPT_COOKIEFILE, 'cookie.txt');
//execute post
$result = curl_exec($ch);
echo $result;
curl_close($ch);
?>
The sms is not sending Using the above code.
If the sms is sent It should show sms is send to-No.
I don't Know where I went wrong. Please help, I am new to PHP.
Finally this attempt is only for my educational purpouse.
Here is some code I came up with that worked. Hope it helps. Some explanations and feedback about your code follow.
<?php
$number = '14155556666';
$message = 'This is my text in all its glory.';
$url = 'http://www.gysms.com/freesms.php';
$cookieFile = tempnam(null, 'SMS');
$userAgent = 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:11.0) Gecko/20100101 Firefox/11.0';
if (strlen($message) > 100) {
die('Message length cannot exceed 100 characters.');
}
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookieFile);
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookieFile);
curl_setopt($ch, CURLOPT_USERAGENT, $userAgent); // empty user agents probably not accepted
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_AUTOREFERER, 1); // enable this - they check referer on POST
$html = curl_exec($ch);
// <input type="hidden" name="trigger" value="CXXrtmqVC7KbUnJ22UBodFy1kBj4ign5PsQ3qNR91nH2055307b4xP4"/>
if (!preg_match('/name=.trigger.\s+value=.([^\'"]+)/i', $html, $trigger)) {
die('Failed to locate hidden input value');
}
sleep(5); // without a slight delay, i often would not receive sms
$trigger = $trigger[1];
// build array of post values - all are important
$post = array('number' => $number,
'trigger' => $trigger,
'message' => $message,
'remLen' => 100 - strlen($message),
$trigger => 'Send Message');
// switch request to POST, use http_build_query to encode post data for us
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post));
$html = curl_exec($ch);
if (strpos($html, '<b>Message sent to</b>') !== false) {
echo "Message sent!";
} else {
echo "<b>Message not sent :(</b><br /><br />";
echo $html;
}
I think you may have had trouble for several reasons:
A User-Agent should be specified in the request, they seem to reject if you leave it empty
I used http_build_query to build the POST string (preference)
You were missing 2 fields in the request, remLen, and the trigger value as the submit button
I often would not receive the messages if I didn't sleep a few seconds before sending the message after getting the trigger value.
In most of the cases where I didn't get the message, it still showed the "Message sent to phone #" on the screen even though it never came. Once I combined all the right things (sleep time, user agent, valid post fields) I would see the success message but also get the response.
I think the most critical thing left out from your code was that on the first request where you grab the trigger value, they also set a cookie (PHPSESSID) that you are required to capture. Without sending that on the POST request it was probably an automatic reject.
To get around this, make sure you capture cookies on the first request as well as subsequent requests. I chose to re-use the same curl handle for both requests. You don't have to do it that way, but you would have to use the same cookie file and cookie jar between requests.
Hope that helps.
I have a frontend code
$ch = curl_init();
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
//curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept: application/json'));
curl_setopt($ch, CURLOPT_URL, $url);
//make the request
$responseJSON = curl_exec($ch);
$response_status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($response_status == 200) { // success
// remove any "problematic" characters from the json string and then decode
if (debug) {
echo "----finish API of getAPI inside basic_function with status==200---";
echo "<br>";
echo "-------the json response is-------" ; //.$responseJSON;
var_dump($responseJSON);
//print_r($responseJSON);
echo "<br>";
}
return json_decode( preg_replace( '/[\x00-\x1F\x80-\xFF]/', '', $responseJSON ) );
}
and I have a backend code which executed when cURL fired its operation with its URL. The backend code would therefore activated. So, I know cURL is operating.
$output=array (
'status'=>'OK',
'data'=>'12345'
)
$output=json_encode($output)
echo $output;
and $output shown on browser as {"status":"OK","data":"12345"}
However, I gone back to the frontend code and did echo $responseJSON, I got nothing. I thought the output of {"status":"OK","data":"12345"} would gone to the $responseJSON. any idea?
Here's output on Browser, something is very odd! the response_status got 200 which is success even before the parsing of API by the backend code. I expect status =200 and json response after the {"status":"OK","data":"12345"}
=========================================================================================
inside the get API of the basic functions
-------url of cURL is -----http://localhost/test/api/session/login/?device_duid=website&UserName=joe&Password=1234&Submit=Submit
----finish API of getAPI inside basic_function with status==200---
-------the json response is-------string(1153)
"************inside Backend API.php******************
---command of api is--/session/login/
---first element of api is--UserName=joe
--second element of api is---Password=1234
---third element of api is----Submit=Submit
----fourth element of api is---
-------inside session login of api-------------
{"status":"OK","data":"12345"}
Have you tried with curl_setopt($ch, CURLOPT_TIMEOUT, 10); commented?
See what happends if you comment that line.
Also try with the a basic code, if that works, smthing you added later is wrong:
// create a new cURL resource
$ch = curl_init();
// set URL and other appropriate options
curl_setopt($ch, CURLOPT_URL, "http://www.example.com/");
curl_setopt($ch, CURLOPT_HEADER, false);
// grab URL and pass it to the browser
curl_exec($ch);
// close cURL resource, and free up system resources
curl_close($ch);
Try var_dump($responseJSON)
If it returns false try
curl_error ( $ch )
Returns a clear text error message for the last cURL operation.
Are you sure your $url is correct?