Php create file 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.

Источник

Saving an Image from URL in PHP

Sometimes, need to download an image from a particular URL and use it into the project. It’s easy to go to the page and use right click button and save the image. But what if you wanted to do it programmatically? The reasons may vary person to person, developer to developer. If set of hundreds of image URLs given and somehow want to save them into the machine, or need to use this concept into the projects. Then definitely not going to download each one of those files manually.

Читайте также:  Css скрывать не помещающийся элемент

There are two different approaches to download image from url which are listed below:

Both of these approaches come with their own set of merits and demerits.

Using Basic File Handling: This is the fundamental and easiest way to accomplish the task. Just like any other file, start with the creation of an empty file and open it in “write” mode. After that, fetch the content from source URL and paste it into this file. And it is as simple as it sounds.

From the script, you can figure out on your own about what it does.

  • Declaring two variables named as $url and $img, representing the source URL and destination file respectively.
  • Use file_put_contents() function to write a string to a file that takes two arguments. One is the file name (or path) and the other is the content for that file.
  • Use file_get_contents() function to read a file into a string.

Note: It save the image to the server with given name logo.png.

Now the only problem with this method is that it requires allow_url_fopen configuration to be set, which is set to 1 by default. But sometimes, project requirements don’t allow to have this option. This may be because of some preventive security measures or just a design principle. In such cases, there is another method to save image.

Using HTTP library, cURL: Strictly speaking, cURL is not just an HTTP library. It has got several other data transferring protocols as well. As our image is on an HTTP server, we will limit ourselves to this small section of this library.

