Php получить файл и сохранить

Php получить файл и сохранить

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» ;
>
?>

Читайте также:  What is java lang string

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
)

[type] => Array
(
[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
)

[documents] => Array
(
[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
)

Источник

Запись и чтение файлов в PHP

Примеры сохранения и чтения текстовых данных и массивов в файлы.

Сохранение в файл

Функция file_put_contents() записывает содержимое переменной в файл, если файла не существует. то пытается его создать, если существует то полностью перезапишет его.

File_put_contents:

$text = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.'; $filename = __DIR__ . '/file.txt'; file_put_contents($filename, $text);

Fopen / fwrite:

Набор функций fopen, fwrite, fclose предназначены для более гибкой работы с файлами.

  • fopen – открытие или создание файла.
  • fwrite – запись данных.
  • fclose – закрытие файла.
$text = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.'; $filename = __DIR__ . '/file.txt'; $fh = fopen($filename, 'w'); fwrite($fh, $text); fclose($fh);

Возможные режимы fopen():

Mode Описание
r Открывает файл только для чтения, помещает указатель в начало файла.
r+ Открывает файл для чтения и записи, помещает указатель в начало файла.
w Открывает файл только для записи, помещает указатель в начало файла и обрезает файл до нулевой длины. Если файл не существует – пробует его создать.
w+ Открывает файл для чтения и записи, помещает указатель в начало файла и обрезает файл до нулевой длины. Если файл не существует – пытается его создать.
a Открывает файл только для записи, помещает указатель в конец файла. Если файл не существует – пытается его создать.
a+ Открывает файл для чтения и записи, помещает указатель в конец файла. Если файл не существует – пытается его создать.
x Создаёт и открывает только для записи; помещает указатель в начало файла. Если файл уже существует, вызов fopen() закончится неудачей, вернёт false и выдаст ошибку. Если файл не существует, попытается его создать.
x+ Создаёт и открывает для чтения и записи, в остальном имеет то же поведение, что и « x ».
c Открывает файл только для записи. Если файл не существует, то он создаётся. Если же файл существует, то он не обрезается (в отличие от « w »), и вызов к этой функции не вызывает ошибку (также как и в случае с « x »). Указатель на файл будет установлен на начало файла.
c+ Открывает файл для чтения и записи, в остальном имеет то же поведение, что и « c ».

Доступно в место fwrite() используют fputs() , разницы ни какой т.к. эта функция является псевдонимом.

Дописать строку в начало файла

$new_str = 'New line of text.'; $filename = __DIR__ . '/file.txt'; $text = file_get_contents($filename); file_put_contents($filename, $new_str . PHP_EOL . $text);

Дописать строку в конец файла

$new_str = 'New line of text.'; $filename = __DIR__ . '/file.txt'; file_put_contents($filename, PHP_EOL . $new_str, FILE_APPEND);
$new_str = 'New line of text.'; $filename = __DIR__ . '/file.txt'; $fh = fopen($filename, 'c'); fseek($fh, 0, SEEK_END); fwrite($fh, PHP_EOL . $new_str); fclose($fh);

Чтение из файла

Чтение всего файла

$filename = __DIR__ . '/file.txt'; $text = file_get_contents($filename); echo $text;
$filename = __DIR__ . '/file.txt'; $text = ''; $fh = fopen($filename, 'r'); while (!feof($fh)) < $line = fgets($fh); $text .= $line . PHP_EOL; >fclose($fh); echo $text;

Чтение файла в массив

Функция file() – читает содержимое файла и помещает его в массив, доступны опции:

  • FILE_IGNORE_NEW_LINES – пропускать новую строку в конце каждого элемента массива.
  • FILE_SKIP_EMPTY_LINES – пропускать пустые строки.
$filename = __DIR__ . '/file.txt'; $array = file($filename); print_r($array);

Чтение файла сразу в браузер

$filename = __DIR__ . '/file.txt'; readfile($filename);

Получить первую строку из файла

$filename = __DIR__ . '/file.txt'; $fh = fopen($filename, 'r'); echo fgets($fh); fclose($fh); /* или */ $filename = __DIR__ . '/file.txt'; $array = file($filename); echo $array[0];

Первые три строки из файла:

$filename = __DIR__ . '/file.txt'; $array = file($filename); $first_3 = array_slice($array, 0, 3); print_r($first_3);

Получить последнюю строку из файла

$filename = __DIR__ . '/file.txt'; $array = file($filename); $last = array_slice($array, -1); echo $last[0];

Последние три строки из файла:

$filename = __DIR__ . '/file.txt'; $array = file($filename); $last_3 = array_slice($array, -3); print_r($last_3);

Запись и чтение массивов в файл

Serialize

Не очень удачное хранение данных в сериализованном виде т.к. изменение одного символа может привести к ошибке чтения всех данных в файле. Подробнее в статье «Функция serialize, возможные проблемы»

Запись:

$array = array('foo', 'bar', 'hallo', 'world'); $text = base64_encode(serialize($array)); file_put_contents(__DIR__ . '/array.txt', $text);

Чтение:

$array = unserialize(base64_decode($text)); print_r($array);

JSON

Запись:

$array = array('foo', 'bar', 'hallo', 'world'); $json = json_encode($array, JSON_UNESCAPED_UNICODE); file_put_contents(__DIR__ . '/array.json', $json);

Чтение:

$json = file_get_contents(__DIR__ . '/array.json'); $array = json_decode($json, true); print_r($array);

Источник

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.

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

Источник

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