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

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.