В каком массиве содержатся данные о загруженном пользователем файле

Данная возможность позволяет загружать как текстовые, так и
бинарные файлы. С помощью PHP-функций аутентификации и работы с
файлами вы имеете полный контроль над тем, кому разрешено
загружать файлы и что делать с файлом после его загрузки.

PHP способен получать загруженные файлы из любого браузера,
совместимого со стандартом RFC-1867.

Замечание:
Смежные замечания по конфигурации

Также ознакомьтесь с описанием директив file_uploads,
upload_max_filesize,
upload_tmp_dir,
post_max_size и
max_input_time конфигурационного
файла php.ini

Также следует заметить, что PHP поддерживает загрузку файлов методом PUT,
который используется в клиентах Netscape Composer
и W3C Amaya. Для получения
более детальной документации обратитесь к разделу
поддержка метода PUT.

Пример #1 Форма для загрузки файлов

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

<!– Тип кодирования данных, enctype, ДОЛЖЕН БЫТЬ указан ИМЕННО так –>
<form enctype=”multipart/form-data” action=”__URL__” method=”POST”>
<!– Поле MAX_FILE_SIZE должно быть указано до поля загрузки файла –>
<input type=”hidden” name=”MAX_FILE_SIZE” value=”30000″ />
<!– Название элемента input определяет имя в массиве $_FILES –>
Отправить этот файл: <input name=”userfile” type=”file” />
<input type=”submit” value=”Отправить файл” />
</form>

В приведенном выше примере __URL__ необходимо заменить ссылкой
на PHP-скрипт.

Скрытое поле MAX_FILE_SIZE (значение
необходимо указывать в байтах) должно предшествовать полю
для выбора файла, и его значение является максимально
допустимым размером принимаемого файла в PHP.
Рекомендуется всегда использовать эту переменную, так как она
предотвращает тревожное ожидание пользователей при передаче
огромных файлов, только для того, чтобы узнать, что файл
слишком большой и передача фактически не состоялась.
Имейте в виду, что обойти это ограничение на стороне браузера достаточно
просто, следовательно, вы не должны полагаться на то, что
все файлы большего размера будут блокированы при помощи этой
возможности. Это по большей части удобная возможность для
пользователей клиентской части вашего приложения.
Однако настройки PHP (на сервере) касательно
максимального размера обойти невозможно.

Замечание:

Также следует убедиться, что форма загрузки имеет атрибут
enctype=”multipart/form-data”, в противном случае
загрузка файлов на сервер не произойдет.

Глобальный массив $_FILES содержит всю информацию о загруженных файлах.
Его содержимое для нашего примера приводится ниже. Обратите внимание, что здесь предполагается
использование имени userfile для поля
выбора файла, как и в приведенном выше примере. На самом деле
имя поля может быть любым.

$_FILES[‘userfile’][‘name’]

Оригинальное имя файла на компьютере клиента.

$_FILES[‘userfile’][‘type’]

Mime-тип файла, в случае, если браузер предоставил такую
информацию. В качестве примера можно привести “image/gif”. Этот
mime-тип не проверяется на стороне PHP, так что не полагайтесь
на его значение без проверки.

$_FILES[‘userfile’][‘size’]

Размер в байтах принятого файла.

$_FILES[‘userfile’][‘tmp_name’]

Временное имя, с которым принятый файл был сохранен на сервере.

$_FILES[‘userfile’][‘error’]

Код ошибки,
которая может возникнуть при загрузке файла.

По умолчанию принятые файлы сохраняются на сервере в стандартной
временной папке до тех пор, пока не будет задана другая директория при
помощи директивы upload_tmp_dir
конфигурационного файла php.ini. Директорию сервера по умолчанию
можно сменить, установив переменную TMPDIR для
окружения, в котором выполняется PHP. Установка этой переменной при помощи
функции putenv() внутри PHP-скрипта работать
не будет. Эта переменная окружения также может использоваться для того,
чтобы удостовериться, что другие операции также работают с принятыми файлами.

