首頁 > 後端開發 > php教程 > 如何使用 file_get_contents 和 HTTP 流上下文上傳檔案?

如何使用 file_get_contents 和 HTTP 流上下文上傳檔案?

Barbara Streisand
發布: 2024-10-18 11:59:03
原創
510 人瀏覽過

How to Upload a File Using file_get_contents and HTTP Stream Context?

Uploading a File with file_get_contents and HTTP Stream Context

Unlike CURL, file_get_contents() can also be utilized to upload files to remote web servers using the HTTP stream context. To achieve this, follow these steps:

1. Define the Boundary:

Start by defining a boundary that will separate each part of the multipart Content-Type. Choose a string that doesn't exist within the content body.

<code class="php">define('MULTIPART_BOUNDARY', '--------------------------'.microtime(true));</code>
登入後複製

2. Set the Content-Type Header:

Send the boundary in the Content-Type header to indicate the expected delimiter.

<code class="php">$header = 'Content-Type: multipart/form-data; boundary='.MULTIPART_BOUNDARY;</code>
登入後複製

3. Define the Form Field Name:

Specify the name of the form field to which the file will be uploaded.

<code class="php">// equivalent to <input type="file" name="uploaded_file"/>
define('FORM_FIELD', 'uploaded_file'); </code>
登入後複製

4. Build the Content Body:

Construct the content body according to the HTTP specification and the header sent. Include the necessary headers and file content.

<code class="php">$filename = "/path/to/uploaded/file.zip";
$file_contents = file_get_contents($filename);    

$content =  "--".MULTIPART_BOUNDARY."\r\n".
            "Content-Disposition: form-data; name=\"".FORM_FIELD."\"; filename=\"".basename($filename)."\"\r\n".
            "Content-Type: application/zip\r\n\r\n".
            $file_contents."\r\n";

// add POST fields
$content .= "--".MULTIPART_BOUNDARY."\r\n".
            "Content-Disposition: form-data; name=\"foo\"\r\n\r\n".
            "bar\r\n";

// end of request
$content .= "--".MULTIPART_BOUNDARY."--\r\n";</code>
登入後複製

5. Create the Context:

Build the stream context with the necessary HTTP parameters.

<code class="php">$context = stream_context_create(array(
    'http' =&gt; array(
          'method' =&gt; 'POST',
          'header' =&gt; $header,
          'content' =&gt; $content,
    )
));</code>
登入後複製

6. Execute the Request:

Upload the file using file_get_contents() with the context.

<code class="php">file_get_contents('http://url/to/upload/handler', false, $context);</code>
登入後複製

Remember, binary files do not need to be encoded before transmission. HTTP can handle them directly.

以上是如何使用 file_get_contents 和 HTTP 流上下文上傳檔案?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:php
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板