PHP - convert file to binary and send it using HTTP POST

I am going to convert some file using php and send it as part of the 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); 

Should the $file variable be the byte representation of the file I want to send?

And is this the right way to submit a file in php without using a form? Do you have any clues?

Also how to convert file to byte representation using PHP?

+4
source share
2 answers

It may be easier for you 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 the place where you want to send the message, and $ file is the path to the file you want to send.

+2
source

Oddly enough, I just wrote an article and illustrated the same scenario. ( phpmaster.com/5-inspiring-and-useful-php-snippets ). But to get you started, here is the 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 such situations, it helps to make a false web form and run it through Firefox with firebug or something like that, and then check the submitted request. From there you can conclude important things.

+1
source

All Articles