>  기사  >  백엔드 개발  >  file_get_contents 및 HTTP 스트림 컨텍스트를 사용하여 파일을 업로드하는 방법은 무엇입니까?

file_get_contents 및 HTTP 스트림 컨텍스트를 사용하여 파일을 업로드하는 방법은 무엇입니까?

Barbara Streisand
Barbara Streisand원래의
2024-10-18 11:59:03371검색

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 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.