Copy php from url

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.

Источник

copy

Если вы хотите переименовать файл, используйте функцию rename() .

Список параметров

Путь к целевому файлу. Если to является URL, то операция копирования может завершиться ошибкой, если обёртка URL не поддерживает перезаписывание существующих файлов.

Если целевой файл уже существует, то он будет перезаписан.

Корректный ресурс контекста, созданный функцией stream_context_create() .

Возвращаемые значения

Возвращает true в случае успешного выполнения или false в случае возникновения ошибки.

Примеры

Пример #1 Пример использования функции copy()

$file = ‘example.txt’ ;
$newfile = ‘example.txt.bak’ ;

if (! copy ( $file , $newfile )) echo «не удалось скопировать $file . \n» ;
>
?>

Смотрите также

  • move_uploaded_file() — Перемещает загруженный файл в новое место
  • rename() — Переименовывает файл или директорию
  • Раздел руководства «Загрузка файлов»

User Contributed Notes 24 notes

Having spent hours tacking down a copy() error: Permission denied , (and duly worrying about chmod on winXP) , its worth pointing out that the ‘destination’ needs to contain the actual file name ! — NOT just the path to the folder you wish to copy into.
DOH !
hope this saves somebody hours of fruitless debugging

Читайте также:  Execute python script from command line

It take me a long time to find out what the problem is when i’ve got an error on copy(). It DOESN’T create any directories. It only copies to existing path. So create directories before. Hope i’ll help,

On Windows, php-7.4.19-Win32-vc15-x64 — copy() corrupted a 6GB zip file. Our only recourse was to write:

function file_win_copy( $src, $dst ) shell_exec( ‘COPY «‘.$src.'» «‘.$dst.'»‘);
return file_exists($dest);
>

Don’t forget; you can use copy on remote files, rather than doing messy fopen stuff. e.g.