cURL allows to make HTTP requests in PHP. Start by initializing an instance of it and setting up some of the necessary options for the request, including the URL itself. Then execute this query which returns the content of the file. After that, the rest of the procedure is the same. As soon as we get the data, put it into a file and save it.

  • In this script, we defined a function file_get_contents_curl to replicate the behaviour of file_get_contents from the previously mentioned technique.
  • Inside this function, we have initialised an instance of cURL using curl_init function in order to use it for fetching the data.
  • After that, some options need to be set using curl_setopt so that this particular example can work. This function takes three arguments
    • An instance of cURL
    • The corresponding option that need to be set
    • And the value to which option is set

    In this example, the following options are set:

    • CURLOPT_HEADER, which is to ensure whether you need to receive the headers or not;
    • CURLOPT_RETURNTRANSFER which transfers data as the return value of curl_exec function rather than outputting it directly.
    • There is this another option CURLOPT_URL that sets the URL for the request.

    Источник

    curl_file_create

    Создает обьект CURLFile, используемый для загрузки файла с использованием опции CURLOPT_POSTFIELDS .

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

    Путь к файлу, который будет загружен

    Имя файла при отправке методом POST.

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

    Список изменений

    Версия Описание
    8.0.0 mime_type и posted_filename теперь допускают значение null; раньше значением по умолчанию был 0 .

    Примеры

    Пример #1 Пример использования CURLFile::__construct()

    // Создаем дескриптор cURL
    $ch = curl_init ( ‘http://example.com/upload.php’ );

    // Создаем объект CURLFile
    $cfile = new CURLFile ( ‘cats.jpg’ , ‘image/jpeg’ , ‘test_name’ );

    // Устанавливаем данные для POST
    $data = array( ‘test_file’ => $cfile );
    curl_setopt ( $ch , CURLOPT_POST , 1 );
    curl_setopt ( $ch , CURLOPT_POSTFIELDS , $data );

    // Запускаем дескриптор на выполнение
    curl_exec ( $ch );
    ?>

    // Создаем дескриптор cURL
    $ch = curl_init ( ‘http://example.com/upload.php’ );

    // Создаем объект CURLFile
    $cfile = curl_file_create ( ‘cats.jpg’ , ‘image/jpeg’ , ‘test_name’ );

    // Устанавливаем данные для POST
    $data = array( ‘test_file’ => $cfile );
    curl_setopt ( $ch , CURLOPT_POST , 1 );
    curl_setopt ( $ch , CURLOPT_POSTFIELDS , $data );

    // Запускаем дескриптор на выполнение
    curl_exec ( $ch );
    ?>

    Результат выполнения данного примера:

    array(1) < ["test_file"]=>array(5) < ["name"]=>string(9) "test_name" ["type"]=> string(10) "image/jpeg" ["tmp_name"]=> string(14) "/tmp/phpPC9Kbx" ["error"]=> int(0) ["size"]=> int(46334) > >

    Пример #2 Пример использования CURLFile::__construct() для загрузки нескольких файлов

    $request = curl_init ( ‘http://www.example.com/upload.php’ );
    curl_setopt ( $request , CURLOPT_POST , true );
    curl_setopt ( $request ,
    CURLOPT_SAFE_UPLOAD , true ); curl_setopt (
    $request ,
    CURLOPT_POSTFIELDS ,
    [
    ‘blob[0]’ => new CURLFile ( realpath ( ‘first-file.jpg’ ), ‘image/jpeg’ ),
    ‘blob[1]’ => new CURLFile ( realpath ( ‘second-file.txt’ ), ‘text/plain’ ),
    ‘blob[2]’ => new CURLFile ( realpath ( ‘third-file.exe’ ), ‘application/octet-stream’ ),
    ] );
    curl_setopt ( $request , CURLOPT_RETURNTRANSFER , true );

    var_dump ( curl_getinfo ( $request ));

    // procedural
    $request = curl_init ( ‘http://www.example.com/upload.php’ );
    curl_setopt ( $request , CURLOPT_POST , true );
    curl_setopt ( $request , CURLOPT_SAFE_UPLOAD , true ); curl_setopt (
    $request ,
    CURLOPT_POSTFIELDS ,
    [
    ‘blob[0]’ => curl_file_create ( realpath ( ‘first-file.jpg’ ), ‘image/jpeg’ ),
    ‘blob[1]’ => curl_file_create ( realpath ( ‘second-file.txt’ ), ‘text/plain’ ),
    ‘blob[2]’ => curl_file_create ( realpath ( ‘third-file.exe’ ), ‘application/octet-stream’ ),
    ] );
    curl_setopt ( $request , CURLOPT_RETURNTRANSFER , true );

    var_dump ( curl_getinfo ( $request ));

    Результат выполнения данного примера:

    array(26) < ["url"]=>string(31) "http://www.example.com/upload.php" ["content_type"]=> string(24) "text/html; charset=UTF-8" ["http_code"]=> int(200) ["header_size"]=> int(198) ["request_size"]=> int(196) ["filetime"]=> int(-1) ["ssl_verify_result"]=> int(0) ["redirect_count"]=> int(0) ["total_time"]=> float(0.060062) ["namelookup_time"]=> float(0.028575) ["connect_time"]=> float(0.029011) ["pretransfer_time"]=> float(0.029121) ["size_upload"]=> float(3230730) ["size_download"]=> float(811) ["speed_download"]=> float(13516) ["speed_upload"]=> float(53845500) ["download_content_length"]=> float(811) ["upload_content_length"]=> float(3230730) ["starttransfer_time"]=> float(0.030355) ["redirect_time"]=> float(0) ["redirect_url"]=> string(0) "" ["primary_ip"]=> string(13) "0.0.0.0" ["certinfo"]=> array(0) < >["primary_port"]=> int(80) ["local_ip"]=> string(12) "0.0.0.0" ["local_port"]=> int(34856) >

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

    Источник

    curl_file_create

    Создает обьект CURLFile, используемый для загрузки файла с использованием опции CURLOPT_POSTFIELDS .

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

    Путь к файлу, который будет загружен

    Имя файла при отправке методом POST.

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

    Список изменений

    Версия Описание
    8.0.0 mime_type и posted_filename теперь допускают значение null; раньше значением по умолчанию был 0 .

    Примеры

    Пример #1 Пример использования CURLFile::__construct()

    // Создаем дескриптор cURL
    $ch = curl_init ( ‘http://example.com/upload.php’ );

    // Создаем объект CURLFile
    $cfile = new CURLFile ( ‘cats.jpg’ , ‘image/jpeg’ , ‘test_name’ );

    // Устанавливаем данные для POST
    $data = array( ‘test_file’ => $cfile );
    curl_setopt ( $ch , CURLOPT_POST , 1 );
    curl_setopt ( $ch , CURLOPT_POSTFIELDS , $data );

    // Запускаем дескриптор на выполнение
    curl_exec ( $ch );
    ?>

    // Создаем дескриптор cURL
    $ch = curl_init ( ‘http://example.com/upload.php’ );

    // Создаем объект CURLFile
    $cfile = curl_file_create ( ‘cats.jpg’ , ‘image/jpeg’ , ‘test_name’ );

    // Устанавливаем данные для POST
    $data = array( ‘test_file’ => $cfile );
    curl_setopt ( $ch , CURLOPT_POST , 1 );
    curl_setopt ( $ch , CURLOPT_POSTFIELDS , $data );

    // Запускаем дескриптор на выполнение
    curl_exec ( $ch );
    ?>

    Результат выполнения данного примера:

    array(1) < ["test_file"]=>array(5) < ["name"]=>string(9) "test_name" ["type"]=> string(10) "image/jpeg" ["tmp_name"]=> string(14) "/tmp/phpPC9Kbx" ["error"]=> int(0) ["size"]=> int(46334) > >

    Пример #2 Пример использования CURLFile::__construct() для загрузки нескольких файлов

    $request = curl_init ( ‘http://www.example.com/upload.php’ );
    curl_setopt ( $request , CURLOPT_POST , true );
    curl_setopt ( $request ,
    CURLOPT_SAFE_UPLOAD , true ); curl_setopt (
    $request ,
    CURLOPT_POSTFIELDS ,
    [
    ‘blob[0]’ => new CURLFile ( realpath ( ‘first-file.jpg’ ), ‘image/jpeg’ ),
    ‘blob[1]’ => new CURLFile ( realpath ( ‘second-file.txt’ ), ‘text/plain’ ),
    ‘blob[2]’ => new CURLFile ( realpath ( ‘third-file.exe’ ), ‘application/octet-stream’ ),
    ] );
    curl_setopt ( $request , CURLOPT_RETURNTRANSFER , true );

    var_dump ( curl_getinfo ( $request ));

    // procedural
    $request = curl_init ( ‘http://www.example.com/upload.php’ );
    curl_setopt ( $request , CURLOPT_POST , true );
    curl_setopt ( $request , CURLOPT_SAFE_UPLOAD , true ); curl_setopt (
    $request ,
    CURLOPT_POSTFIELDS ,
    [
    ‘blob[0]’ => curl_file_create ( realpath ( ‘first-file.jpg’ ), ‘image/jpeg’ ),
    ‘blob[1]’ => curl_file_create ( realpath ( ‘second-file.txt’ ), ‘text/plain’ ),
    ‘blob[2]’ => curl_file_create ( realpath ( ‘third-file.exe’ ), ‘application/octet-stream’ ),
    ] );
    curl_setopt ( $request , CURLOPT_RETURNTRANSFER , true );

    var_dump ( curl_getinfo ( $request ));

    Результат выполнения данного примера:

    array(26) < ["url"]=>string(31) "http://www.example.com/upload.php" ["content_type"]=> string(24) "text/html; charset=UTF-8" ["http_code"]=> int(200) ["header_size"]=> int(198) ["request_size"]=> int(196) ["filetime"]=> int(-1) ["ssl_verify_result"]=> int(0) ["redirect_count"]=> int(0) ["total_time"]=> float(0.060062) ["namelookup_time"]=> float(0.028575) ["connect_time"]=> float(0.029011) ["pretransfer_time"]=> float(0.029121) ["size_upload"]=> float(3230730) ["size_download"]=> float(811) ["speed_download"]=> float(13516) ["speed_upload"]=> float(53845500) ["download_content_length"]=> float(811) ["upload_content_length"]=> float(3230730) ["starttransfer_time"]=> float(0.030355) ["redirect_time"]=> float(0) ["redirect_url"]=> string(0) "" ["primary_ip"]=> string(13) "0.0.0.0" ["certinfo"]=> array(0) < >["primary_port"]=> int(80) ["local_ip"]=> string(12) "0.0.0.0" ["local_port"]=> int(34856) >

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

    Источник

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