Пример #2 Проверка загружаемых на сервер файлов

Для получения более детальной информации вы можете ознакомиться
с описанием функций is_uploaded_file()
и move_uploaded_file(). Следующий пример
принимает и обрабатывает загруженный при помощи формы файл.

<?php
$uploaddir = ‘/var/www/uploads/’;
$uploadfile = $uploaddir . basename($_FILES[‘userfile’][‘name’]);

echo 

‘<pre>’;
if (move_uploaded_file($_FILES[‘userfile’][‘tmp_name’], $uploadfile)) {
    echo “Файл корректен и был успешно загружен.n”;
} else {
    echo “Возможная атака с помощью файловой загрузки!n”;
}

echo 

‘Некоторая отладочная информация:’;
print_r($_FILES);

print 

“</pre>”;?>

PHP-скрипт, принимающий загруженный файл, должен реализовывать логику,
необходимую для определения дальнейших действий над принятым файлом.
Например, вы можете проверить переменную $_FILES[‘userfile’][‘size’],
чтобы отсечь слишком большие или слишком маленькие файлы. Также вы
можете использовать переменную $_FILES[‘userfile’][‘type’]
для исключения файлов, которые не удовлетворяют критерию касательно
типа файла, однако, принимайте во внимание, что это поле полностью
контролируется клиентом, используйте его только в качестве первой
из серии проверок. Также вы можете использовать
$_FILES[‘userfile’][‘error’] и
коды ошибок
при реализации вашей логики. Независимо от того, какую модель поведения
вы выбрали, вы должны удалить файл из временной папки или переместить его в
другую директорию.

В случае, если при отправке формы файл выбран не был, PHP установит
переменную $_FILES[‘userfile’][‘size’] значением 0, а переменную
$_FILES[‘userfile’][‘tmp_name’] – none.

По окончанию работы скрипта, если загруженный файл не был
переименован или перемещен, он будет автоматически удален из временной папки.

Пример #3 Загрузка массива файлов

PHP поддерживает возможность передачи массива из HTML
в том числе и с файлами.

<form action=”” method=”post” enctype=”multipart/form-data”>
<p>Изображения:
<input type=”file” name=”pictures[]” />
<input type=”file” name=”pictures[]” />
<input type=”file” name=”pictures[]” />
<input type=”submit” value=”Отправить” />
</p>
</form>

<?php
foreach ($_FILES[“pictures”][“error”] as $key => $error) {
    if ($error == UPLOAD_ERR_OK) {
        $tmp_name = $_FILES[“pictures”][“tmp_name”][$key];
        // basename() может спасти от атак на файловую систему;
        // может понадобиться дополнительная проверка/очистка имени файла
        $name = basename($_FILES[“pictures”][“name”][$key]);
        move_uploaded_file($tmp_name, “data/$name”);
    }
}
?>

Полоса прогресса загрузки файлов может быть реализована с помощью
“отслеживания прогресса загрузки файлов с помощью сессий”.

daevid at daevid dot com

11 years ago

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
        )

    [1] => Array
        (
            [name] =>
            [type] =>
            [tmp_name] =>
            [error] => 4
            [size] =>
        )
)

and not this
Array
(
    [name] => Array
        (
            [0] => facepalm.jpg
            [1] =>
        )

    [type] => Array
        (
            [0] => image/jpeg
            [1] =>
        )

    [tmp_name] => Array
        (
            [0] => /tmp/phpn3FmFr
            [1] =>
        )

    [error] => Array
        (
            [0] => 0
            [1] => 4
        )

    [size] => Array
        (
            [0] => 15476
            [1] => 0
        )
)

Anyways, here is a fuller example than the sparce one in the documentation above:

<?php
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.”‘.<br/>n”;
        else
            $errormsg .= “Could not move uploaded file ‘”.$tmp_name.”‘ to ‘”.$name.”‘<br/>n”;
    }
    else $errormsg .= “Upload error. [“.$error.”] on file ‘”.$name.”‘<br/>n”;
}
?>

mpyw

