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.
Related
I am trying to connect to Moz API V2, using HTTP Request by file get contents function but I am new using this... could you guys help me?
Example HTPP Request in their doc:
POST /v2/url_metrics
Host: lsapi.seomoz.com
Content-Length: [length of request payload in bytes]
User-Agent: [user agent string]
Authorization: Basic [credentials]
{
"targets": ["facebook.com"]
}
Here's the code I am trying:
$url = 'https://lsapi.seomoz.com/v2/url_metrics';
$domains = json_encode(['targets' => 'moz.com']);
$opts = ['http' =>
[
'method' => 'POST',
'header' => 'Content-Type: application/x-www-form-urlencoded\r\n'.
("Authorization: Basic " . base64_encode("mozscape-XXXXX:XXXXX")),
'content-length' => strlen($domains),
'user-agent' => $_SERVER['HTTP_USER_AGENT'],
'content' => $domains,
]
];
$context = stream_context_create($opts);
$result = file_get_contents($url, false, $context);
print_r($result);
Here is the link of documentation : https://moz.com/help/links-api/making-calls/url-metrics
I got nothing when I print result, Probably I am missing some parameter... :(
Thank you for your time :)
Most probably you're simply making an invalid request. You declare the content type as application/x-www-form-urlencoded yet sending the data as application/json.
You also need basic error handling (eg. in case of invalid credentials).
I'd write it this way:
$url = 'https://lsapi.seomoz.com/v2/url_metrics';
$content = json_encode(['targets' => 'moz.com']);
$opts = ['http' => [
'method' => 'POST',
'content' => $content,
'header' => implode("\r\n", [
'Authorization: Basic ' . base64_encode("mozscape-XXXXX:XXXXX"),
'Content-Type: application/json',
'Content-Length: ' . strlen($content),
'User-Agent: ' . $_SERVER['HTTP_USER_AGENT'],
]),
]];
$stream = fopen($url, 'r', false, stream_context_create($opts));
if (!is_resource($stream)) {
die('The call failed');
}
// header information as well as meta data
// about the stream
var_dump(stream_get_meta_data($stream));
// actual data
var_dump(stream_get_contents($stream));
// free resources
fclose($stream);
To be honest, the sockets & fopen is pretty low level. It would be better for you to use an abstraction layer instead: like Guzzle.
Sorry for late solution I forgot to post here before...
Maybe someone is looking for how to use moz API V2 with PHP...
$username='Access ID';
$password='Secret Key';
$URL='https://lsapi.seomoz.com/v2/url_metrics';
$payload = json_encode(array("targets" => ["moz.com"]));
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$URL);
curl_setopt($ch, CURLOPT_TIMEOUT, 30); //timeout after 30 seconds
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($ch, CURLOPT_USERPWD, "$username:$password");
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
$result=curl_exec ($ch);
$status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE); //get status code
curl_close ($ch);
print_r(json_decode($result, true));
I am trying to use Thycotic PAM API. According to their documentation, The following is a sample HTTP POST request. The placeholders shown need to be replaced with actual values.
POST /SecretServer/webservices/SSWebservice.asmx/GetUser HTTP/1.1
Host: 192.168.3.242
Content-Type: application/x-www-form-urlencoded
Content-Length: length
token=string&userId=string
I can get token string and user ID from the app. With this data, following is the PHP code I am trying
$url = 'https://192.168.3.242/SecretServer/webservices/SSWebservice.asmx/GetUser';
$data = array(
'token' => 'token_string',
'userId' => 8
);
// use key 'http' even if you send the request to https://...
$options = array(
'http' => array(
'header' => "Content-type: application/x-www-form-urlencoded\r\n",
'method' => 'POST',
'content' => http_build_query($data)
)
);
$context = stream_context_create($options);
$result = json_decode(file_get_contents($url, false, $context));
if ($result === FALSE) { /* Handle error */ }
var_dump($result);
I also tried this way:
function curl_get_contents($url)
{
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
$url = 'https://192.168.3.242/SecretServer/webservices/SSWebservice.asmx/GetUser?token=token_string&userId=8 HTTP/1.1';
$json = json_decode(curl_get_contents($url));
var_dump($json);
Both of them are returning nothing. Any suggestion is much appreciated.
curl_setopt($ch ,CURLOPT_POST, 1);
$headers[] = 'Content-Type: application/x-www-form-urlencoded';
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch ,CURLOPT_POSTFIELDS, "token=string&userId=string");
you must use this parameters
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);
I'm trying to upload a config file via PHP's CURL to the Cisco APIC-EM via POST but am receiving an unexpected error:
//File Upload
echo "<b>File Upload:</b><br>";
$namespace = "config";
$data = array(
"version" => "",
"response" =>
array(
"nameSpace" => $namespace,
"encrypted" => false,
"id" => "",
"md5Checksum" => "",
"sha1Checksum" => "",
"fileFormat" => "",
"fileSize" => "",
"downloadPath" => "http://hama0942.global.bdfgroup.net/network/net_config/bdfbrsao00000000rt02.txt",
"name" => "bdfbrsao00000000rt02.txt",
"attributeInfo" => "object"
)
);
$data = json_encode($data);
//For Debugging only - Request
echo "<br>Request:<br>";
echo '<pre>';
print_r($data);
echo '</pre>';
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_URL, "https://hams1484.global.bdfgroup.net/api/v1/file/".$namespace);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: multipart/form- data", "X-Auth-Token: ".$serviceTicket));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, array($data));
curl_setopt($ch, CURLINFO_HEADER_OUT, true);
$response = curl_exec($ch);
echo "<br><b>Request-Header: </b>".curl_getinfo($ch, CURLINFO_HEADER_OUT )."<br><br>";
//For Output Debugging only - Response
echo "<br>Response:<br>";
echo '<pre>';
print_r(json_decode($response));
echo '</pre>';
curl_close($ch);
echo "<br><hr>";
This is the result:
File Upload:
Request:
{"version":"","response":{"nameSpace":"config","encrypted":false,"id":"","md5Checksum":"","sha1Checksum":"","fileFormat":"","fileSize":"","downloadPath":"http:\/\/hama0942.global.bdfgroup.net\/network\/net_config\/bdfbrsao00000000rt02.txt","name":"bdfbrsao00000000rt02.txt","attributeInfo":"object"}}
Request-Header: POST /api/v1/file/config HTTP/1.1 Host: hams1484.global.bdfgroup.net Accept: */* X-Auth-Token: ST-1111-OUiNBLtgALg2ufcwFrh5-cas Content-Length: 436 Expect: 100-continue Content-Type: multipart/form-data; boundary=------------------------5e86cb7113449960
Response:
stdClass Object
(
[response] => stdClass Object
(
[errorCode] => 7062
[message] => Unexpected error
[detail] => Non valid file object
)
[version] => 1.0
)
I'm afraid that there is something wrong with the CURL settings but I'm not sure. Has someone an idea what is wrong here? I'm using PHP7.
Thanks.
I have been struggling with this for a long time now and finally found a solution for this.
1 : File for upload has to be local file on the server your are CURL'ing from.
2 : $file = realpath("filenameOnServer");
3 : $config = new CURLfile($file);
4 : $array = array("fileUpload" => $config); $array = json_encode($array);
5 : curl_setopt($ch, CURLOPT_HTTPHEADER, array( 'Content-Type: multipart/form-data; charset=utf-8;',
'X-Auth-Token: ' . $token,
));
6 : send the array as POST variable in the CURL. Nothing else is needed
Im trying to get data from api HERE via POST request to my application and it does return error in error.log.
PHP message: PHP Warning: file_get_contents('url_here') failed to open stream: HTTP request failed! HTTP/1.1 406 Not Acceptable
Here is my code:
$url = 'http://inventory.api.eciaauthorized.com/api/Search/Query';
$fields = array(
'CompanyID' => 'company_id',
'APIKey' => 'api_key_here',
'Queries' => array(
'SearchToken' => 'query_string_here',
),
'InStockOnly' => true,
'ExactMatch' => true,
'IsCrawler' => true
);
$postdata = http_build_query($fields);
$opts = array('http' =>
array(
'method' => 'POST',
'header' => 'Content-type: application/json ' . ' Accept: application/json',
'content' => $postdata
)
);
$context = stream_context_create($opts);
$result = file_get_contents($url, false, $context);
var_dump($result);
When I var_dump the result it returns:
false
What I am missing here? Please help. Thanks.
From This Question who have answer It throws the same error.
$result = fopen($url, "r",true, $context);
Some suggest to user CURL so I do it this is my code:
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Accept: application/json',
'Content-Type: application/json'
));
curl_setopt($ch, CURLINFO_HEADER_OUT, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
curl_setopt($ch, CURLOPT_VERBOSE, true);
//execute post
$result['body'] = curl_exec($ch);
$result['headers'] = curl_getinfo($ch);
if(curl_error($ch))
{echo 'error:' . curl_error($ch);}
var_dump($ch);
curl_close($ch);
When I var_dump the $result it returns
true
and there are no data included and it throws error on
"HTTP/1.1 406 Not Acceptable Cache-Control: no-cache Pragma: no-cache Expires: -1 Server: Microsoft-IIS/8.0 X-AspNet-Version: 4.0.30319 X-Powered-By: ASP.NET Date: Wed, 24 Aug 2016 06:43:54 GMT Content-Length: 0
Ive done my research on that error and see that the headers are incomplete but I follow properly the API documentation. Please Help. Thanks.
These are on the documentation:
The ECIA Inventory API receives search requests via HTTP POST. It supports both JSON and XML requests and responses. Please indicate with your requests which format you would like to use by including the "Content-Type" and "Accept" headers set to either "application/json" or "application/xml".
The format for the body of the requests and responses is defined
below. The url for the API is:
https://inventory.api.eciaauthorized.com/api/Search/Query