This question already has answers here:
PHP, cURL, and HTTP POST example?
(14 answers)
Closed 3 years ago.
I just played with PHP Curl for the first time and wrote a sample code, but I don't know how to pass the parameters in the URL correctly.
Remote Site Code:
if(isset($_REQUEST['updateme']))
{
$license = $Gauntlet->filter($_REQUEST['licensekey']);
$domainnew = $Gauntlet->filter($_REQUEST['domainnew']);
$domainold = strtolower($_SERVER['REMOTE_ADDR']);
$sqlcheckexist = "SELECT * FROM licenses WHERE licensekey = '$license' AND host = '$domainold' AND status = 'active'";
$querycheck = $DatabaseHandler->query($sqlcheckexist);
if($querycheck)
{
if($querycheck->num_rows < 1){
$json['status'] = 301;
$json['message'] = 'Wrong Domain or License';
}else{
$sqlupdate = "UPDATE licenses SET host = '$domainnew', status = 'active' WHERE licensekey = '$license'";
$json['message'] = 'Success!';
}
}
}
Remote Site API Url: mydomain.com/myapi/
How can i do this REQUEST in Url with parameters if i POST licensekey and domainnew and Update my Database value?
You can post value using php curl like this
$payload=array();
$payload['licensekey']='abc';
$payload['domainnew']='123';
$payload['updateme']='update';
$payload=json_encode($payload);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
curl_setopt($ch, CURLOPT_POSTREDIR, 3);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$res=curl_exec($ch);
Related
I've created a sample script utilising Securepay's direct post api documentation provided at https://www.securepay.com.au/wp-content/uploads/2017/06/Direct_Post_Integration_Guide.pdf
Here is the script code:
$test_url = "https://test.api.securepay.com.au/directpost/authorise";
$EPS_MERCHANTID = "ABC0001"; //manual id
$Transaction_Password = "abc123"; // manual password
$EPS_TXNTYPE = 0; //sending default
$EPS_REFERENCEID = "1234"; //manual order id
$EPS_AMOUNT = "20.77";
$EPS_TIMESTAMP = gmdate('Ymdhis');
$hash_string = "$EPS_MERCHANTID|$Transaction_Password|$EPS_TXNTYPE|$EPS_REFERENCEID|$EPS_AMOUNT|$EPS_TIMESTAMP";
$sha_256_string = hash('SHA256',$hash_string);
//card details
$EPS_CARDNUMBER = "4444333322221111";
$EPS_EXPIRYMONTH = "01";
$EPS_EXPIRYYEAR = "2020";
$EPS_CCV = 123;
$EPS_CURRENCY = "AUD";
$post_data = "EPS_MERCHANT=".$EPS_MERCHANTID
."&EPS_TXNTYPE=".$EPS_TXNTYPE
."&EPS_AMOUNT=".$EPS_AMOUNT
."&EPS_REFERENCEID=".$EPS_REFERENCEID
."&EPS_TIMESTAMP=".$EPS_TIMESTAMP
."&EPS_CARDNUMBER=".$EPS_CARDNUMBER
."&EPS_EXPIRYMONTH=".$EPS_EXPIRYMONTH
."&EPS_EXPIRYYEAR=".$EPS_EXPIRYYEAR
."&EPS_CCV=".$EPS_CCV
."&EPS_RESULTURL="."https://mydomain.com.au/pay.php" //custom url form - mydomain.com.au is replaced with personal domain
."&EPS_CURRENCY=".$EPS_CURRENCY
."&EPS_FINGERPRINT=".$sha_256_string;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $test_url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
$ch_result = curl_exec($ch);
print_r($ch_result);
This script outputs to error "Invalid Fingerprint".
Any help to resolve this will be greatly appreciated.
The issue is now resolved with help of secure pay support and a bit of research.
The above code has two errors:
The Fingerprint should be encrypted with HMAC and transaction password should be used as a secret.
$sha_256_string = hash_hmac('SHA256',$hash_string,$Transaction_Password);
GMT Timestamp should use a 24hr format
$EPS_TIMESTAMP = gmdate('YmdGis', time());
I am using the API to retrieve some information. But my problem is that I don't want all the columns that are in there but just want only specific one's. Like "Description","StartDate","EndDate"etc.
And the below code is working fine if i just want to retrieve one column using $select:
$sdate=$_POST["Startdate"];
$edate=$_POST["Enddate"];
$Authorization= "Token: $result";
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 100);
curl_setopt($ch, CURLOPT_HTTPHEADER, ["Content-type:application/JSON",
$Authorization]);
$api_request_parameter1 = ['search'=>"StartDate gt DateTime'$sdate' and StartDate le DateTime'$edate'"];
$api_request_parameter7 = ['$orderby'=>"Description"];
$api_request_parameter2 = array('$select'=>"Description");
//$api_request_parameter3 = ['$select'=>"StartDate"];
//$api_request_parameter4 = ['$select'=>"EndDate"];
//$api_request_parameter5 = ['$select'=>"StaerTime"];
//$api_request_parameter6 = ['$select'=>"EndTime"];
//$api_request_parameter2 = array('select'=>"");
$api_request_url = "...../api/v1/Events/10";
$api_request_url .= "?".http_build_query($api_request_parameter1).http_build_query($api_request_parameter2).http_build_query($api_request_parameter7);
curl_setopt($ch, CURLOPT_URL, $api_request_url);
$response = curl_exec($ch);
echo $response;
I have tried to select multiple column using
$api_request_url .= "?".http_build_query($api_request_parameter1).http_build_query($api_request_parameter2).http_build_query($api_request_parameter3).http_build_query($api_request_parameter7);
But not succeeded.
Can you please help me to solve this issue?
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
I am currently writing a piece of code to interface with an API in Python. Supplied by the company that hosts the API is a PHP script that logs into the API given the correct username and password, retrieved the current event ID (JSON format), and then logs out. This works perfectly.
Currently, I am in the process of writing a script in Python to do the very same thing, the current code is shown below. It logs in and out successfully, however, when it tries to retrieve the current event ID I get the status code 404, suggesting that the URL doesn't exist, despite this same URL working with the PHP code.
PHP Code:
define('BASE_URL', 'https://website.api.com/');
define('API_USER', 'username');
define('API_PASS', 'password');
$cookiefile = tempnam(__DIR__, "cookies");
$ch = curl_init();
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookiefile);
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookiefile);
$loginParams = array(
'username' => API_USER,
'password' => API_PASS
);
$obj = CurlPost($ch, BASE_URL . '/api/login', $loginParams);
if( $obj->success )
{
echo 'API login successful.' . PHP_EOL;
}
$obj = CurlGet($ch, BASE_URL . '/api/current-event-id');
echo 'API current event ID: ' . $obj->currentEventId . PHP_EOL;
// logout of the API
$obj = CurlGet($ch, BASE_URL . '/api/logout' );
if( $obj->success )
{
echo 'Logged out successfully.' . PHP_EOL;
}
curl_close($ch);
exit(0);
// -------------------------------------------------------------------------
// Functions
// -------------------------------------------------------------------------
// Run cURL post and decode the returned JSON object.
function CurlPost($ch, $url, $params)
{
$query = http_build_query($params);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, count($query));
curl_setopt($ch, CURLOPT_POSTFIELDS, $query);
$output=curl_exec($ch);
$obj = json_decode($output);
return $obj;
}
// Run cURL get and decode the returned JSON object.
function CurlGet($ch, $url)
{
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, '');
$output=curl_exec($ch);
$obj = json_decode($output);
return $obj;
}
Python Code:
import requests
BASE_URL = 'https://website.api.com/';
API_USER = "username";
API_PASS = "password";
headers = {'content-type': 'application/json'}
PARAMS = {'username':API_USER,'password':API_PASS}
session = requests.Session()
# Login
resp = session.post(BASE_URL + '/api/login',data=PARAMS)
if resp.status_code != 200:
print("*** ERROR ***: Login failed.")
else:
print("API login successful.")
resp = session.get(BASE_URL + '/api/current-event-id', headers=headers)
print(resp.status_code)
print(resp.text)
# Logout
resp = session.get(BASE_URL + '/api/logout')
if resp.status_code != 200:
print("*** ERROR ***: Logout failed.")
else:
print("API logout successful.")
It's ideal to change BASE_URL to:
'https://website.api.com'
the code looks fine to me when compared to php and should normally work.(Shouldn't you be passing some kind of authentication like a token?).
try debugging your API using postman.
It turns out that my API will only accept cookies transferred in the header, so I wrote a slight hack that dumped the cookiejar into a string that could be sent in the header file.
cookies = json.dumps(requests.utils.dict_from_cookiejar(resp.cookies));
cookies = cookies.replace('"', '')
cookies = cookies.replace('{', '')
cookies = cookies.replace('}', '')
cookies = cookies.replace(': ', '=')
cookies = cookies.replace(',', ';')
headers = {'Cookie':cookies}
resp = session.get(BASE_URL + '/api/current-event-id', headers=headers)
my problem is that i'm working with salesforce in wordpress, i'm not using wordpress-to-lead plugin, I have a form in a template and that form sends data to salesforce via cURL and also is posting data in database cause I have to generate a password and then send it to the user but its not working, is working salesforce but not saving data in the database, here is my code to post data in database and generate the password
$keysString = implode(", ", array_keys($blank_section));
unset($_POST['userId']);
$user_id = mysql_query("SELECT MAX(id) AS id FROM int_form_data");
$user_id = $user_id+11;
$passwordSend = 'INTELIGOS'.rand(10000, 5000000);
$array_user_id = array('user_id' => $user_id, 'password' => $passwordSend);
$posted_data = array_merge($_POST,$array_user_id);
foreach($posted_data as $k=>$v) {
$itfdatainfo[$k] = $v;
}
$itfkeys = array_keys($itfdatainfo);
$itfvalues = array_values($itfdatainfo);
if(isset($_POST['submit'])) {
$sql = "INSERT INTO int_form_data (".implode(',',$itfkeys).") VALUES('".implode("','",$itfvalues)."')";
$result = mysql_query($sql);
}
And here I use cURL to send data to Salesforce:
//Initialize the $query_string variable for later use
$query_string = "";
$kv = array();
//If there are POST variables
if ($_POST) {
//Initialize the $kv array for later use
//For each POST variable as $name_of_input_field => $value_of_input_field
foreach ($_POST as $llav => $value) {
//Set array element for each POST variable (ie. first_name=Arsham)
$kv[] = stripslashes($llav)."=".stripslashes($value);
}
//Create a query string with join function separted by &
$query_string = join("&", $kv);
}
//Check to see if cURL is installed ...
if (!function_exists('curl_init')){
die('Sorry cURL is not installed!');
}
//The original form action URL from Step 2
$url = 'https://www.salesforce.com/servlet/servlet.WebToLead?encoding=UTF-8';
//Open cURL 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($kv));
curl_setopt($ch, CURLOPT_POSTFIELDS, $query_string);
//Set some settings that make it all work
curl_setopt($ch, CURLOPT_HEADER, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, FALSE);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
//Execute SalesForce web to lead PHP cURL
$result = curl_exec($ch);
//close cURL connection
curl_close($ch);
Anyone knows why is happening that? I have all the code in one template in wordpress
I'm looking at this INSERT INTO int_form_data (".implode(',',$itfkeys).") and thinking if some column name in $itfkeys needs to be enclosed in backticks then it would cause an sql error.