4 years ago

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:

<form action=”” method=”post” enctype=”multipart/form-data”>
    <input type=”file” name=”files[x][y][z]”>
    <input type=”submit”>
</form>

As the solution, you should use PSR-7 based zendframework/zend-diactoros.

GitHub:

https://github.com/zendframework/zend-diactoros

Example:

<?phpuse PsrHttpMessageUploadedFileInterface;
use ZendDiactorosServerRequestFactory;$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’);?>

fravadona at gmail dot com

7 months ago

mpyw is right, PSR-7 is awesome but a little overkill for simple projects (in my opinion).

Here’s an example of function that returns the file upload metadata in a (PSR-7 *like*) normalized tree. This function deals with whatever dimension of upload metadata.

I kept the code extremely simple, it doesn’t validate anything in $_FILES, etc… AND MOST IMPORTANTLY, it calls array_walk_recursive in an *undefined behaviour* way!!!

You can test it against the examples of the PSR-7 spec ( https://www.php-fig.org/psr/psr-7/#16-uploaded-files ) and try to add your own checks that will detect the error in the last example ^^

<?php
function getNormalizedFiles()
{
  $normalized = array();

  if ( isset(

$_FILES) ) {
   
    foreach ( $_FILES as $field => $metadata ) {
     
      $normalized[$field] = array(); foreach ( $metadata as $meta => $data ) { if ( is_array($data) ) {
         
          array_walk_recursive($data, function (&$v,$k) use ($meta) { $v = array( $meta => $v ); });
         
          $normalized[$field] = array_replace_recursive($normalized[$field], $data);
       
        } else {
          $normalized[$field][$meta] = $data;
        }
      }
    }
  }
  return $normalized;
}
?>

coreywelch+phpnet at gmail dot com

4 years ago

The documentation doesn’t have any details about how the HTML array feature formats the $_FILES array.

Example $_FILES array:

For single file –

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
                )

            [error] => Array
                (
                    [0] => 0
                    [1] => 0
                )

            [size] => Array
                (
                    [0] => 0
                    [1] => 0
                )

        )

)

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.

<?phpfunction normalize_files_array($files = []) {$normalized_array = [];

        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]
                ];
            }

        }

        return

$normalized_array;

    }

?>

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
                )

        )

)

anon

5 years ago

For clarity; the reason you would NOT want to replace the example script with
$uploaddir = ‘./’;
is because if you have no coded file constraints a nerd could upload a php script with the same name of one of your scripts in the scripts directory.

Given the right settings and permissions php-cgi is capable of replacing even php files.

Imagine if it replaced the upload post processor file itself. The next “upload” could lead to some easy exploits.

Even when replacements are not possible; uploading an .htaccess file could cause some problems, especially if it is sent after the nerd throws in a devious script to use htaccess to redirect to his upload.

There are probably more ways of exploiting it. Don’t let the nerds get you.

More sensible to use a fresh directory for uploads with some form of unique naming algorithm; maybe even a cron job for sanitizing the directory so older files do not linger for too long.

eslindsey at gmail dot com

11 years ago

Also note that since MAX_FILE_SIZE hidden field is supplied by the browser doing the submitting, it is easily overridden from the clients’ side.  You should always perform your own examination and error checking of the file after it reaches you, instead of relying on information submitted by the client.  This includes checks for file size (always check the length of the actual data versus the reported file size) as well as file type (the MIME type submitted by the browser can be inaccurate at best, and intentionally set to an incorrect value at worst).

Anonymous

3 years ago

I have found it useful to re-order the multidimensional $_FILES array into a more intuitive format, as proposed by many other developers already.

Unfortunately, most of the proposed functions are not able to re-order the $_FILES array when it has more than 1 additional dimension.

Therefore, I would like to contribute the function below, which is capable of meeting the aforementioned requirement:

