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.
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.
I am trying to send a file_get_contents request to a URL with POST data and a cookie set.
My code is like that:
$postdata = http_build_query(
array(
'search' => 'test',
'token' => '0'
)
);
// Create a stream
$opts = array(
'http'=> array(
'method'=>"POST",
'content' => $postdata,
'header' => "Content-Type: application/x-www-form-urlencoded\n"."Cookie: session_hash=123456789"
)
);
$context = stream_context_create($opts);
// Open the file using the HTTP headers set above
$file = file_get_contents('https://example.com', false, $context);
echo $file;
This is posting the data as I can see, but the Cookie is not being sent during the request...
I also tried to use the same request but with CURL and I have the same problem with that.
Any help would be appreciated.
Thanks!
The headers may need to be separated by \r\n rather than just \n. You can also use an array, and they'll be sent properly.
'header' => array("Content-Type: application/x-www-form-urlencoded",
"Cookie: session_hash=123456789")
i'm new to curl.
i have this curl code.
but i have no idea about run this with php
curl -X POST -u "{username}":"{password}"
--header "Content-Type: audio/flac"
--data-binary "#audio-file1.flac"
"https://stream.watsonplatform.net/speech-to-text/api/v1/recognize?timestamps=true&word_alternatives_threshold=0.9&keywords=%22colorado%22%2C%22tornado%22%2C%22tornadoes%22&keywords_threshold=0.5"
this is my php code.but not sure that i'm correct.
$s = curl_init();
curl_setopt($s, CURLOPT_URL, 'https://stream.watsonplatform.net/speech-to-text/api/v1/recognize?timestamps=true&word_alternatives_threshold=0.9&keywords=%22colorado%22%2C%22tornado%22%2C%22tornadoes%22&keywords_threshold=0.5');
curl_setopt($s, CURLOPT_POST, 1);
curl_setopt($s, CURLOPT_POSTFIELDS, http_build_query([
'--header' => "Content-Type: audio/flac",
'--data-binary' => '#audio-file1.flac'
]));
curl_exec($s);
curl_close($s);
please help me how to add -u "{username}":"{password}" to php code?
the good way to do this, is with a file handle and CURLOPT_INFILE, this will work with files of any size, and allows the upload to start before the entire file has been read from disk, thus it's faster and use just a small amount of memory, no matter how big the file is. however, the quick'n easy way, which puts the entire file in memory at once, and doesn't start the upload until the entire file has been read into ram, and is thus unsuitable for big files, is simply: curl_setopt($ch,CURLOPT_POSTFIELDS,file_get_contents($filename));, but.. the rough equivalent to your curl command, using the good method, is:
$ch = curl_init ();
$filename = "audio-file1.flac";
$fileh = fopen ( $filename, 'rb' );
curl_setopt_array ( $ch, array (
CURLOPT_USERPWD => "{username}:{password}",
CURLOPT_HTTPHEADER => array (
'Content-Type: audio/flac'
),
CURLOPT_POST => 1,
CURLOPT_INFILE => $fileh,
CURLOPT_INFILESIZE => filesize ( $filename ),
CURLOPT_URL => "https://stream.watsonplatform.net/speech-to-text/api/v1/recognize?timestamps=true&word_alternatives_threshold=0.9&keywords=%22colorado%22%2C%22tornado%22%2C%22tornadoes%22&keywords_threshold=0.5",
CURLOPT_USERAGENT => 'libcurl/' . curl_version () ['version'] . '; php/' . PHP_VERSION
) );
// curl_setopt ( $ch, CURLOPT_URL, '127.0.0.1:9999' );
curl_exec ( $ch );
fclose ( $fileh );
curl_close ( $ch );
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
)
);
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);