Mirek
Mirek

Reputation: 391

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

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?

Upvotes: 4

Views: 9589

Answers (2)

Timothy
Timothy

Reputation: 4650

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.

Upvotes: 1

nathan
nathan

Reputation: 5452

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.

Upvotes: 2

Related Questions