<?php
    function get_fixed_files() {
        $function = function($files, $fixed_files = array(), $path = array()) use (&$function) {
            foreach ($files as $key => $value) {
                $temp = $path;
                $temp[] = $key;
           
                if (is_array($value)) {
                    $fixed_files = $function($value, $fixed_files, $temp);
                } else {
                    $next = array_splice($temp, 1, 1);
                    $temp = array_merge($temp, $next);
                   
                    $new = &$fixed_files;
                   
                    foreach ($temp as $key) {
                        $new = &$new[$key];
                    }
                   
                    $new = $value;
                }
            }
           
            return $fixed_files;
        };
       
        return $function($_FILES);
    }
?>

Side note: the unnamed function within the function is used to avoid confusion regarding the arguments necessary for the recursion within the function, for example when viewing the function in an IDE.

Mark

10 years ago

$_FILES will be empty if a user attempts to upload a file greater than post_max_size in your php.ini

post_max_size should be >= upload_max_filesize in your php.ini.

claude dot pache at gmail dot com

11 years ago

Note that the MAX_FILE_SIZE hidden field is only used by the PHP script which receives the request, as an instruction to reject files larger than the given bound. This field has no significance for the browser, it does not provide a client-side check of the file-size, and it has nothing to do with web standards or browser features.

Age Bosma

9 years ago

“If no file is selected for upload in your form, PHP will return $_FILES[‘userfile’][‘size’] as 0, and $_FILES[‘userfile’][‘tmp_name’] as none.”

Note that the situation above is the same when a file exceeding the MAX_FILE_SIZE hidden field is being uploaded. In this case $_FILES[‘userfile’][‘size’] is also set to 0, and $_FILES[‘userfile’][‘tmp_name’] is also empty. The difference would only be the error code.
Simply checking for these two conditions and assuming no file upload has been attempted is incorrect.

Instead, check if $_FILES[‘userfile’][‘name’] is set or not. If it is, a file upload has at least been attempted (a failed attempt or not). If it is not set, no attempt has been made.

bimal at sanjaal dot com

5 years ago

Some suggestions here:

1. It is always better to check for your error status. If MAX_FILE_SIZE is active and the uploaded file crossed the limit, it will set the error. So, only when error is zero (0), move the file.

2. If possible, never allow your script to upload in the path where file can be downloaded. Point your upload path to outside of public_html area or prevent direct browsing (using .htaccess restrictions). Think, if someone uploads malicious code, specially php codes, they will be executed on the server.

3. Do not use the file name sent by the client. Regenerate a new name for newly uploaded file. This prevents overwriting your old files.

4. Regularly track the disk space consumed, if you are running out of storage.

katrinaelaine6 at gmail dot com

3 years ago

Here’s a complete example of the $_FILES array with nested and non-nested names. Let’s say we have this html form:

<form action=”test.php” method=”post”>

    <input type=”file” name=”single” id=”single”>

    <input type=”file” name=”nested[]”          id=”nested_one”>
    <input type=”file” name=”nested[root]”      id=”nested_root”>        
    <input type=”file” name=”nested[][]”        id=”nested_two”>
    <input type=”file” name=”nested[][parent]”  id=”nested_parent”>
    <input type=”file” name=”nested[][][]”      id=”nested_three”>
    <input type=”file” name=”nested[][][child]” id=”nested_child”>

    <input type=”submit” value=”Submit”>

</form>

In the test.php file:

<?php

    print_r

($_FILES);
    exit;?>

If we upload a text file with the same name as the input id for each input and click submit, test.php will output this:

<?phpArray
(

    [

single] => Array
        (
            [name] => single.txt
            [type] => text/plain
            [tmp_name] => /tmp/phpApO28i
            [error] => 0
            [size] => 3441
        )

    [

nested] => Array
        (
            [name] => Array
                (
                    [0] => nested_one.txt
                    [root] => nested_root.txt
                    [1] => Array
                        (
                            [0] => nested_two.txt
                        )

                    [

2] => Array
                        (
                            [parent] => nested_parent.txt
                        )

                    [

3] => Array
                        (
                            [0] => Array
                                (
                                    [0] => nested_three.txt
                                )

                        )

                    [

4] => Array
                        (
                            [0] => Array
                                (
                                    [child] => nested_child.txt
                                )

                        )

                )

)

)

