Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I like to post a JSON object with curl. All I have is that piece of code:
curl -X POST \
-H "Accept: application/json" \
-H "X-Access-Token: ###secureToken###" \
-H "Cache-Control: no-cache" \
-d '{
"frames": [
{
"index": 0,
"text": "SUCCESS",
"icon": null
}
]
}' \
https://developer.lametric.com/api/V1/dev/widget/update/com.lametric.###appid###
What to do now exactly, to make this happen in PHP? Could you please post an example?
// init curl
$handle = curl_init();
// set options/parameters
curl_setopt( $handle, CURLOPT_URL, 'https://developer.lametric.c...');
curl_setopt( $handle, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt( $handle, CURLOPT_POSTFIELDS, 'the-json-encoded-data-here' );
curl_setopt( $handle, CURLOPT_RETURNTRANSFER, true ); // you want to get the response
// set headers
curl_setopt( $handle, CURLOPT_HTTPHEADER, array( 'Accept: application/json',
'....' ) );
// execute the request and get the response
$response = curl_exec( $handle );
// get the status too
$status = curl_getinfo( $handle, CURLINFO_HTTP_CODE );
// release resources
curl_close( $handle );
Just an example/introduction.
You initialize php's curl.
Setup all the parameters.
Send the request.
I won't write all the code for you.
PHP Reference is clear (and have examples too)
http://php.net/manual/en/book.curl.php
SO have examples too:
PHP + curl, HTTP POST sample code?
Or without curl, very generic pattern that I use to keep dependencies down.
<?php
$reqBody = array(
'frames' => array(
'index' => 0,
'text' => "SUCCESS",
'icon' => null
)
);
$bodyString = json_encode($reqBody);
$access_token = "###secureToken###";
$context_options = array (
'http' => array (
'method' => 'POST',
'header' => "Accept: application/json\r\nX-Access-Token: " . $access_token . "\r\nCache-Control: no-cache\r\nContent-Length: " . strlen($bodyString) . "\r\n",
'content' => $bodyString
)
);
$context_for_post = stream_context_create($context_options);
$response = file_get_contents($"https://developer.lametric.com/api/V1/dev/widget/update/com.lametric.###appid###", FALSE, $context_for_post);
// Check for errors
if(!$response){
die("<h2>ERROR</h2>");
}
// Decode the response
$responseData = json_decode($response, TRUE);
// some examples of parsing response json ...
if ($responseData['message'] != null) {
}
$this->sessionToken = $responseData['message']['data']['results']['token'];
if($this->sessionToken === FALSE) {
die('Failed to Parse Response');
}
?>
If the web server doesn't seem to like your post, it might be expecting form-data type of POST, so set up the body and headers like this:
$bodyString = "------WebKitFormBoundaryiAsuvpNuslAE3Kqx\r\nContent-Disposition: form-data; name=\"json\"\r\n\r\n" .
json_encode($reqBody) .
"\r\n------WebKitFormBoundaryiAsuvpNuslAE3Kqx--\r\n";
$access_token = "###secureToken###";
$context_options = array (
'http' => array (
'method' => 'POST',
'header' => "X-Access-Token: " . $access_token . "\r\nCache-Control: no-cache\r\nAccept: application/json\r\nContent-Type: multipart/form-data; boundary=----WebKitFormBoundaryiAsuvpNuslAE3Kqx\r\n" . "Content-Length: " . strlen($bodyString) . "\r\n",
'content' => $bodyString
)
);
Related
I have this json data:
{
userID: 'a7664093-502e-4d2b-bf30-25a2b26d6021',
itemKind: 0,
value: 1,
description: 'Saude',
itemID: '03e76d0a-8bab-11e0-8250-000c29b481aa'
}
and I need to post into json url:
http://domain/OnLeagueRest/resources/onleague/Account/CreditAccount
using php how can I send this post request?
You can use CURL for this purpose see the example code:
$url = "your url";
$content = json_encode("your data to be sent");
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER,
array("Content-type: application/json"));
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $content);
$json_response = curl_exec($curl);
$status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
if ( $status != 201 ) {
die("Error: call to URL $url failed with status $status, response $json_response, curl_error " . curl_error($curl) . ", curl_errno " . curl_errno($curl));
}
curl_close($curl);
$response = json_decode($json_response, true);
Without using any external dependency or library:
$options = array(
'http' => array(
'method' => 'POST',
'content' => json_encode( $data ),
'header'=> "Content-Type: application/json\r\n" .
"Accept: application/json\r\n"
)
);
$context = stream_context_create( $options );
$result = file_get_contents( $url, false, $context );
$response = json_decode( $result );
$response is an object. Properties can be accessed as usual, e.g. $response->...
where $data is the array contaning your data:
$data = array(
'userID' => 'a7664093-502e-4d2b-bf30-25a2b26d6021',
'itemKind' => 0,
'value' => 1,
'description' => 'Boa saudaÁ„o.',
'itemID' => '03e76d0a-8bab-11e0-8250-000c29b481aa'
);
Warning: this won't work if the allow_url_fopen setting is set to Off in the php.ini.
If you're developing for WordPress, consider using the provided APIs: https://developer.wordpress.org/plugins/http-api/
Beware that file_get_contents solution doesn't close the connection as it should when a server returns Connection: close in the HTTP header.
CURL solution, on the other hand, terminates the connection so the PHP script is not blocked by waiting for a response.
use CURL luke :) seriously, thats one of the best ways to do it AND you get the response.
we're using GLPI API we need to create a ticket linked with documents .
The only curl part that i can't translate it's the document's upload .
With Curl (working) :
curl -i -X POST "http://glpitest/glpi/apirest.php/Document" -H "Content-Type: multipart/form-data" -H "Session-Token:sessiontoken"-H "App-Token:apptoken" -F "uploadManifest={\"input\": {\"name\": \"Uploaded document\", \"_filename\" : \"test.txt\"}};type=application/json" -F "filename[0]=#test.txt" "http://glpitest/glpi/apirest.php/Document"
But i can't translate this is in PHP CURL i tried something like this :
$headers = array(
'Authorization: Basic ' . $_SESSION['encodelogin'],
'App-Token:' . $_SESSION['app_token'], // <---
'Session-Token:' . $_SESSION['session_token'],
'Http_Accept: application/json',
);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_exec($ch);
echo $url = $_SESSION['api_url'] . "/Document";
$cfile = new CURLFile('testpj.txt', 'text/plain', 'test_name');
//$manifest = 'uploadManifest={"input": {"name": "test", "_filename" : "testpj.txt"}};type=application/json filename[0]=#'+$cfile;
$post = ["{\"input\": {\"name\": \"test\", \"_filename\" : \"testpj.txt\"}};type=application/json}", #"C:\\xampp\htdocs\glpi"];
print_r($post);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($ch);
the example in the api:
$ curl -X POST \
-H 'Content-Type: multipart/form-data' \
-H "Session-Token: 83af7e620c83a50a18d3eac2f6ed05a3ca0bea62" \
-H "App-Token: f7g3csp8mgatg5ebc5elnazakw20i9fyev1qopya7" \
-F 'uploadManifest={"input": {"name": "Uploaded document", "_filename" : ["file.txt"]}};type=application/json' \
-F 'filename[0]=#file.txt' \
'http://path/to/glpi/apirest.php/Document/'
< 201 OK
< Location: http://path/to/glpi/api/Document/1
< {"id": 1, "message": "Document move succeeded.", "upload_result": {...}}
update : I tried #hanshenrik but i have an error .
["ERROR_JSON_PAYLOAD_INVALID","JSON payload seems not valid"]
in the api.class.php :
if (strpos($content_type, "application/json") !== false) {
if ($body_params = json_decode($body)) {
foreach ($body_params as $param_name => $param_value) {
$parameters[$param_name] = $param_value;
}
} else if (strlen($body) > 0) {
$this->returnError("JSON payload seems not valid", 400, "ERROR_JSON_PAYLOAD_INVALID",
false);
}
$this->format = "json";
} else if (strpos($content_type, "multipart/form-data") !== false) {
if (count($_FILES) <= 0) {
// likely uploaded files is too big so $_REQUEST will be empty also.
// see http://us.php.net/manual/en/ini.core.php#ini.post-max-size
$this->returnError("The file seems too big!".print_r($_FILES), 400,
"ERROR_UPLOAD_FILE_TOO_BIG_POST_MAX_SIZE", false);
}
// with this content_type, php://input is empty... (see http://php.net/manual/en/wrappers.php.php)
if (!$uploadManifest = json_decode(stripcslashes($_REQUEST['uploadManifest']))) {
//print_r($_FILES);
$this->returnError("JSON payload seems not valid", 400, "ERROR_JSON_PAYLOAD_INVALID",
false);
}
I have no uploadManifest in $_REQUEST and if i put the the filename[0]file i have the curl error 26 (can't read file) .
Thank you
translating
-F "uploadManifest={\"input\": {\"name\": \"Uploaded document\", \"_filename\" : \"test.txt\"}};type=application/json"
is tricky because php doesn't really have native support for adding Content-Type headers (or any headers really) to members of a multipart request, with the only *exception* (known to me) being CURLFile's "Content-Type" and Content-Disposition's "filename" header... with that in mind, you can work around this by putting your data in a file and creating a CURLFile() around that dummy file, but it's.. tricky and stupid-looking (because PHP's curl api wrappers lacks proper support for it)
with the CURLFile workaround, it would look something like:
<?php
declare(strict_types = 1);
$ch = curl_init();
$stupid_workaround_file1h = tmpfile();
$stupid_workaround_file1f = stream_get_meta_data($stupid_workaround_file1h)['uri'];
fwrite($stupid_workaround_file1h, json_encode(array(
'input' => array(
'name' => 'Uploaded document',
'_filename' => 'test.txt'
)
)));
curl_setopt_array($ch, array(
CURLOPT_URL => "http://glpitest/glpi/apirest.php/Document",
CURLOPT_POST => 1,
CURLOPT_HEADER => 1,
CURLOPT_HTTPHEADER => array(
"Session-Token:sessiontoken",
"App-Token:apptoken"
),
CURLOPT_POSTFIELDS => array(
'uploadManifest' => new CURLFile($stupid_workaround_file1f, 'application/json', ' '), // https://bugs.php.net/bug.php?id=79004
'filename[0]' => new CURLFile('test.txt', 'text/plain')
)
));
curl_exec($ch);
curl_close($ch);
fclose($stupid_workaround_file1h);
Thanks for the Help .
$document can be a $_FILES['whatever'] post .
Works on GLPI api .
<?php
declare (strict_types = 1);
session_start();
$document = array('name' => 'document', 'path' => 'C:\xampp\htdocs\glpi\document.pdf', 'type' => 'txt', 'name_ext' => 'document.pdf');
$url = $_SESSION['api_url'] . "/Document";
$uploadManifest = json_encode(array(
'input' => array(
'name' => $document['name'],
'_filename' => $document['name_ext'],
),
));
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($ch, CURLINFO_HEADER_OUT, 1);
curl_setopt_array($ch, array(
CURLOPT_URL => $url,
CURLOPT_POST => 1,
CURLOPT_HEADER => 1,
CURLOPT_HTTPHEADER => array(
'Content-Type: multipart/form-data',
'Authorization: Basic ' . $_SESSION['encodelogin'],
'App-Token:' . $_SESSION['app_token'], // <---
'Session-Token:' . $_SESSION['session_token'],
),
CURLOPT_POSTFIELDS => array(
'uploadManifest' => $uploadManifest,
'filename[0]' => new CURLFile($document['path'], $document['type'], $document['name_ext']),
),
));
print_r($_REQUEST);
echo $result = curl_exec($ch);
echo "erreur n° " . curl_errno($ch);
$header_info = curl_getinfo($ch, CURLINFO_HEADER_OUT) . "/";
print_r($header_info);
if ($result === false) {
$result = curl_error($ch);
echo stripslashes($result);
}
curl_close($ch);
I am going to convert some file using php and send it as a part of HTTP POST request.
There is part of my code:
$context = stream_context_create(array(
'http' => array(
'method' => 'POST',
'header' => "Content-type: " . $this->contentType."",
'content' => "file=".$file
)
));
$data = file_get_contents($this->url, false, $context);
Does variable $file have to be byte representation of the file which I want to send?
And is that correct way to send file in php without using form? Have you got any clues?
Also what is the way to convert file to byte representation using PHP?
You may find it much easier to use CURL, for example:
function curlPost($url,$file) {
$ch = curl_init();
if (!is_resource($ch)) return false;
curl_setopt( $ch , CURLOPT_SSL_VERIFYPEER , 0 );
curl_setopt( $ch , CURLOPT_FOLLOWLOCATION , 0 );
curl_setopt( $ch , CURLOPT_URL , $url );
curl_setopt( $ch , CURLOPT_POST , 1 );
curl_setopt( $ch , CURLOPT_POSTFIELDS , '#' . $file );
curl_setopt( $ch , CURLOPT_RETURNTRANSFER , 1 );
curl_setopt( $ch , CURLOPT_VERBOSE , 0 );
$response = curl_exec($ch);
curl_close($ch);
return $response;
}
Where $url is where you want to post to, and $file is the path to the file you want to send.
Oddly enough I just wrote an article and illustrated this same scenario. (phpmaster.com/5-inspiring-and-useful-php-snippets). But to get you started, here's code that should work:
<?php
$context = stream_context_create(array(
"http" => array(
"method" => "POST",
"header" => "Content-Type: multipart/form-data; boundary=--foo\r\n",
"content" => "--foo\r\n"
. "Content-Disposition: form-data; name=\"myFile\"; filename=\"image.jpg\"\r\n"
. "Content-Type: image/jpeg\r\n\r\n"
. file_get_contents("image.jpg") . "\r\n"
. "--foo--"
)
));
$html = file_get_contents("http://example.com/upload.php", false, $context);
In situations like these it helps to make a mock web form and run it through Firefox with firebug enabled or something, and then inspect the request that was sent. From there you can deduce the important things to include.
file_get_contents not working for fetching fata from facebook using batch requests.Am using the code below:
$url='https://graph.facebook.com/?batch=[{ "method": "POST", "relative_url":"method/fql.query?query=SELECT+first_name+from+user+where+uid=12345678"}]& access_token=xxxxxxx&method=post';
echo $post = file_get_contents($url,true);
it produces
Warning: file_get_contents(graph.facebook.com/?batch=[{ "method": "POST", "relative_url": "method/fql.query?query=SELECT+first_name+from+user+where+uid=12345"}]&access_to ken=xxxx&method=post): failed to open stream: HTTP request failed! HTTP/1.1 400 Bad Request in /home/user/workspace/fslo/test.php on line 9
I would say the most likely answer to this is that you need to pass the URL values through urlencode() - particularly the JSON string.
Also, you should be POSTing the data.
Try this code:
NB: I presume you are building the URL from several variables. If you edit the question with your actual code, I will provide a solution using that code
<?php
$baseURL = 'https://graph.facebook.com/';
$requestFields = array (
'batch' => '[{"method":"POST","relative_url":"method/fql.query?query=SELECT+first_name+from+user+where+uid=12345678"}]',
'access_token' => 'whatever'
);
$requestBody = http_build_query($requestFields);
$opts = array(
'http'=>array(
'method' => 'POST',
'header' => "Content-Type: application/x-www-form-urlencoded\r\n"
. "Content-Length: ".strlen($requestBody)."\r\n"
. "Connection: close\r\n",
'content' => $requestBody
)
);
$context = stream_context_create($opts);
$result = file_get_contents($baseURL, FALSE, $context);
A "more standard" way to do this these days is with cURL:
<?php
$baseURL = 'https://graph.facebook.com/';
$requestFields = array (
'batch' => '[{"method":"POST","relative_url":"method/fql.query?query=SELECT+first_name+from+user+where+uid=12345678"}]',
'access_token' => 'whatever'
);
$requestBody = http_build_query($requestFields);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $baseURL);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $requestBody);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/x-www-form-urlencoded',
'Content-Length: '.strlen($requestBody),
'Connection: close'
));
$post = curl_exec($ch);
I have this json data:
{
userID: 'a7664093-502e-4d2b-bf30-25a2b26d6021',
itemKind: 0,
value: 1,
description: 'Saude',
itemID: '03e76d0a-8bab-11e0-8250-000c29b481aa'
}
and I need to post into json url:
http://domain/OnLeagueRest/resources/onleague/Account/CreditAccount
using php how can I send this post request?
You can use CURL for this purpose see the example code:
$url = "your url";
$content = json_encode("your data to be sent");
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER,
array("Content-type: application/json"));
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $content);
$json_response = curl_exec($curl);
$status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
if ( $status != 201 ) {
die("Error: call to URL $url failed with status $status, response $json_response, curl_error " . curl_error($curl) . ", curl_errno " . curl_errno($curl));
}
curl_close($curl);
$response = json_decode($json_response, true);
Without using any external dependency or library:
$options = array(
'http' => array(
'method' => 'POST',
'content' => json_encode( $data ),
'header'=> "Content-Type: application/json\r\n" .
"Accept: application/json\r\n"
)
);
$context = stream_context_create( $options );
$result = file_get_contents( $url, false, $context );
$response = json_decode( $result );
$response is an object. Properties can be accessed as usual, e.g. $response->...
where $data is the array contaning your data:
$data = array(
'userID' => 'a7664093-502e-4d2b-bf30-25a2b26d6021',
'itemKind' => 0,
'value' => 1,
'description' => 'Boa saudaÁ„o.',
'itemID' => '03e76d0a-8bab-11e0-8250-000c29b481aa'
);
Warning: this won't work if the allow_url_fopen setting is set to Off in the php.ini.
If you're developing for WordPress, consider using the provided APIs: https://developer.wordpress.org/plugins/http-api/
Beware that file_get_contents solution doesn't close the connection as it should when a server returns Connection: close in the HTTP header.
CURL solution, on the other hand, terminates the connection so the PHP script is not blocked by waiting for a response.
use CURL luke :) seriously, thats one of the best ways to do it AND you get the response.