Jump to content

Posting form data to page with basic auth using stream_context_create()


simonrs

Recommended Posts

Hi all,

Subject says it all really...

 

I had a script that was posting XML files to a URL, it was working absolutely fine. Then my client put apache basic auth (you know, like a .htaccess file, with the popup that asks for username and password) on the page that receives the XMLs. Now I can achieve the authorisation with a header line I found on PHP.net's documentation, but now the file doesn't get through - the stream is empty when it is sent.

 

Has anyone managed to do this or can anyone see a flaw in my code?

 

$boundary = "---------------------".substr(md5(rand(0,32000)), 0, 10);
    $data = "--$boundary\n";
    
    $fileContents = file_get_contents($file);
    $parts = split('/', $file);
    $filename = end($parts);
    
    $data .=
    "Content-Disposition: form-data; name=\"file\"; filename=\"$filename\"\n" .
    "Content-Type: $contentType\n" .
    "Content-Transfer-Encoding: binary\n\n" .
    $fileContents . "\n" .
    "--$boundary--\n";
    
    
    
    $header = 'Content-Type: multipart/form-data; boundary=' . $boundary;
    if(isset($username))
    {
      $auth = base64_encode("$username:$password");
      $header .= "\nAuthorization: Basic $auth";
    }
    
    $params = array('http' => array(
      'method' => $method,
      'header' => $header,
      'content' => $data));

   $ctx = stream_context_create($params);
   $fp = fopen($url, 'rb', false, $ctx);
   if(!$fp)
     trigger_error('Invalid URL specified for httprequest', E_USER_ERROR);
   
   $response = @stream_get_contents($fp);
   return $response;

 

Many thanks

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.