?>

Источник

(PHP 4, PHP 5, PHP 7)

file — Читает содержимое файла и помещает его в массив

Описание

file
( string $filename
[, int $flags = 0
[, resource $context
]] ) : array

Замечание:

Можно также использовать функцию file_get_contents()
для получения файла в виде строки.

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

filename

Путь к файлу.

Подсказка

Для этой функции вы можете использовать URL в качестве имени файла, если была включена опция fopen wrappers. Смотрите более подробную информацию об определении имени файла в описании функции fopen(). Смотрите также список поддерживаемых оберток URL, их возможности, замечания по использованию и список предопределенных констант в разделе Поддерживаемые протоколы и обертки.

flags

В качестве необязательного параметра flags может
можно указать одну или более следующих констант:

FILE_USE_INCLUDE_PATH

Ищет файл в include_path.

FILE_IGNORE_NEW_LINES

Пропускать новую строку в конце каждого элемента массива

FILE_SKIP_EMPTY_LINES

Пропускать пустые строки

context

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

Замечание: Поддержка контекста была добавлена в PHP 5.0.0. Для описания контекстов смотрите раздел Потоки.

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

Возвращает файл в виде массива. Каждый элемент массива соответствует
строке файла, с символами новой строки включительно. В случае
ошибки file() возвращает FALSE.

Замечание:

Каждая строка в полученном массиве будет завершаться символами конца
строки, если только не используется FILE_IGNORE_NEW_LINES).

Замечание: Если у вас возникают проблемы с распознаванием PHP концов строк при чтении или создании файлов на Macintosh-совместимом компьютере, включение опции auto_detect_line_endings может помочь решить проблему.

Ошибки

Вызывает ошибку уровня E_WARNING, если файл не существует.

Примеры

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

