need some information about php curl - php

Please before my question please see those data 1st.
API URL: https://api.awebsite.com/api/redeem
Data Sent Method: POST
Requested Headers:
Host: api.awebsite.com
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:64.0) Gecko/20100101 Firefox/64.0
Accept: application/json
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate, br
Referer: https://m.awebsite.com/en/exchange
Content-Type: application/json
Content-Length: 87
Origin: https://m.awebsite.com
Connection: keep-alive
Cookie: PHPSESSID=e0c4f6ec8a13e963bf6b11ebc33a96d2
TE: Trailers
Pragma: no-cache
Cache-Control: no-cache
Posted Data
{"redeemcode":"f564hfkj4shfee25","gameid":"123456","vcode":"7895","language":"en"}
I collect all of those from Browser > Inspect > Network area.
My Question is, Can I use php curl to post data to that api url from my localhost or my server? I Write my own code but its not working.. Here is my code.
//API Url
$url = 'https://api.awebsite.com/api/redeem';
$code = 'f564hfkj4shfee25';
$user = '123456';
$vcode = '7895';
//Initiate cURL.
//$ch = curl_init();
//The JSON data.
$jsonData = array(
'redeemcode' => $code,
'gameid' => $user,
'vcode' => $vcode,
'language' => 'en'
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
//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'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_REFERER, 'https://m.awebsite.com/en/exchange');
//Execute the request
$result = curl_exec($ch);
Do you think there is a way to post data using php?

Yes, you can send post with cURL to other domain but... the other domain (https://api.awebsite.com/api/redeem) need allow the access with a cross domian policy
<?PHP
//API Url
$url = 'https://api.awebsite.com/api/redeem';
$code = 'f564hfkj4shfee25';
$user = '123456';
$vcode = '7895';
//Initiate cURL.
//$ch = curl_init();
//The JSON data.
$jsonData = array(
'redeemcode' => $code,
'gameid' => $user,
'vcode' => $vcode,
'language' => 'en'
);
$ch = curl_init();
//curl_setopt($ch, CURLOPT_URL, $url);
//Encode the array into JSON.
$jsonDataEncoded = json_encode($jsonData);
$defaults = array(
CURLOPT_URL => $url,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $jsonDataEncoded,
CURLOPT_HTTPHEADER => array('Content-Type: application/json'),
CURLOPT_RETURNTRANSFER => true,
CURLOPT_VERBOSE => true,
CURLOPT_SSL_VERIFYPEER => false // <= Skip the secure validation
);
curl_setopt_array($ch, ($defaults));
//Execute the request
echo $result = curl_exec($ch);
$info = curl_getinfo($ch);
var_dump($info);
curl_close($ch);

Related

How to send HTTP GET request to REST API via cURL using PHP and call method from REST API with cURL

I'm using PHP and cURL.
I want to send HTTP GET request to REST API and I want to call method from REST API. How can i make via cURL using PHP? I have API URL and Key. I must send my key with URL and I need method inside REST API. What I need to do? At the same time, i have to send basic authentication on all requests and I'll get JSON data.How can i do?
Thanks.
Regards
this is my code
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 20);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERPWD, $username.':'.$password);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Accept: application/json',
'Content-Type: application/json')
);
$result = curl_exec($ch);
curl_close($ch);
I have tried your code and changed variables into array.
Added httpheaders, useragents.
And save to cookies and cookie location.
And tested:
$username = "username";
$password = "password";
$url = "http://localhost/html/login";
$send = "?username=".$username."&password=".$password;
$ch = curl_init();
curl_setopt_array($ch, array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_FOLLOWLOCATION => 1,
CURLOPT_VERBOSE => 1,
CURLOPT_USERAGENT => 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:37.0) Gecko/20100101 Firefox/37.0',
CURLOPT_POST => true,
CURLOPT_USERNAME, $username,
CURLOPT_USERPWD, $password,
CURLOPT_POSTFIELDS => $send,
CURLOPT_SSL_VERIFYPEER, false,
CURLOPT_HEADER => 1,
CURLOPT_HTTPHEADER => array(
"Accept-Language: en-US;q=0.6,en;q=0.4",
"Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
"Connection: keep-alive"
),
CURLOPT_COOKIEFILE => "cookies.txt",
CURLOPT_COOKIEJAR => "cookies.txt",
CURLOPT_REFERER => "http://localhost/html/login",
CURLOPT_ENCODING => 'gzip,deflate'
)); //gzip, if modul on
curl_exec($ch);
curl_close($ch);

