When we make a query to [Translate API][1]:
function curl($url, $post_array=false){
$handle = curl_init();
if (FALSE === $handle)
throw new Exception('failed to CURL initialize; '. __FILE__);
curl_setopt($handle, CURLOPT_URL, $url);
curl_setopt($handle, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($handle, CURLOPT_SSL_VERIFYPEER, false);
if($post_array) {
curl_setopt($handle, CURLOPT_POST, 1 );
curl_setopt($handle, CURLOPT_POSTFIELDS, $post_array );
}
curl_setopt($handle,CURLOPT_HTTPHEADER,array('X-HTTP-Method-Override: GET'));
$response = curl_exec($handle);
return $response;
}
var_dump ( curl("https://www.googleapis.com/language/translate/v2", ['key'=>$key, 'q[]'=>"hello", 'q[]'=>"world", 'source'=>"en", 'target'=>'ru'] ) );
ends in error:
{
"error": {
"code": 400,
"message": "Required Text",
"errors": [
{
"message": "Required Text",
"domain": "global",
"reason": "required"
}
]
}
}
How to send multiple q input texts? As I see, the API doesn't allow q[] type arrays, instead it uses multiple q parameters. But in php we can't have same key multiple times in array...
i believe this API supports JSON, and JSON supports arrays, so just do
function curl($url, array $post_array){
$handle = curl_init();
curl_setopt_array($ch,array(
CURLOPT_POST=>1,
CURLOPT_POSTFIELDS=>json_encode($post_data),
CURLOPT_HTTPHEADER=>array('Content-Type: application/json')
));
(...)
}
and call it like
var_dump ( curl("https://www.googleapis.com/language/translate/v2",
['key'=>$key, 'q'=>array("hello","world"),
'source'=>"en", 'target'=>'ru'] ) );
You should encode the post fields. PHP offers http_build_query.
function curl($url, $post_array=false){
$handle = curl_init();
if (FALSE === $handle)
throw new Exception('failed to CURL initialize; '. __FILE__);
curl_setopt($handle, CURLOPT_URL, $url);
curl_setopt($handle, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($handle, CURLOPT_SSL_VERIFYPEER, false);
if($post_array) {
curl_setopt($handle, CURLOPT_POST, 1 );
curl_setopt($handle, CURLOPT_POSTFIELDS, http_build_query($post_array) );
}
curl_setopt($handle,CURLOPT_HTTPHEADER,array('X-HTTP-Method-Override: GET'));
$response = curl_exec($handle);
return $response;
}
var_dump ( curl("https://www.googleapis.com/language/translate/v2", ['key'=>$key, 'q'=> array("hello", "world"), 'source'=>"en", 'target'=>'ru'] ) );
Relevant are this post and this post.
As suggested in a comment, rather than using an array where there can not be repeated keys in the POSTFIELDS data array ( or any array in PHP ) you can supply a string for the POST data
My curl function
function curl( $url=NULL, $options=NULL ){
$cacert='c:/wwwroot/cacert.pem'; #<---- edit to suit
$vbh = fopen('php://temp', 'w+');
$res=array(
'response' => NULL,
'info' => array( 'http_code' => 100 ),
'headers' => NULL,
'errors' => NULL
);
if( is_null( $url ) ) return (object)$res;
session_write_close();
/* Initialise curl request object */
$curl=curl_init();
if( parse_url( $url,PHP_URL_SCHEME )=='https' ){
curl_setopt( $curl, CURLOPT_SSL_VERIFYPEER, true );
curl_setopt( $curl, CURLOPT_SSL_VERIFYHOST, 2 );
curl_setopt( $curl, CURLOPT_CAINFO, $cacert );
}
/* Define standard options */
curl_setopt( $curl, CURLOPT_URL,trim( $url ) );
curl_setopt( $curl, CURLOPT_AUTOREFERER, true );
curl_setopt( $curl, CURLOPT_FOLLOWLOCATION, true );
curl_setopt( $curl, CURLOPT_FAILONERROR, true );
curl_setopt( $curl, CURLOPT_HEADER, false );
curl_setopt( $curl, CURLINFO_HEADER_OUT, false );
curl_setopt( $curl, CURLOPT_RETURNTRANSFER, true );
curl_setopt( $curl, CURLOPT_BINARYTRANSFER, true );
curl_setopt( $curl, CURLOPT_CONNECTTIMEOUT, 20 );
curl_setopt( $curl, CURLOPT_TIMEOUT, 60 );
curl_setopt( $curl, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36' );
curl_setopt( $curl, CURLOPT_MAXREDIRS, 10 );
curl_setopt( $curl, CURLOPT_ENCODING, '' );
curl_setopt( $curl, CURLOPT_VERBOSE, true );
curl_setopt( $curl, CURLOPT_NOPROGRESS, true );
curl_setopt( $curl, CURLOPT_STDERR, $vbh );
/* Assign runtime parameters as options */
if( isset( $options ) && is_array( $options ) ){
foreach( $options as $param => $value ) curl_setopt( $curl, $param, $value );
}
/* Execute the request and store responses */
$res=(object)array(
'response' => curl_exec( $curl ),
'info' => (object)curl_getinfo( $curl ),
'errors' => curl_error( $curl )
);
rewind( $vbh );
$res->verbose=stream_get_contents( $vbh );
fclose( $vbh );
curl_close( $curl );
return $res;
}
The configuration for the request:
$key='AIzaSyxxxxxxxxxxxxxxxxxxx9oIhY8Q8xxxxx';
$url='https://www.googleapis.com/language/translate/v2';
$arr=array( 'another', 'elephant', 'banana', 'woman' );
/* some translate parameters */
$params=array(
'target' => 'fr',
'format' => 'text',
'source' => 'en',
'model' => 'nmt'
);
/* the POST data */
$query=implode( '&', array(
sprintf( 'key=%s&q=%s',$key, implode( '&q=', $arr ) ), #query
urldecode( http_build_query( $params ) ) #google params
));
$config=array(
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $query
);
$res=curl( $url, $config );
if( $res->info->http_code==200 ){
printf('<pre>%s</pre>',print_r( $res->response,true ) );
}
Appears to work OK and returns:
{
"data": {
"translations": [
{
"translatedText": "un autre",
"model": "nmt"
},
{
"translatedText": "l'éléphant",
"model": "nmt"
},
{
"translatedText": "banane",
"model": "nmt"
},
{
"translatedText": "femme",
"model": "nmt"
}
]
}
}
For others finding their way here and looking for how to translate multiple texts in a simple GET-request to the Google Cloud Translation v2 REST API, you just need to add multiple q= parameters to your URL.
No need to mess around with cURL, just use file_get_contents and get on with your life. Something like this would do the job:
$texts = ['foo', 'bar', 'hello world'];
// Translate from english to swedish
$queryParams = [
'target' => 'sv',
'source' => 'en',
'format' => 'text',
'key' => 'INSERT_YOUR_API_KEY_HERE',
];
// Now let's add q=<text> for each text
$queryString = http_build_query($queryParams);
foreach($texts as $t){
$queryString .= '&q='.rawurlencode($t);
}
$url = "https://translation.googleapis.com/language/translate/v2?$queryString";
$responseBody = file_get_contents($url);
$responseArr = json_decode($responseBody, true);
this is my well-worked code snippet.
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://translation.googleapis.com/language/translate/v2?API-KEY');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
$text1="The Great Pyramid of Giza (also known as the Pyramid of Khufu or the Pyramid of Cheops) is the oldest and largest of the three pyramids in the Giza pyramid complex.";
$text2="this is second text example";
$params = array(
'source'=>"en",
'target'=> "sr-Latn",//serbian sr
'format'=>"text",
);
$post=implode('&',array(sprint_f('&q=%s',implode('&q=',array($text1,$text2)),urldecode(http_build_query($params)))));
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
$response = curl_exec($ch);
if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
}
curl_close($ch);
$result=json_decode($response,true);
print_r($result['data']['translations']);
Related
I am using codeigniter-3 ,inside controller i am hitting one external API it's giving 400 error but same curl request if i hit in postman it's working fine can you please help me did i miss anything ..?
CURL REQUEST in postman
curl --location --request POST 'http://armycalling.com/baligaz-api/api/userapi/login' \
--header 'x-api-key: ccccc' \
--header 'Authorization: Basic YWRtaW46YmFsaWdheiFAIyQ=' \
--header 'Content-Type: application/json' \
--header 'Cookie: ci_session=f3630b226e539f4aa079e980e23cc730609a1627' \
--data-raw '{
"email" : "dummy#gmail.com",
"password" : "dummy.srk"
}'
usercontroller.php
if(isset($_POST['login']))
{
//phpinfo();
$url = 'http://localhost/login';
$u_name = $this->input->post('username');
$password= $this->input->post('password');
$curl = curl_init($url);
$data = [
'email'=>$u_name,
'password'=>$password
];
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
'x-api-key: ccccc',
'Authorization: Basic YWRtaW46YmFsaWdheiFAIyQ=',
'Content-Type: Application/json',
'Cookie: ci_session=6dc4b8f72e2953c590ff503bd47f52ecfa158c79'
));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($curl);
$httpcode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
return print($httpcode);
curl_close($curl);
Setting this request to use a cookie session and sending the username/password in a POST request yields a successful login.
function curl( $url=NULL, $options=NULL, $headers=false ){
$vbh = fopen('php://temp', 'w+');
session_write_close();
/* Initialise curl request object - these should be OK as-is */
$curl=curl_init();
/* Define standard options */
curl_setopt( $curl, CURLOPT_URL, trim( $url ) );
curl_setopt( $curl, CURLOPT_AUTOREFERER, true );
curl_setopt( $curl, CURLOPT_FOLLOWLOCATION, true );
curl_setopt( $curl, CURLOPT_FAILONERROR, true );
curl_setopt( $curl, CURLOPT_HEADER, false );
curl_setopt( $curl, CURLINFO_HEADER_OUT, false );
curl_setopt( $curl, CURLOPT_RETURNTRANSFER, true );
curl_setopt( $curl, CURLOPT_BINARYTRANSFER, true );
curl_setopt( $curl, CURLOPT_CONNECTTIMEOUT, 20 );
curl_setopt( $curl, CURLOPT_TIMEOUT, 60 );
curl_setopt( $curl, CURLOPT_USERAGENT, 'Mozilla/5.0' );
curl_setopt( $curl, CURLOPT_MAXREDIRS, 10 );
curl_setopt( $curl, CURLOPT_ENCODING, '' );
/* enhanced debug */
curl_setopt( $curl, CURLOPT_VERBOSE, true );
curl_setopt( $curl, CURLOPT_NOPROGRESS, true );
curl_setopt( $curl, CURLOPT_STDERR, $vbh );
/* Assign runtime parameters as options to override defaults if needed. */
if( isset( $options ) && is_array( $options ) ){
foreach( $options as $param => $value ) curl_setopt( $curl, $param, $value );
}
/* send any headers with the request that are needed */
if( isset( $headers ) && is_array( $headers ) ){
curl_setopt( $curl, CURLOPT_HTTPHEADER, $headers );
}
/* Execute the request and store responses */
$res=(object)array(
'response' => curl_exec( $curl ),
'status' => curl_getinfo( $curl, CURLINFO_RESPONSE_CODE ),
'info' => (object)curl_getinfo( $curl ),
'errors' => curl_error( $curl )
);
rewind( $vbh );
$res->verbose=stream_get_contents( $vbh );
fclose( $vbh );
curl_close( $curl );
return $res;
}
# create a temporary file somewhere to store cookie data.
# Using the system temp directory should mean automatic
# deletion of these files in time.
$cookiestore=tempnam( sys_get_temp_dir(), '_cookiejar_' );
$url='http://armycalling.com/baligaz-api/api/userapi/login';
$headers=array(
'x-api-key: BALIGAZ#123',
'Authorization: Basic YWRtaW46YmFsaWdheiFAIyQ='
);
$args=array(
'email' => 'rasakumar.srk#gmail.com',
'password' => 'rasakumar.srk'
);
/*
Mark the request as a new Cookie session - subsequent requests
would have different options without CURLOPT_COOKIESESSION
*/
$options=array(
CURLOPT_COOKIESESSION => true,
CURLOPT_COOKIEFILE => $cookiestore,
CURLOPT_COOKIEJAR => $cookiestore,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $args
);
/*
Make the request with specified config options
*/
$res=curl( $url, $options, $headers );
/*
If the request is successful a 200 OK status code will be received
so we can then proceed to work with the response data.
If the request fails, using the returned info & verbose properties
of the response will show useful debug info.
*/
if( $res->status==200 ){
printf('<pre>%s</pre>',print_r( $res->response, true ) );
}
This yields:
{
"status": true,
"message": "User login successful.",
"data": {
"id": "22",
"user_id": "baligaz_595689",
"first_name": "Rasa",
"last_name": "Kumar",
"email": "rasakumar.srk#gmail.com",
"password": "529f263ebb230b4709003bb0f7457f90",
"phone": "73339190384",
"profile_img": "http://armycalling.com/baligaz-api/profile_image/baligaz_595689_app_one.png",
"role": "1",
"station_id": "HP Petrols",
"forgot_otp": "",
"created": "2022-06-24 04:47:13",
"created_by": null,
"modified": "2022-06-30 23:38:15",
"updated_by": "baligaz_595689",
"login_completed": null,
"status": "1"
}
}
I have a php script running with curl and reporting setup as such, but it stops executing on the line with the curl_exec() method, and there are no errors thrown:
$fields = array(
'auth' => array(
'cId' => 'DEADBEEF-8675309-8675309-123123-4321',
'sig' => 'Not really a signature',
'data' => array(
'field' => 'pat',
'value' => '12',
'id1' => 'lasagna',
'id2' => 'peperoni'
)
),
'item1' => 'QPFMgH1TnCTLrylGeNs8yzYVVXxUgR0RHwj9jNwgXJJEfxODdoOKDOJLv66CSU5XKRfu4KYtDJB5rAmngxNrRDFpWU69oHMTlZoHAewuy3ft',
'item2' => 'gMiGdw==',
'tokenList' => array(
"token", "list"
)
);
$postfields = json_encode($fields);
error_reporting(E_ALL);
ini_set('display_errors', true);
$curl = curl_init('http://localhost:8080/endpoint');
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $postFields);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
//curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
//$result = curl_exec($curl);
echo "before curl_exec" . "\n\n";
$response = json_decode(curl_exec($curl));
echo "after curl_exec" . "\n\n";
print_r($response);
EDIT: forgot to include the line with json_encode for the $fields variable to pass to curl_setopt();
There are a couple of issues with your code:
you put the "post" data into $fields but then...
curl_setopt($curl, CURLOPT_POSTFIELDS, $postFields);
...you're passing $postFields to curl.
Assuming this is a typo, fixing with
curl_setopt($curl, CURLOPT_POSTFIELDS, $fields);
won't work.
If the parameter used for CURLOPT_POSTFIELDS is an array it must be an associative array where keys and values are strings (or values that can be casted/converted to strings).
In your case $fields is an array where some values are arrays. That won't work (and raises a warning "array to string conversion").
You set an header that specifies that the data sent with the request is in JSON format
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
If you want to send the data into $fields as JSON with a POST request you can do it this way:
$fields = array( /* ... */ );
$json_fields = json_encode( $fields );
$curl = curl_init( 'http://localhost:8080/endpoint' );
curl_setopt( $curl, CURLOPT_POST, true );
curl_setopt( $curl, CURLOPT_CUSTOMREQUEST, "POST" );
curl_setopt( $curl, CURLOPT_POSTFIELDS, $json_fields );
curl_setopt( $curl, CURLOPT_RETURNTRANSFER, true );
curl_setopt( $curl, CURLOPT_HTTPHEADER, [ 'Content-Type: application/json',
'Content-Length: ' . strlen($json_fields) ] );
curl_setopt( $curl, CURLOPT_FOLLOWLOCATION, true );
$response = curl_exec( $curl );
$response_data = json_decode( $response );
If still something needs to be fixed proceed with debugging by steps to isolate the problem:
// 1 - Check curl error
$errnum = curl_errno( $curl );
$errstr = curl_strerror( $errnum );
echo "Error: $errnum - $errstr\n";
// 2 - Check http status code of the response
$status = curl_getinfo( $curl, CURLINFO_HTTP_CODE );
echo "Status: $status\n";
// 3 - Inspect the response before coverting to JSON
echo "Response:\n";
var_export( $response );
echo "\n";
I have a simple daily PHP notification to a discord webhook. It was working for almost a year, but it's now responding me an error:
{"message": "Cannot send an empty message", "code": 50006}
$content is created before and filled, and it's not empty.
I replaced the real username and avatar link here.
$hookObject = json_encode([
"type" => "rich",
"content" => "**Rotation today**\n\n".$content,
"username" => "avatar",
"avatar_url" => "link to avatar",
"tts" => false,
], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE );
$ch = curl_init();
curl_setopt_array( $ch, [
CURLOPT_URL => $url,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $hookObject,
CURLOPT_HTTPHEADER => [
"Length" => strlen( $hookObject ),
"Content-Type" => "application/json"
]
]);
$response = curl_exec( $ch );
curl_close( $ch );
Does anyone know what might be the problem now?
I also got this error last day.
I found this code and it works:
//===========================================
// Create new webhook in your Discord channel settings and copy&paste URL
//===========================================
$webhookurl = "YOUR_WEBHOOK_URL";
//===========================================
// Compose message. You can use Markdown
// Message Formatting -- https://discordapp.com/developers/docs/reference#message- formatting
//===========================================
$msg = "Test **message** ";
$json_data = array ('content'=>"$msg");
$make_json = json_encode($json_data);
$ch = curl_init( $webhookurl );
curl_setopt( $ch, CURLOPT_HTTPHEADER, array('Content-type: application/json'));
curl_setopt( $ch, CURLOPT_POST, 1);
curl_setopt( $ch, CURLOPT_POSTFIELDS, $make_json);
curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt( $ch, CURLOPT_HEADER, 0);
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec( $ch );
I am trying to execute CURL via cron job, hosting is GoDaddy's shared linux hosting. When I execute the script from browser URL then it works, it is not working via cron job.
Following error:
curl: (35) error:14077410:SSL routines:SSL23_GET_SERVER_HELLO:sslv3 alert handshake failure
Please notice: GET request is working fine, it is only issue with POST request, I tried different solutions, but question is that why it is working for GET and not only POST. When I execute script via browser URL it works but it is only issue via cron job.
Following is my code for CURL
$postData = array(
"email" => "login",
"password" => "password",
);
$headers = array(
"Content-Type: application/json"
);
$ch=curl_init();
curl_setopt($ch,CURLOPT_URL,'https://reqres.in/api/login');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($postData));
curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,2);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt ($ch, CURLOPT_HTTPPROXYTUNNEL, TRUE);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
$result = curl_exec ($ch);
if (empty($result)){
$return = "<hr><br>\n";
$return .= 'Errors: ' . curl_errno($ch) . ' ' . curl_error($ch) . '<br><br>';
$return .= "<hr><br>\n";
}
else{
$return = $result;
}
print $result;
curl_close ($ch);
Please suggest.
When dealing with curl requests to SSL enabled endpoints you'll have much greater success if the curl request includes options specifically geared towards ssl connections. The simple function below uses cacert.pem and other ssl specific options
function curl( $url=NULL, $options=NULL ){
$cacert='c:/wwwroot/cacert.pem';
$vbh = fopen('php://temp', 'w+');
$res=array(
'response' => NULL,
'info' => array( 'http_code' => 400 ),
'headers' => NULL,
'errors' => NULL
);
if( is_null( $url ) ) return (object)$res;
session_write_close();
/* Initialise curl request object */
$curl=curl_init();
if( parse_url( $url,PHP_URL_SCHEME )=='https' ){
curl_setopt( $curl, CURLOPT_SSL_VERIFYPEER, true );
curl_setopt( $curl, CURLOPT_SSL_VERIFYHOST, 2 );
curl_setopt( $curl, CURLOPT_CAINFO, $cacert );
}
/* Define standard options */
curl_setopt( $curl, CURLOPT_URL,trim( $url ) );
curl_setopt( $curl, CURLOPT_AUTOREFERER, true );
curl_setopt( $curl, CURLOPT_FOLLOWLOCATION, true );
curl_setopt( $curl, CURLOPT_FAILONERROR, true );
curl_setopt( $curl, CURLOPT_HEADER, false );
curl_setopt( $curl, CURLINFO_HEADER_OUT, false );
curl_setopt( $curl, CURLOPT_RETURNTRANSFER, true );
curl_setopt( $curl, CURLOPT_BINARYTRANSFER, true );
curl_setopt( $curl, CURLOPT_CONNECTTIMEOUT, 20 );
curl_setopt( $curl, CURLOPT_TIMEOUT, 60 );
curl_setopt( $curl, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36' );
curl_setopt( $curl, CURLOPT_MAXREDIRS, 10 );
curl_setopt( $curl, CURLOPT_ENCODING, '' );
curl_setopt( $curl, CURLOPT_VERBOSE, true );
curl_setopt( $curl, CURLOPT_NOPROGRESS, true );
curl_setopt( $curl, CURLOPT_STDERR, $vbh );
/* Assign runtime parameters as options */
if( isset( $options ) && is_array( $options ) ){
foreach( $options as $param => $value ) curl_setopt( $curl, $param, $value );
}
/* Execute the request and store responses */
$res=(object)array(
'response' => curl_exec( $curl ),
'info' => (object)curl_getinfo( $curl ),
'errors' => curl_error( $curl )
);
rewind( $vbh );
$res->verbose=stream_get_contents( $vbh );
fclose( $vbh );
curl_close( $curl );
return $res;
}
/* configure the request */
$data = array(
'email' => 'peter#klaven',
'password' => 'cityslicka'
);
/* the target endpoint */
$url='https://reqres.in/api/login';
$config=array(
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => json_encode( $data ),
CURLOPT_HTTPHEADER => array('Content-Type: application/json')
);
/* make the request */
$results=curl( $url, $config );
if( $results->info->http_code==200 ){
printf('<pre>%s</pre>',print_r( $results, true ));
}
Some info from the response object - notably verbose details ~ the full response includes the token ~ {"token":"QpwL5tke4Pnpja7X"} which suggests success!
* TCP_NODELAY set
* Connected to reqres.in (104.27.134.11) port 443 (#0)
* ALPN, offering http/1.1
* successfully set certificate verify locations:
CAfile: c:/wwwroot/cacert.pem
CApath: none
* SSL connection using TLSv1.2 / ECDHE-ECDSA-CHACHA20-POLY1305
* ALPN, server accepted to use http/1.1
* Server certificate:
* subject: OU=Domain Control Validated; OU=PositiveSSL Multi-Domain; CN=sni96286.cloudflaressl.com
* start date: Jan 23 00:00:00 2019 GMT
* expire date: Aug 1 23:59:59 2019 GMT
* subjectAltName: host "reqres.in" matched cert's "reqres.in"
* issuer: C=GB; ST=Greater Manchester; L=Salford; O=COMODO CA Limited; CN=COMODO ECC Domain Validation Secure Server CA 2
* SSL certificate verify ok.
We're posting from a wordpress form to an API.
Everything we have read so far seems to indicate that this should work.
All CURL config seems to be there and when passing the JSON through Postman, we do get a response.
BUT we do not get a response through this CURL implementation.
Please advise.
add_action( 'wpcf7_before_send_mail', 'CF7_pre_send' );
function CF7_pre_send($cf7) {
$data = array(
"user" => array(
"first_name" => "Some",
"surname" => "Guy",
"mobile_number" => "0724717299",
"email" => "someguy#a.com",
"skype_username" => "john.doe",
"twitter_handle" => "test.john",
"linkedin" => "John Matthews Doe",
"slack_username" => "johndoe",
"receive_marketing_info" => true,
"accept_terms_and_conditions" => true,
"green_member" => false,
"industry" => "Industry 1",
"nda" => true,
"relationship_type" => "Partner",
"communication_type" => "Newsletter"
),
"company" => array(
"company_name" => "Test Company",
"website_url" => "www.test.com",
"contact_number" => "0211111111",
"email" => "test#test.com",
"address_line_1" => "450 Test Strees. Testville",
"story" => "We specialize in test of testing",
"service_type" => "Fintech"
)
);
$data_string = json_encode($data);
$username = 'USERNAME GOES HERE';
$password = 'PASSWORD GOES HERE';
$ch = curl_init("API URL GOES HERE");
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_USERPWD, $username . ":" . $password);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
file_put_contents("cf7outputtest.txt", $result);
return $result;
}
Try this:
$ch = curl_init();
curl_setopt( $ch, CURLOPT_URL, "url-goes-here");
curl_setopt( $ch, CURLOPT_POST, true);
curl_setopt( $ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt( $ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
curl_setopt( $ch, CURLOPT_HEADER, 1);
curl_setopt( $ch, CURLOPT_USERPWD, $username . ":" . $password);
curl_setopt( $ch, CURLOPT_SSL_VERIFYHOST, FALSE );
curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, FALSE );
$result = curl_exec($ch) ;
if( curl_error( $ch ) )
{
echo "Error occurred " . curl_error( $ch );
}
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ( $httpCode != 200 )
{
echo "Return code is {$httpCode} \n"
.curl_error($ch);
}
else {
echo "<pre>".htmlspecialchars( $result )."</pre>";
}
var_dump($result);
NJOY