- file_get_contents
- Parameters
- Return Values
- Errors/Exceptions
- Changelog
- Examples
- Notes
- See Also
- User Contributed Notes 6 notes
- Php file load url
- How to download file from URL using PHP
- To download file from URL using PHP
- 1. Using PHP file_get_contents() and file_put_contents() function:
- 2. Using PHP CURL and fopen()
- Final thoughts
- You might also like
- References
- Download a file from the URL in PHP
- First Method
- Second Method.
file_get_contents
This function is similar to file() , except that file_get_contents() returns the file in a string , starting at the specified offset up to length bytes. On failure, file_get_contents() will return false .
file_get_contents() is the preferred way to read the contents of a file into a string. It will use memory mapping techniques if supported by your OS to enhance performance.
Note:
If you’re opening a URI with special characters, such as spaces, you need to encode the URI with urlencode() .
Parameters
Note:
The FILE_USE_INCLUDE_PATH constant can be used to trigger include path search. This is not possible if strict typing is enabled, since FILE_USE_INCLUDE_PATH is an int . Use true instead.
A valid context resource created with stream_context_create() . If you don’t need to use a custom context, you can skip this parameter by null .
The offset where the reading starts on the original stream. Negative offsets count from the end of the stream.
Seeking ( offset ) is not supported with remote files. Attempting to seek on non-local files may work with small offsets, but this is unpredictable because it works on the buffered stream.
Maximum length of data read. The default is to read until end of file is reached. Note that this parameter is applied to the stream processed by the filters.
Return Values
The function returns the read data or false on failure.
This function may return Boolean false , but may also return a non-Boolean value which evaluates to false . Please read the section on Booleans for more information. Use the === operator for testing the return value of this function.
Errors/Exceptions
An E_WARNING level error is generated if filename cannot be found, length is less than zero, or if seeking to the specified offset in the stream fails.
When file_get_contents() is called on a directory, an E_WARNING level error is generated on Windows, and as of PHP 7.4 on other operating systems as well.
Changelog
Version | Description |
---|---|
8.0.0 | length is nullable now. |
7.1.0 | Support for negative offset s has been added. |
Examples
Example #1 Get and output the source of the homepage of a website
Example #2 Searching within the include_path
// If strict types are enabled i.e. declare(strict_types=1);
$file = file_get_contents ( ‘./people.txt’ , true );
// Otherwise
$file = file_get_contents ( ‘./people.txt’ , FILE_USE_INCLUDE_PATH );
?>?php
Example #3 Reading a section of a file
// Read 14 characters starting from the 21st character
$section = file_get_contents ( ‘./people.txt’ , FALSE , NULL , 20 , 14 );
var_dump ( $section );
?>?php
The above example will output something similar to:
Example #4 Using stream contexts
// Create a stream
$opts = array(
‘http’ =>array(
‘method’ => «GET» ,
‘header’ => «Accept-language: en\r\n» .
«Cookie: foo=bar\r\n»
)
);
?php
$context = stream_context_create ( $opts );
// Open the file using the HTTP headers set above
$file = file_get_contents ( ‘http://www.example.com/’ , false , $context );
?>
Notes
Note: This function is binary-safe.
A URL can be used as a filename with this function if the fopen wrappers have been enabled. See fopen() for more details on how to specify the filename. See the Supported Protocols and Wrappers for links to information about what abilities the various wrappers have, notes on their usage, and information on any predefined variables they may provide.
When using SSL, Microsoft IIS will violate the protocol by closing the connection without sending a close_notify indicator. PHP will report this as «SSL: Fatal Protocol Error» when you reach the end of the data. To work around this, the value of error_reporting should be lowered to a level that does not include warnings. PHP can detect buggy IIS server software when you open the stream using the https:// wrapper and will suppress the warning. When using fsockopen() to create an ssl:// socket, the developer is responsible for detecting and suppressing this warning.
See Also
- file() — Reads entire file into an array
- fgets() — Gets line from file pointer
- fread() — Binary-safe file read
- readfile() — Outputs a file
- file_put_contents() — Write data to a file
- stream_get_contents() — Reads remainder of a stream into a string
- stream_context_create() — Creates a stream context
- $http_response_header
User Contributed Notes 6 notes
file_get_contents can do a POST, create a context for that first:
$opts = array( ‘http’ =>
array(
‘method’ => ‘POST’ ,
‘header’ => «Content-Type: text/xml\r\n» .
«Authorization: Basic » . base64_encode ( » $https_user : $https_password » ). «\r\n» ,
‘content’ => $body ,
‘timeout’ => 60
)
);
$context = stream_context_create ( $opts );
$url = ‘https://’ . $https_server ;
$result = file_get_contents ( $url , false , $context , — 1 , 40000 );
Note that if an HTTP request fails but still has a response body, the result is still false, Not the response body which may have more details on why the request failed.
There’s barely a mention on this page but the $http_response_header will be populated with the HTTP headers if your file was a link. For example if you’re expecting an image you can do this:
$mimetype = null ;
foreach ( $http_response_header as $v ) if ( preg_match ( ‘/^content\-type:\s*(image\/[^;\s\n\r]+)/i’ , $v , $m )) $mimetype = $m [ 1 ];
>
>
if (! $mimetype ) // not an image
>
if the connection is
content-encoding: gzip
and you need to manually ungzip it, this is apparently the key
$c=gzinflate( substr($c,10,-8) );
(stolen from the net)
//从指定位置获取指定长度的文件内容
function file_start_length($path,$start=0,$length=null) if(!file_exists($path)) return false;
$size=filesize($path);
if($start <0) $start+=$size;
if($length===null) $length=$size-$start;
return file_get_contents($path, false, null, $start, $length );
>
I’m not sure why @jlh was downvoted, but I verified what he reported.
>>> file_get_contents($path false, null, 5, null)
=> «»
>>> file_get_contents($path, false, null, 5, 5)
=> «r/bin»
Php file load url
I think the way an array of attachments works is kind of cumbersome. Usually the PHP guys are right on the money, but this is just counter-intuitive. It should have been more like:
Array
(
[0] => Array
(
[name] => facepalm.jpg
[type] => image/jpeg
[tmp_name] => /tmp/phpn3FmFr
[error] => 0
[size] => 15476
)
Anyways, here is a fuller example than the sparce one in the documentation above:
foreach ( $_FILES [ «attachment» ][ «error» ] as $key => $error )
$tmp_name = $_FILES [ «attachment» ][ «tmp_name» ][ $key ];
if (! $tmp_name ) continue;
$name = basename ( $_FILES [ «attachment» ][ «name» ][ $key ]);
if ( $error == UPLOAD_ERR_OK )
if ( move_uploaded_file ( $tmp_name , «/tmp/» . $name ) )
$uploaded_array [] .= «Uploaded file ‘» . $name . «‘.
\n» ;
else
$errormsg .= «Could not move uploaded file ‘» . $tmp_name . «‘ to ‘» . $name . «‘
\n» ;
>
else $errormsg .= «Upload error. [» . $error . «] on file ‘» . $name . «‘
\n» ;
>
?>
Do not use Coreywelch or Daevid’s way, because their methods can handle only within two-dimensional structure. $_FILES can consist of any hierarchy, such as 3d or 4d structure.
The following example form breaks their codes:
As the solution, you should use PSR-7 based zendframework/zend-diactoros.
use Psr \ Http \ Message \ UploadedFileInterface ;
use Zend \ Diactoros \ ServerRequestFactory ;
$request = ServerRequestFactory :: fromGlobals ();
if ( $request -> getMethod () !== ‘POST’ ) http_response_code ( 405 );
exit( ‘Use POST method.’ );
>
$uploaded_files = $request -> getUploadedFiles ();
if (
!isset( $uploaded_files [ ‘files’ ][ ‘x’ ][ ‘y’ ][ ‘z’ ]) ||
! $uploaded_files [ ‘files’ ][ ‘x’ ][ ‘y’ ][ ‘z’ ] instanceof UploadedFileInterface
) http_response_code ( 400 );
exit( ‘Invalid request body.’ );
>
$file = $uploaded_files [ ‘files’ ][ ‘x’ ][ ‘y’ ][ ‘z’ ];
if ( $file -> getError () !== UPLOAD_ERR_OK ) http_response_code ( 400 );
exit( ‘File uploading failed.’ );
>
$file -> moveTo ( ‘/path/to/new/file’ );
The documentation doesn’t have any details about how the HTML array feature formats the $_FILES array.
Array
(
[document] => Array
(
[name] => sample-file.doc
[type] => application/msword
[tmp_name] => /tmp/path/phpVGCDAJ
[error] => 0
[size] => 0
)
)
Multi-files with HTML array feature —
Array
(
[documents] => Array
(
[name] => Array
(
[0] => sample-file.doc
[1] => sample-file.doc
)
(
[0] => application/msword
[1] => application/msword
) [tmp_name] => Array
(
[0] => /tmp/path/phpVGCDAJ
[1] => /tmp/path/phpVGCDAJ
)
The problem occurs when you have a form that uses both single file and HTML array feature. The array isn’t normalized and tends to make coding for it really sloppy. I have included a nice method to normalize the $_FILES array.
function normalize_files_array ( $files = [])
foreach( $files as $index => $file )
if (! is_array ( $file [ ‘name’ ])) $normalized_array [ $index ][] = $file ;
continue;
>
foreach( $file [ ‘name’ ] as $idx => $name ) $normalized_array [ $index ][ $idx ] = [
‘name’ => $name ,
‘type’ => $file [ ‘type’ ][ $idx ],
‘tmp_name’ => $file [ ‘tmp_name’ ][ $idx ],
‘error’ => $file [ ‘error’ ][ $idx ],
‘size’ => $file [ ‘size’ ][ $idx ]
];
>
?>
The following is the output from the above method.
Array
(
[document] => Array
(
[0] => Array
(
[name] => sample-file.doc
[type] => application/msword
[tmp_name] => /tmp/path/phpVGCDAJ
[error] => 0
[size] => 0
)
(
[0] => Array
(
[name] => sample-file.doc
[type] => application/msword
[tmp_name] => /tmp/path/phpVGCDAJ
[error] => 0
[size] => 0
) [1] => Array
(
[name] => sample-file.doc
[type] => application/msword
[tmp_name] => /tmp/path/phpVGCDAJ
[error] => 0
[size] => 0
)
How to download file from URL using PHP
Building PHP applications will require file interaction a lot, one of them is download file from URL using PHP. This article will guide you the very basic methods of using PHP for downloading file from an URL.
To download file from URL using PHP
1. Using PHP file_get_contents() and file_put_contents() function:
This method can only be used if the web hosting allows the file_get_contents function to run. A lot of the web hosting turns off this function for security reasons , so you should check if the function is enabled before using this method. After successfully getting the file, file_put_contents will be used to actually save the file into a location.
If the message tells that the download is successful, the file will be store on the save path we defined.
2. Using PHP CURL and fopen()
The CURL method is more widely used, and we recommend you to use PHP CURL for downloading files from URLs instead of using file_get_contents function. CURL provides more compatibility, more controls over the downloading process and helps you to get familiar with using CURL in PHP, which will be crucial for many other network-related tasks in PHP. Also, working with fopen will be more convenient later with file interaction tasks. To download file from URL using PHP with CURL and fopen :
If no error displays after running the codes, the file will be stored at the defined $savePath location.
Final thoughts
The tutorial is now over. Hopefully it is helpful for you to understand the basic knowledge to download file from URL using PHP with file_get_contents and CURL. Thank you for reading!
You might also like
References
Download a file from the URL in PHP
In this post, I will try to explain to you how you can download any file by its URL with the help of PHP. You can do it in many ways but in this tutorial, I will explain to you a few tricks.
First Method
We will use file_get_contents() a built-in function of PHP. This function is similar to file() the only difference is file_get_contents() returns the file in a string. This function uses memory mapping techniques and it is a preferred way to read file content.
file_get_contents ( string $filename [, bool $use_include_path = FALSE [, resource $context [, int $offset = 0 [, int $maxlen ]]]] ) : string
The function returns the read data or FALSE on failure.
The above function will save the file on the same path where you run the script of PHP. If you want to download the file in your desired location then you need to set some headers. That is why I write a function given below that you can use to save file form URL into your local system.
The usage of the above function is given below.
Second Method.
In this method, I will show you how you can download a file with the helo of CURL another built-in function of PHP. If you use the below function you can save the file directly into your system by giving your desired location.
The usage of the above function is given below.
$urlPdf = 'http://www.africau.edu/images/default/sample.pdf'; dfCurl($urlPdf);
You can use any above function to download the file into your system or into your server.