sending Curl POSTFIELDS array

I am trying to use CURL to post the following fields to PANDADOCS, but for some reason I am getting an error that the values are not being received on their side.
This is the error I am getting:
"type": "validation_error", "detail": {"url": ["This field is required."], "name": ["This field is required."]}}
I am posting with the following:
$docurl = "myurl.com/document.pdf";
$headr = array();
$headr[] = 'Content-length: 0';
$headr[] = 'Content-Type: application/json;charset=UTF-8';
$headr[] = "Authorization: Bearer $ACCESS_TOKEN";
$url = 'https://api.pandadoc.com/public/v1/documents';
$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPHEADER,$headr);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, FALSE);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_USERAGENT, $useragent);
$postfields = array();
$postfields['name'] = 'PSA';
$postfields['url'] = $docurl;
$postfields['recipients'] = array ([0]=>array(
['email'] => ['dondon#gmail.com'],
['first_name'] => ['don'],
['last_name'] => ['jones'],
['role']=>['u1'] ));
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query( $postfields) );
$ret = curl_exec($ch); //
when I print_r($postfields)
I get
Array ( [name] => PSA [url] => https://api.pandadoc.com/public/v1/documents [recipients] => Array ( ) )
so all the fields arent getting posted.
but whats wierd is that the URL and NAME are in the array but not the other fields yet the error is complaining about not receiving NAME and URL..
dazed and confused...
* Hostname was found in DNS cache
* Trying 54.190.72.92...
* Connected to api.pandadoc.com (54.190.72.92) port 443 (#28)
* SSL connection using TLSv1.2 / ECDHE-RSA-AES256-GCM-SHA384
* Server certificate:
* subject: OU=GT83522468; OU=See www.rapidssl.com/resources/cps (c)14; OU=Domain Control Validated - RapidSSL(R); CN=*.pandadoc.com
* start date: 2014-11-09 00:32:24 GMT
* expire date: 2016-10-11 09:34:58 GMT
* subjectAltName: api.pandadoc.com matched
* issuer: C=US; O=GeoTrust Inc.; CN=RapidSSL SHA256 CA - G3
* SSL certificate verify result: unable to get local issuer certificate (20), continuing anyway.
> POST /public/v1/documents HTTP/1.1
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/533.2 (KHTML, like Gecko) Chrome/5.0.342.3 Safari/533.2
Host: api.pandadoc.com
Accept: */*
Content-length: 0
Content-Type: application/json;charset=UTF-8
Authorization: Bearer [ACCESS TOKEN]
* upload completely sent off: 37 out of 37 bytes
< HTTP/1.1 400 BAD REQUEST
* Server nginx/1.4.6 (Ubuntu) is not blacklisted
< Server: nginx/1.4.6 (Ubuntu)
< Date: Fri, 06 Mar 2015 19:52:53 GMT
< Content-Type: application/json
< Transfer-Encoding: chunked
< Connection: keep-alive
< Vary: Accept
< Allow: GET, POST, DELETE, HEAD, OPTIONS
<
* Connection #28 to host api.pandadoc.com left intact
$string is not defined.
Add
$string = http_build_query( $postfields );
after
$postfields = array();
$postfields['name'] = 'PSA';
$postfields['url'] = $docurl;
// This is invalid array
$postfields['recipients'] = array ([0]=>array(
['email'] => ['dondon#gmail.com'],
['first_name'] => ['don'],
['last_name'] => ['jones'],
['role']=>['u1'] ));
http://php.net/manual/en/function.http-build-query.php
UPDATE
I just read Pandadoc API. They accept json data and your data was invalid. Also content type.
This should work:
<?php
$url = 'https://api.pandadoc.com/public/v1/documents';
$docurl = "myurl.com/document.pdf";
$postfields = array();
$postfields['name'] = 'PSA';
$postfields['url'] = $docurl;
$postfields['recipients'] = array(
array(
'email' => 'dondon#gmail.com',
'first_name' => 'don',
'last_name' => 'jones',
'role' => 'u1'
)
);
$data_string = json_encode( $postfields );
$headr = array();
$headr[] = 'Content-length: '.strlen( $data_string );
$headr[] = 'Content-type: application/json';
$headr[] = "Authorization: Bearer $ACCESS_TOKEN";
$ch = curl_init( $url );
curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, true );
curl_setopt( $ch, CURLOPT_VERBOSE, 1 );
curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, false );
curl_setopt( $ch, CURLOPT_CUSTOMREQUEST, "POST" );
curl_setopt( $ch, CURLOPT_POSTFIELDS, $data_string );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt( $ch, CURLOPT_HTTPHEADER, $headr );
$result = curl_exec( $ch );
?>

How to use ConvertAPI Word2Pdf?

I'm trying to call ConvertAPI.com/Word2Pdf, but with no success.
My sample code is:
$fileToConvert = 'test.docx';
$apiKey = *******;
$postdata = array('OutputFileName' => 'test.pdf', 'ApiKey' => $apiKey, 'File' => $fileToConvert);
$ch = curl_init("http://do.convertapi.com/Word2Pdf");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
$result = curl_exec($ch);
$headers = curl_getinfo($ch);
curl_close($ch);
var_dump($result);
I'm getting as a result something like: "HTTP/1.1 100 Continue HTTP/1.1 400 The 'File' parameter cannot be null. Please set value. Cache-Control: no-cache, no-store Pragma: no-cache Content-Type: text/html..."
What I'm doing wrong here?
Try this using http://unirest.io/php.html library
$response = Unirest::post(
"http://do.convertapi.com/Word2Pdf?ApiKey=<Your api key>",
array(
"File" => "#/tmp/file.path",
"OutputFormat" => "pdf",
)
);

JSON over cURL in PHP not working

I have the pages below.
Page json.php:
$json_data = array(
'first_name' => 'John',
'last_name' => 'Doe',
'birthdate' => '12/02/1977',
'files' => array(
array(
'name' => 'file1.zip',
'status' => 'good'
),
array(
'name' => 'file2.zip',
'status' => 'good'
)
)
);
$url = 'http://localhost/test.php';
$content = json_encode($json_data);
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER,
array(
"Content-type: application/json",
"Content-Length: " . strlen($content)
)
);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, 'json=' . urlencode($content));
curl_setopt($curl, CURLINFO_HEADER_OUT, true);
$json_response = curl_exec($curl);
$status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
$header_sent = curl_getinfo($curl, CURLINFO_HEADER_OUT);
curl_close($curl);
echo $header_sent;
echo '<br>';
echo $status;
echo '<br>';
echo $json_response;
Page test.php:
echo '<pre>';
print_r($_POST);
echo '</pre>';
When I’m calling json.php from the browser, I get the following result:
POST /json.php HTTP/1.1 Host: localhost Accept: */* Content-type: application/json Content-Length: 150
200
Array
(
)
Why can’t I see the POST string I’m trying to send?
Edit:
If I don’t set the Content-type: application/json header (as per #landons’s comment), I get the following result:
POST /ddabvd/widendcm/widendcm-finished.php HTTP/1.1 Host: localhost Accept: */* Content-Length: 150 Content-Type: application/x-www-form-urlencoded
200
Array
(
[json] => {"first_name":"John","last_name":"Doe","birthdate":"12\/02\/1977","files":[{"name":
)
PHP does not use it's internal request parsing for POST requests if the content type is not set to one of the two official content types that are used when posting forms from inside a browser. (e.g. the only allowed content types are multipart/form-data, often used for file uploads, and the default value application/x-www-form-urlencoded).
If you want to use a different content-type, you are on your own, e.g. you have to do all the parsing yourself when fetching the request body from php://input.
In fact, your content type is currently wrong. It is NOT application/json, because the data reads json={...}, which is incorrect when being parsed as json.

php curl: I need a simple post request and retrival of page example

I would like to know how to send a post request in curl and get the response page.
What about something like this :
$ch = curl_init();
$curlConfig = array(
CURLOPT_URL => "http://www.example.com/yourscript.php",
CURLOPT_POST => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POSTFIELDS => array(
'field1' => 'some date',
'field2' => 'some other data',
)
);
curl_setopt_array($ch, $curlConfig);
$result = curl_exec($ch);
curl_close($ch);
// result sent by the remote server is in $result
For a list of options that can be used with curl, you can take a look at the page of curl_setopt.
Here, you'll have to use, at least :
CURLOPT_POST : as you want to send a POST request, and not a GET
CURLOPT_RETURNTRANSFER : depending on whether you want curl_exec to return the result of the request, or to just output it.
CURLOPT_POSTFIELDS : The data that will be posted -- can be written directly as a string, like a querystring, or using an array
And don't hesitate to read the curl section of the PHP manual ;-)
$url = "http://www.example.com/";
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
$data = array(
'username' => 'foo',
'password' => 'bar'
);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
$contents = curl_exec($ch);
curl_close($ch);
You need to set the request to post using CURLOPT_POST and if you want to pass data with it, use CURLOPT_POSTFIELDS:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://www.example.com/");
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
$data = array(
'username' => 'foo',
'password' => 'bar'
);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$contents = curl_exec($ch);
curl_close($ch);
try the one in the comments: http://php.net/manual/en/curl.examples-basic.php
(but add curl_setopt($ch, CURLOPT_POST, 1) to make it a post instead of get)
or this example: http://php.dzone.com/news/execute-http-post-using-php-cu
<?php
ob_start();
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,'https://example.com/student_list.php');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
echo $response;
?>
I think you need to add
curl_setopt($curlHandle, CURLOPT_POSTFIELDS, $postFields);
Using JSON DATA with CURL
client.php
<?php
$url="http://192.168.44.10/project/server/curl_server.php";
$data=['username'=>'abc','password'=>'123'];
$data = json_encode($data);
$ch = curl_init();
$curlConfig = array(
CURLOPT_URL => $url,
CURLOPT_HTTPHEADER => array('Content-Type: application/json'),
CURLOPT_POST => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POSTFIELDS => $data
);
curl_setopt_array($ch, $curlConfig);
$result = curl_exec($ch);
curl_close($ch);
echo $result; //here you get result like: username: abc and password: 123
?>
curl_server.php
<?php
$data = file_get_contents('php://input');
$Data= json_decode($data,true);
echo 'username: '.$Data['username']." and password: ".$Data['password'];
?>
Check out my code in this post
https://stackoverflow.com/a/56027033/6733212
<?php
if (!function_exists('curl_version')) {
exit("Enable cURL in PHP");
}
$url = "https://www.google.com/";
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_POSTFIELDS => "",
CURLOPT_HTTPHEADER => array(
"Accept: */*",
"Cache-Control: no-cache",
"Connection: keep-alive",
"Host: " . url($url),
"User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36",
"accept-encoding: gzip, deflate",
"cache-control: no-cache",
),
));
function url($url)
{
$result = parse_url($url);
return $result['host'];
}
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo "<textarea>" . $response . "</textarea>";
}
http://codepad.org/YE6fyzCA

Categories