<?php
// Получает содержимое файла в виде массива. В данном примере мы используем
// обращение по протоколу HTTP для получения HTML-кода с удаленного сервера.
$lines = file(‘https://www.example.com/’);// Осуществим проход массива и выведем содержимое в виде HTML-кода вместе с номерами строк.
foreach ($lines as $line_num => $line) {
    echo “Строка #<b>{$line_num}</b> : ” . htmlspecialchars($line) . “<br />n”;
}// Второй пример. Получим содержание веб-страницы в виде одной строки.
// См. также описание функции file_get_contents().
$html = implode(”, file(‘https://www.example.com/’));// Используем необязательный параметр flags (начиная с PHP 5)
$trimmed = file(‘somefile.txt’, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
?>

Примечания

Внимание

При использовании SSL, Microsoft IIS нарушает протокол, закрывая соединение без отправки индикатора close_notify. PHP сообщит об этом как “SSL: Fatal Protocol Error” в тот момент, когда вы достигнете конца данных. Чтобы обойти это, вы должны установить error_reporting на уровень, исключающий E_WARNING. PHP умеет определять, что на стороне сервера находится проблемный IIS при открытии потока с помощью обертки https:// и не выводит предупреждение. Если вы используете fsockopen() для создания ssl:// сокета, вы сами отвечаете за определение и подавление этого предупреждения.

d basin

11 years ago

this may be obvious, but it took me a while to figure out what I was doing wrong. So I wanted to share. I have a file on my “c:” drive. How do I file() it?

Don’t forget the backslash is special and you have to “escape” the backslash i.e. “\”:

<?php

$lines

= file(“C:\Documents and Settings\myfile.txt”);

foreach(

$lines as $line)
{
    echo($line);
}?>

hope this helps…

bingo at dingo dot com

7 years ago

To write all the lines of the file in other words to read the file line by line you can write the code like this:
<?php
$names=file(‘name.txt’);
echo count($names).'<br>’;
foreach($names as $name)
{
   echo $name.'<br>’;
}
?>

this example is so basic to understand how it’s working. I hope it will help many beginners.

Regards,
Bingo

Martin K.

6 years ago

If the file you are reading is in CSV format do not use file(), use fgetcsv().  file() will split the file by each newline that it finds, even newlines that appear within a field (i.e. within quotations).

twichi at web dot de

9 years ago

read from CSV data (file) into an array with named keys

… with or without 1st row = header (keys)
(see 4th parameter of function call as  true / false)

<?php
function csv_in_array($url,$delm=”;”,$encl=”””,$head=false) {
   
    $csvxrow = file($url);   $csvxrow[0] = chop($csvxrow[0]);
    $csvxrow[0] = str_replace($encl,”,$csvxrow[0]);
    $keydata = explode($delm,$csvxrow[0]);
    $keynumb = count($keydata);
   
    if ($head === true) {
    $anzdata = count($csvxrow);
    $z=0;
    for($x=1; $x<$anzdata; $x++) {
        $csvxrow[$x] = chop($csvxrow[$x]);
        $csvxrow[$x] = str_replace($encl,”,$csvxrow[$x]);
        $csv_data[$x] = explode($delm,$csvxrow[$x]);
        $i=0;
        foreach($keydata as $key) {
            $out[$z][$key] = $csv_data[$x][$i];
            $i++;
            }   
        $z++;
        }
    }
    else {
        $i=0;
        foreach($csvxrow as $item) {
            $item = chop($item);
            $item = str_replace($encl,”,$item);
            $csv_data = explode($delm,$item);
            for ($y=0; $y<$keynumb; $y++) {
               $out[$i][$y] = $csv_data[$y];
            }
        $i++;
        }
    }

return

$out;
}?>

fuction call with 4 parameters:

(1) = the file with CSV data (url / string)
(2) = colum delimiter (e.g: ; or | or , …)
(3) = values enclosed by (e.g: ‘ or ” or ^ or …)
(4) = with or without 1st row = head (true/false)

<?php$csvdata = csv_in_array( $yourcsvfile, “;”, “””, true );
echo “<pre>rn”;
print_r($csvdata);
echo “</pre>rn”;
?>

PS: also see: https://php.net/manual/de/function.fgetcsv.php to read CSV data into an array
… and other file-handling methods

^

sheldon at hyperlinked dot com

1 year ago

As of PHP 5.6 the file(), file_get_contents(), and fopen() functions will return false if you are referencing a source URL that doesn’t have a valid SSL certificate. Presumably, you will run into this a lot in your development environments this will drive you crazy.

You will need to create a stream context and provide it as an argument to the various file operations to tell it to ignore invalid SSL credentials.

$args = array(“ssl”=>array(“verify_peer”=>false,”verify_peer_name”=>false),”http”=>array(‘timeout’ => 60, ‘user_agent’ => ‘Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.9) Gecko/20071025 Firefox/3.0.0.1’));

$context = stream_context_create($args);
$httpfile = file($url, false, $context);

lanresmith

3 years ago

Using if ( file(name.txt) ) might not be enough for testing if the file was successfully opened for reading because the file could be empty in which case the array returned is empty, so test instead with !==. e.g.:

$file_array = file(‘test.txt’); // an empty file

echo ‘<pre>’;
if ( $file_array ) {
    # code…
    echo “successn”;
} else {
    # code…
    echo “failuren”; // executed
}

if ( $file_array !== false ) {
    # code…
    echo “successn”; // executed
} else {
    # code…
    echo “failuren”;
}
echo ‘</pre>’;

result:
failure
success

jon+spamcheck at phpsitesolutions dot com

12 years ago

A user suggested using rtrim always, due to the line ending conflict with files that have an EOL that differs from the server EOL.

Using rtrim with it’s default character replacement is a bad solution though, as it removes all whitespace in addition to the ‘r’ and ‘n’ characters.

A good solution using rtrim follows:

<?php
$line = rtrim($line, “rn”) . PHP_EOL;
?>

This removes only EOL characters, and replaces with the server’s EOL character, thus making preg_* work fine when matching the EOL ($)

Anonymous

6 years ago

(“file()’s problem with UTF-16” is wrong. This is updated.
The former may miss the last line of the string.)

file() seems to have a problem in handling
UTF-16 with or without BOM.

file() is likely to think “n”=LF (0A) as a line-ending.
So, not only “000A” but also “010A, 020A,…,FE0A, FF0A,…”
are regarded as line-endings.

Moreover, file() causes a serious problem in UTF-16LE.
file() loses first “0A” (the first half of “0A00”)!
And the next line begins with “00” (the rest of “0A00”).
So lines after the first “0A” are totally different.

To avoid this phenomena,
eg. in case (php_script : UTF-8 , file : UTF-16 with line-ending “rn”),

<?php

mb_regex_encoding

(‘UTF-16’);    $str = file_get_contents($file_path);
$to_encoding = ‘UTF-16’;        $from_encoding = ‘UTF-8’;        $pattern1 = mb_convert_encoding(‘[^r]*rn’, $to_encoding, $from_encoding);
mb_ereg_search_init($str, $pattern1);
while ($res = mb_ereg_search_regs()) {
    $file[] = $res[0];
}
$pattern2 = mb_convert_encoding(‘A.*rn(.*)z’, $to_encoding, $from_encoding);
mb_ereg($pattern2, $str, $match);
    $file[] = $match[1];?>

instead of
$file = file($file_path);

If line-ending is “n”,
$pattern1 = mb_convert_encoding(‘[^n]*n’, $to_encoding, $from_encoding);

marco dot remy at aol dot com

6 years ago

Here’s my CSV converter
supports Header and trims all fields
Note: Headers must be not empty!

<?phpfunction csv2array($file, $delim = ‘;’, $encl = ‘”‘, $header = false) {
   
    if(!file_exists($file))
        return false;
   
    $file_lines = file($file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
   
    if($file_lines === array())
        return NULL;
   
    if($header === true) {
        $line_header = array_shift($file_lines);
        $array_header = array_map(‘trim’, str_getcsv($line_header, $delim, $encl));
    }$out = NULL;foreach ($file_lines as $line) {
        if(trim($line) === ”)
            continue;
       
        $array_fields = array_map(‘trim’, str_getcsv($line, $delim, $encl));
       
        if($header === true)
            $out[] = array_combine ($array_header, $array_fields);
        else
            $out[] = $array_fields;
    }
   
    return $out;
}
?>

Reversed: moc dot liamg at senroc dot werdna

13 years ago

This note applies to PHP 5.1.6 under Windows (although may apply to other versions).

It appears that the ‘FILE_IGNORE_NEW_LINES’ flag doesn’t remove newlines properly when reading Windows-style text files, i.e. files whose lines end in ‘rn’.

Solution: Always use ‘rtrim()’ in preference to ‘FILE_IGNORE_NEW_LINES’.

vbchris at gmail dot com

12 years ago

If you’re getting “failed to open stream: Permission denied” when trying to use either file() or fopen() to access files on another server. Check your host doesn’t have any firewall restrictions in-place which prevent outbound connections. This is the case with my host Aplus.net

justin at visunet dot ie

17 years ago

Note: Now that file() is binary safe it is ‘much’ slower than it used to be. If you are planning to read large files it may be worth your while using fgets() instead of file() For example:

<?php

$fd = fopen (“log_file.txt”, “r”);

while (!feof ($fd))

{

   $buffer = fgets($fd, 4096);

   $lines[] = $buffer;

}

fclose ($fd);

?>

The resulting array is $lines.

I did a test on a 200,000 line file. It took seconds with fgets()  compared to minutes with file().

info at carstanje dot com

13 years ago

Using file() for reading large text files > 10 Mb gives problems, therefore you should use this instead. It is much slower but it works fine. $lines will return an array with all the lines.

<?php

$handle = @fopen(‘yourfile…’, “r”);

if ($handle) {

   while (!feof($handle)) {

       $lines[] = fgets($handle, 4096);

   }

   fclose($handle);

}

?>

Источник