if(!@ copy ( ‘http://someserver.com/somefile.zip’ , ‘./somefile.zip’ ))
$errors = error_get_last ();
echo «COPY ERROR: » . $errors [ ‘type’ ];
echo «
\n» . $errors [ ‘message’ ];
> else echo «File copied from remote!» ;
>
?>

Here is a simple script that I use for removing and copying non-empty directories. Very useful when you are not sure what is the type of a file.

I am using these for managing folders and zip archives for my website plugins.

// removes files and non-empty directories
function rrmdir ( $dir ) if ( is_dir ( $dir )) $files = scandir ( $dir );
foreach ( $files as $file )
if ( $file != «.» && $file != «..» ) rrmdir ( » $dir / $file » );
rmdir ( $dir );
>
else if ( file_exists ( $dir )) unlink ( $dir );
>

// copies files and non-empty directories
function rcopy ( $src , $dst ) if ( file_exists ( $dst )) rrmdir ( $dst );
if ( is_dir ( $src )) mkdir ( $dst );
$files = scandir ( $src );
foreach ( $files as $file )
if ( $file != «.» && $file != «..» ) rcopy ( » $src / $file » , » $dst / $file » );
>
else if ( file_exists ( $src )) copy ( $src , $dst );
>
?>

Cheers!

A nice simple trick if you need to make sure the folder exists first:

$srcfile = ‘C:\File\Whatever\Path\Joe.txt’ ;
$dstfile = ‘G:\Shared\Reports\Joe.txt’ ;
mkdir ( dirname ( $dstfile ), 0777 , true );
copy ( $srcfile , $dstfile );

Below a code snippet for downloading a file from a web server to a local file.

It demonstrates useful customizations of the request (such as setting a User-Agent and Referrer, often required by web sites), and how to download only files if the copy on the web site is newer than the local copy.

It further demonstrates the processing of response headers (if set by server) to determine the timestamp and file name. The file type is checked because some servers return a 200 OK return code with a textual «not found» page, instead of a proper 404 return code.

// $fURI: URL to a file located on a web server
// $target_file: Path to a local file

if ( file_exists ( $target_file ) ) $ifmodhdr = ‘If-Modified-Since: ‘ . date ( «r» , filemtime ( $target_file ) ). «\r\n» ;
>
else $ifmodhdr = » ;
>

Читайте также:  Php сделать превью pdf

// set request header for GET with referrer for modified files, that follows redirects
$arrRequestHeaders = array(
‘http’ =>array(
‘method’ => ‘GET’ ,
‘protocol_version’ => 1.1 ,
‘follow_location’ => 1 ,
‘header’ => «User-Agent: Anamera-Feed/1.0\r\n» .
«Referer: $source \r\n» .
$ifmodhdr
)
);
$rc = copy ( $fURI , $target_file , stream_context_create ( $arrRequestHeaders ) );

// HTTP request completed, preserve system error, if any
if( $rc ) if ( fclose ( $rc ) ) unset( $err );
>
else $err = error_get_last ();
>
>
else $err = error_get_last ();
>

// Parse HTTP Response Headers for HTTP Status, as well filename, type, date information
// Need to start from rear, to get last set of headers after possible sets of redirection headers
if ( $http_response_header ) for ( $i = sizeof ( $http_response_header ) — 1 ; $i >= 0 ; $i — ) if ( preg_match ( ‘@^http/\S+ (\S) (.+)$@i’ , $http_response_header [ $i ], $http_status ) > 0 ) // HTTP Status header means we have reached beginning of response headers for last request
break;
>
elseif ( preg_match ( ‘@^(\S+):\s*(.+)\s*$@’ , $http_response_header [ $i ], $arrHeader ) > 0 ) switch ( $arrHeader [ 1 ] ) case ‘Last-Modified’ :
if ( !isset( $http_content_modtime ) ) $http_content_modtime = strtotime ( $arrHeader [ 2 ] );
>
break;
case ‘Content-Type’ :
if ( !isset( $http_content_image_type ) ) if ( preg_match ( ‘@^image/(\w+)@ims’ , $arrHeader [ 2 ], $arrTokens ) > 0 ) if ( in_array ( strtolower ( $arrTokens [ 1 ]), $arrValidTypes )) $http_content_image_type = $arrTokens [ 1 ];
break;
>
>
throw new Exception ( «Error accessing file $fURI ; invalid content type: $arrHeader [ 2 ] » , 2 );
>
break;
case ‘Content-Disposition’ :
if ( !isset( $http_content_filename ) && preg_match ( ‘@filename\\s*=\\s*(?|»([^»]+)»|([\\S]+));?@ims’ , $arrHeader [ 2 ], $arrTokens ) > 0 ) $http_content_filename = basename ( $arrTokens [ 1 ]);
>
break;
>
>
>
>

if ( $http_status ) // Make sure we have good HTTP Status
switch ( $http_status [ 1 ] ) case ‘200’ :
// SUCCESS: HTTP Status is «200 OK»
break;
case ‘304’ :
throw new Exception ( «Remote file not newer: $fURI » , $http_status [ 1 ] );
break;
case ‘404’ :
throw new Exception ( «Remote file not found: $fURI » , $http_status [ 1 ] );
break;
default:
throw new Exception ( «HTTP Error, $http_status [ 2 ] , accessing $fURI » , $http_status [ 1 ] );
break;
>
>
elseif ( $err ) // Protocol / Communication error
throw new Exception ( $err [ ‘message’ ] /*.»; Remote file: $fURI»*/ , $err [ ‘type’ ] );
>
else // No HTTP status and no error
throw new customException ( «Unknown HTTP response accessing $fURI : $http_response_header [ 0 ] » , — 1 );
>
?>

Notes:
1. Currently copy() does NOT appropriately handle the 304 response code. Instead of NOT performing a copy (possibly setting the RC), it will overwrite the target file with an zero length file.
2. There may be a problem accessing a list of remote files when HTTP 1.1 protocol is used. If you experience time-out errors, try the default 1.0 protocol version.

Источник

How to download file from URL using PHP

PHP101.net - 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.

Читайте также:  Css sticky overflow scroll

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

Источник

How to Save Image from URL using PHP

Saving image from URL is very useful when you want to copy an image dynamically from the remote server and store in the local server. The file_get_contents() and file_put_contents() provides an easiest way to save remote image to local server using PHP. The image file can be saved straight to directory from the URL. In the example code snippet, we will provide two ways to save image from URL using PHP.

Save Image from URL using PHP

The following code snippet helps you to copy an image file from remote URL and save in a folder using PHP.

  • file_get_contents() – This function is used to read the image file from URL and return the content as a string.
  • file_put_contents() – This function is used to write remote image data to a file.
// Remote image URL
$url = 'http://www.example.com/remote-image.png';

// Image path
$img = 'images/codexworld.png';

// Save image
file_put_contents($img, file_get_contents($url));

Save Image from URL using cURL

You can use cURL to save an image from URL using PHP. The following code snippet helps you to copy an image file from URL using cURL in PHP.

// Remote image URL
$url = 'http://www.example.com/remote-image.png';

// Image path
$img = 'images/codexworld.png';

// Save image
$ch = curl_init($url);
$fp = fopen($img, 'wb');
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_exec($ch);
curl_close($ch);
fclose($fp);

Источник

Оцените статью