Php передать переменные в подключаемый файл
но если я опущу '?page=$page_no part' из аргумента функции require не отображается ошибка или предупреждение.
мне нужно передать переменную, когда я использую функцию require ().
require() и include() откроет файл, соответствующий пути / имени, которое они получают.
что означает, что с вашим кодом у вас должен быть файл с именем diggstyle_code.php?page=1 на диске. Очевидно, что это не так, поэтому он терпит неудачу.
со ссылкой на переменная страница руководства по PHP:
область переменной-это контекст, в котором она определена. По большей части все переменные PHP имеют только одну область. эта область охватывает включенные и необходимые файлы, а также.
в вашем случае, вам не нужно проходить переменной. Если у вас есть переменная в текущем скрипте, она также будет существовать в скрипте, который вы включаете,вне функций, которые имеют свой собственный объем.
в вашем основном скрипте вы должны иметь:
помните, что включение / требование файла точно так же, как копирование-вставка его содержимого в строку, которая требуется.
это должно работать, но это довольно грязный хак:
вы, наверное, хотите выполнить рефакторинг кода, чтобы использовать функции и/или объекты и вызывать их из ваших файлов, а не включая их (спагетти код оповещения)
require не извлекает файл с веб-сервера - вместо этого он должен ссылаться на файл в файловой системе.
вызов include или require просто говорит PHP вставить содержимое данного файла в ваш код в этом месте, не более того.
Если ваша переменная является глобальной, нет необходимости "передавать"ее, она уже есть: область переменных PHP.
ответ тогда: ничего не делайте, если $page_no существует в файле, в котором вы вызываете require (), он будет доступен в включенном файле.
require, require_once, include и include_once попробуйте включить файлы из файловой системы в текущий файл.
Так как нет файлов с именем diggstyle_code.РНР?page=1, вполне логично, что PHP не может его найти.
вы не можете передавать значения таким образом, однако любая переменная, объявленная в текущем файле, будет доступна в включенных файлах.
если я правильно понял, вам нужно вызвать файл diggstyle_code.php передача аргументов, так что никто не может назвать этот файл и заставить его работать, а не ваш основной файл. Я прав?
таким образом, предположим, что ваш "главный".php " имеет строки
это означает, что: если кто-нибудь позвонит "main.РНР" получает diggstyle_code.php работает. Но если кто-нибудь каким-либо образом звонит прямо diggstyle_code.php Он / она ничего не получит.
если я прав в своем понимании, способ достигните этого, чтобы включить в основной файл переменную или константу, которая будет ограничена diggstyle_code.php
так, например: 'main.на PHP'
и теперь diggstyle_code.php
хотя этот вопрос старый, есть еще один вариант, который я использую, который пропал из этой темы. Вы можете вернуть функцию из требуемого файла, которая принимает аргументы, которые вы хотите передать:
и вызовите его с аргументами, когда вы require это:
Удалённые файлы могут быть обработаны на удалённой стороне (в зависимости от расширения файла и того, что удалённый сервер выполняет скрипты PHP или нет), но это всё равно должно производить корректный скрипт PHP, потому что он будет затем обработан уже на локальном сервере. Если файл с удалённого сервера должен быть обработан и только отображён его результат, гораздо эффективно воспользоваться функцией readfile() В противном случае следует соблюдать особую осторожность, чтобы обезопасить удалённый скрипт для получения корректного и желаемого кода.
Смотрите также раздел Удалённые файлы, функции fopen() и file() для дополнительной информации.
Обработка возвращаемых значений: оператор include возвращает значение FALSE в случае возникновения ошибки и выдаёт предупреждение. Успешные включения, пока это не переопределено во включаемом файле, возвращают значение 1 . Возможно выполнить выражение return внутри включаемого файла, чтобы завершить процесс выполнения в этом файле и вернуться к выполнению включающего файла. Кроме того, возможно вернуть значение из включаемых файлов. Вы можете получить значение включения, как если бы вы вызвали обычную функцию. Хотя это невозможно при включении удалённого файла, только если вывод удалённого файла не содержит корректные теги начала и конца PHP кода (так же, как и локальный файл). Вы можете определить необходимые переменные внутри этих тегов и они будут представлены в зависимости от того, какой файл был выключен.
Так как include - это специальная языковая конструкция, круглые скобки не обязательны вокруг аргумента. Будьте внимательны при сравнении возвращаемого значения.
// не сработает, интерпретируется как include(('vars.php') == TRUE), то есть include('1')
if (include( 'vars.php' ) == TRUE ) echo 'OK' ;
>
// сработает
if ((include 'vars.php' ) == TRUE ) echo 'OK' ;
>
?>
$foo = include 'return.php' ;
echo $foo ; // выведет 'PHP'
$bar = include 'noreturn.php' ;
echo $bar ; // выведет 1
$bar имеет значение 1 , т.к. включение файла произошло успешно. Заметьте разницу между примерами сверху. Первый использует return внутри включаемого файла, тогда как второй не использует. Если файл не может быть включён, возвращается false и возникает E_WARNING .
Если во включаемом файле определены функции, они могут быть использованы в главном файле вне зависимости от того, были ли они объявлены до return или после. Если файл включается дважды, PHP выдаст фатальную ошибку, потому что функции уже были определены. Рекомендуется использовать include_once вместо того, чтобы проверять был ли файл уже включён.
Другой путь "включить" PHP-файл в переменную - это захватить вывод с помощью функций контроля вывода вместе с include . Например:
$string = get_include_contents ( 'somefile.php' );
?phpfunction get_include_contents ( $filename ) if ( is_file ( $filename )) ob_start ();
include $filename ;
return ob_get_clean ();
>
return false ;
>
Для того, чтобы включать файлы автоматически в скрипты, обратите внимание на конфигурационные директивы auto_prepend_file и auto_append_file в php.ini .
Замечание: Поскольку это языковая конструкция, а не функция, она не может вызываться при помощи переменных функций или именованных аргументов.
Как работает подключение кода PHP
Интерпретатор php «читает» код сверху вниз и слева направо, как мы читаем книги на русском языке. На исполнение от сервера ему указывается файл "index.php", а значит, чтение начинается с него. Дойдя до строчки с `include 'test/1.php'`, интерпретатор пытается найти и исполнить это файл так, как будто он является частью "index.php".
Перед подключением и исполнением файла "1.php" уже существует переменная `$say`, в которой содержится 'Hello world!'. При выполнении файла "1.php", содержимое этой переменной выводится на экран и создается переменная `$test`, которая в свою очередь и выводится на экран в файле `index.php`.
Если описанное выше непонятно, советую немного поиграться с файлами `1.php` и `index.php` создавая и выводя в них переменные.
Список изменений
Версия | Описание |
---|---|
7.2.34, 7.3.23, 7.4.11 | имена входящих cookie больше не декодируются из URL-закодированной строки из соображений безопасности. |
Как подключить PHP из другой директории
Теперь изменим условия. Переместим файл `1.php` в папку с названием `test`, которую создадим в директории с файлом `index.php`.
Поскольку подключаемый файл находится в другой директории, для его подключения следует указать сначала папку, в которой он находится, а потом и сам файл.
Далее изменим код в `index.php`.
Строка, что мы указываем после инструкции `include`, это путь к файлу. Он может быть относительный (к файлу, где используется подключение) и абсолютным (от корня файловой системы). В приложениях рекомендуются использовать относительные пути.
Между папками, файлами и другими папками в пути устанавливаются разделители. Универсальный разделитель для различных операционных систем – `/`.
Если в папке `test` у нас была бы еще папка `lot`, в которой лежал файл `1.php`, то относительный путь выглядел бы так: 'test/lot/1.php'.
С путями немного разобрались – возвращаемся к инструкциям. Произведем изменения в файлах. Файл "index.php":
Посмотрим на изменение в выводе:
Примеры
$file = 'people.txt' ;
// Открываем файл для получения существующего содержимого
$current = file_get_contents ( $file );
// Добавляем нового человека в файл
$current .= "John Smith\n" ;
// Пишем содержимое обратно в файл
file_put_contents ( $file , $current );
?>?php
$file = 'people.txt' ;
// Новый человек, которого нужно добавить в файл
$person = "John Smith\n" ;
// Пишем содержимое в файл,
// используя флаг FILE_APPEND для дописывания содержимого в конец файла
// и флаг LOCK_EX для предотвращения записи данного файла кем-нибудь другим в данное время
file_put_contents ( $file , $person , FILE_APPEND | LOCK_EX );
?>?php
Подведём итоги
Чтобы подключить PHP-файлы, можно воспользоваться четырьмя похожими инструкциями — `include` и `include_once`, `require` и `require_once`.
- Разница между `include` и `require`: при отсутствии файла последняя выводит фатальную ошибку, а первая — нет.
- Разница между `include` и `include_once` (а также `require` и `require_once` соответственно): инструкции с “once” проверяют перед подключением, был ли этот файл подключен ранее. Если он подключался, повторного подключения не произойдет.
- Разница между `require_once` и `include_once`: думаю, она понятна из двух предыдущих пунктов :)
Если вы хотите освоить PHP во всей его полноте — приглашаем вас на курсы PHP-разработки в GeekBrains. За шесть месяцев вы изучите не только работу с PHP, но и другие важные в профессии технологии — фреймворк Laravel, базы данных MS SQL и Postgre SQL, основы HTML/CSS и ООП. А также сможете пройти полноценную онлайн-стажировку!
Смотрите также
- fopen() - Открывает файл или URL
- fwrite() - Бинарно-безопасная запись в файл
- file_get_contents() - Читает содержимое файла в строку
- stream_context_create() - Создаёт контекст потока
Точки в именах приходящих переменных
Как правило, PHP не меняет передаваемых скрипту имён переменных. Однако следует отметить, что точка не является корректным символом в имени переменной PHP. Поэтому рассмотрим такую запись:
В данном случае интерпретатор видит переменную $varname , после которой идёт оператор конкатенации, а затем голая строка (то есть, не заключённая в кавычки строка, не соответствующая ни одному из ключевых или зарезервированных слов) 'ext'. Очевидно, что это не даст ожидаемого результата.
По этой причине важно отметить, что PHP будет автоматически заменять любые точки в именах, приходящих переменных на символы подчёркивания.
Определение типов переменных
Поскольку PHP определяет типы переменных и преобразует их (как правило) по мере необходимости, не всегда очевидно, какой тип имеет данная переменная в любой момент времени. PHP содержит несколько функций, позволяющих определить тип переменной, таких как: gettype() , is_array() , is_float() , is_int() , is_object() и is_string() . Смотрите также раздел Типы.
HTTP является текстовым протоколом, и большинство, если не всё, содержимое, которое приходит в суперглобальные массивы, например, $_POST и $_GET , останется в виде строк. PHP не будет преобразовывать значения в определённый тип. В приведённом ниже примере $_GET["var1"] будет содержать строку "null", а $_GET["var2"] - строку "123".
User Contributed Notes 30 notes
The full list of field-name characters that PHP converts to _ (underscore) is the following (not just dot):
chr(32) ( ) (space)
chr(46) (.) (dot)
chr(91) ([) (open square bracket)
chr(128) - chr(159) (various)
PHP irreversibly modifies field names containing these characters in an attempt to maintain compatibility with the deprecated register_globals feature.
Important: Pay attention to the following security concerns when handling user submitted data :
This post is with regards to handling forms that have more than one submit button.
Suppose we have an HTML form with a submit button specified like this:
Normally the 'value' attribute of the HTML 'input' tag (in this case "Delete") that creates the submit button can be accessed in PHP after post like this:
$_POST [ 'action_button' ];
?>
We of course use the 'name' of the button as an index into the $_POST array.
This works fine, except when we want to pass more information with the click of this particular button.
Imagine a scenario where you're dealing with user management in some administrative interface. You are presented with a list of user names queried from a database and wish to add a "Delete" and "Modify" button next to each of the names in the list. Naturally the 'value' of our buttons in the HTML form that we want to display will be "Delete" and "Modify" since that's what we want to appear on the buttons' faceplates.
Both buttons (Modify and Delete) will be named "action_button" since that's what we want to index the $_POST array with. In other words, the 'name' of the buttons along cannot carry any uniquely identifying information if we want to process them systematically after submit. Since these buttons will exist for every user in the list, we need some further way to distinguish them, so that we know for which user one of the buttons has been pressed.
Using arrays is the way to go. Assuming that we know the unique numerical identifier of each user, such as their primary key from the database, and we DON'T wish to protect that number from the public, we can make the 'action_button' into an array and use the user's unique numerical identifier as a key in this array.
Our HTML code to display the buttons will become:
The 0000000002 is of course the unique numerical identifier for this particular user.
Then when we handle this form in PHP we need to do the following to extract both the 'value' of the button ("Delete" or "Modify") and the unique numerical identifier of the user we wish to affect (0000000002 in this case). The following will print either "Modify" or "Delete", as well as the unique number of the user:
$submitted_array = array_keys ( $_POST [ 'action_button' ]);
echo ( $_POST [ 'action_button' ][ $submitted_array [ 0 ]] . " " . $submitted_array [ 0 ]);
?>
$submitted_array[0] carries the 0000000002.
When we index that into the $_POST['action_button'], like we did above, we will extract the string that was used as 'value' in the HTML code 'input' tag that created this button.
If we wish to protect the unique numerical identifier, we must use some other uniquely identifying attribute of each user. Possibly that attribute should be encrypted when output into the form for greater security.
Функция идентична последовательным успешным вызовам функций fopen() , fwrite() и fclose() .
Если filename не существует, файл будет создан. Иначе, существующий файл будет перезаписан, за исключением случая, если указан флаг FILE_APPEND .
User Contributed Notes 21 notes
This might be useful:
include $_SERVER [ 'DOCUMENT_ROOT' ]. "/lib/sample.lib.php" ;
?>
So you can move script anywhere in web-project tree without changes.
If you want to have include files, but do not want them to be accessible directly from the client side, please, please, for the love of keyboard, do not do this:
// check if what is defined and die if not
?>
The reason you should not do this is because there is a better option available. Move the includeFile(s) out of the document root of your project. So if the document root of your project is at "/usr/share/nginx/html", keep the include files in "/usr/share/nginx/src".
include __DIR__ . '/../src/includeFile.php' ;
?>
Since user can't type 'your.site/../src/includeFile.php', your includeFile(s) would not be accessible to the user directly.
Before using php's include, require, include_once or require_once statements, you should learn more about Local File Inclusion (also known as LFI) and Remote File Inclusion (also known as RFI).
The LFI and RFI vulnerabilities occur when you use an input variable in the include statement without proper input validation. Suppose you have an example.php with code:
// Bad Code
$path = $_GET [ 'path' ];
include $path . 'example-config-file.php' ;
?>
As a programmer, you might expect the user to browse to the path that you specify.
The example.php would download my evil.txt and process the operating system command that I passed in as the command variable. In this case, it is whoami. I ended the path variable with a %00, which is the null character. The original include statement in the example.php would ignore the rest of the line. It should tell me who the web server is running as.
Please use proper input validation if you use variables in an include statement.
I cannot emphasize enough knowing the active working directory. Find it by: echo getcwd();
Remember that if file A includes file B, and B includes file C; the include path in B should take into account that A, not B, is the active working directory.
When including a file using its name directly without specifying we are talking about the current working directory, i.e. saying (include "file") instead of ( include "./file") . PHP will search first in the current working directory (given by getcwd() ) , then next searches for it in the directory of the script being executed (given by __dir__).
This is an example to demonstrate the situation :
We have two directory structure :
-dir1
----script.php
----test
----dir1_test
-dir2
----test
----dir2_test
dir1/test contains the following text :
This is test in dir1
dir2/test contains the following text:
This is test in dir2
dir1_test contains the following text:
This is dir1_test
dir2_test contains the following text:
This is dir2_test
script.php contains the following code:
echo 'Directory of the current calling script: ' . __DIR__ ;
echo '
' ;
echo 'Current working directory: ' . getcwd ();
echo '
' ;
echo 'including "test" . ' ;
echo '
' ;
include 'test' ;
echo '
' ;
echo 'Changing current working directory to dir2' ;
chdir ( '../dir2' );
echo '
' ;
echo 'Directory of the current calling script: ' . __DIR__ ;
echo '
' ;
echo 'Current working directory: ' . getcwd ();
echo '
' ;
echo 'including "test" . ' ;
echo '
' ;
include 'test' ;
echo '
' ;
echo 'including "dir2_test" . ' ;
echo '
' ;
include 'dir2_test' ;
echo '
' ;
echo 'including "dir1_test" . ' ;
echo '
' ;
include 'dir1_test' ;
echo '
' ;
echo 'including "./dir1_test" . ' ;
echo '
' ;
(@include './dir1_test' ) or die( 'couldn\'t include this file ' );
?>
The output of executing script.php is :
Directory of the current calling script: C:\dev\www\php_experiments\working_directory\example2\dir1
Current working directory: C:\dev\www\php_experiments\working_directory\example2\dir1
including "test" .
This is test in dir1
Changing current working directory to dir2
Directory of the current calling script: C:\dev\www\php_experiments\working_directory\example2\dir1
Current working directory: C:\dev\www\php_experiments\working_directory\example2\dir2
including "test" .
This is test in dir2
including "dir2_test" .
This is dir2_test
including "dir1_test" .
This is dir1_test
including "./dir1_test" .
couldn't include this file
If you're doing a lot of dynamic/computed includes (>100, say), then you may well want to know this performance comparison: if the target file doesn't exist, then an @include() is *ten* *times* *slower* than prefixing it with a file_exists() check. (This will be important if the file will only occasionally exist - e.g. a dev environment has it, but a prod one doesn't.)
As a rule of thumb, never include files using relative paths. To do this efficiently, you can define constants as follows:
----
define ( 'MAINDIR' , dirname ( __FILE__ ) . '/' );
define ( 'DL_DIR' , MAINDIR . 'downloads/' );
define ( 'LIB_DIR' , MAINDIR . 'lib/' );
?>
----
and so on. This way, the files in your framework will only have to issue statements such as this:
require_once( LIB_DIR . 'excel_functions.php' );
?>
This also frees you from having to check the include path each time you do an include.
If you're running scripts from below your main web directory, put a prepend.php file in each subdirectory:
--
include( dirname ( dirname ( __FILE__ )) . '/prepend.php' );
?>
--
This way, the prepend.php at the top always gets executed and you'll have no path handling headaches. Just remember to set the auto_prepend_file directive on your .htaccess files for each subdirectory where you have web-accessible scripts.
Ideally includes should be kept outside of the web root. That's not often possible though especially when distributing packaged applications where you don't know the server environment your application will be running in. In those cases I use the following as the first line.
( __FILE__ != $_SERVER['SCRIPT_FILENAME'] ) or exit ( 'No' );
It's worth noting that PHP provides an OS-context aware constant called DIRECTORY_SEPARATOR. If you use that instead of slashes in your directory paths your scripts will be correct whether you use *NIX or (shudder) Windows. (In a semi-related way, there is a smart end-of-line character, PHP_EOL)
Example:
$cfg_path
= 'includes'
. DIRECTORY_SEPARATOR
. 'config.php'
;
require_once( $cfg_path );
I would like to point out the difference in behavior in IIS/Windows and Apache/Unix (not sure about any others, but I would think that any server under Windows will be have the same as IIS/Windows and any server under Unix will behave the same as Apache/Unix) when it comes to path specified for included files.
Consider the following:
include '/Path/To/File.php' ;
?>
In IIS/Windows, the file is looked for at the root of the virtual host (we'll say C:\Server\Sites\MySite) since the path began with a forward slash. This behavior works in HTML under all platforms because browsers interpret the / as the root of the server.
However, Unix file/folder structuring is a little different. The / represents the root of the hard drive or current hard drive partition. In other words, it would basically be looking for root:/Path/To/File.php instead of serverRoot:/Path/To/File.php (which we'll say is /usr/var/www/htdocs). Thusly, an error/warning would be thrown because the path doesn't exist in the root path.
I just thought I'd mention that. It will definitely save some trouble for those users who work under Windows and transport their applications to an Unix-based server.
A work around would be something like:
$documentRoot = null ;
if (isset( $_SERVER [ 'DOCUMENT_ROOT' ])) $documentRoot = $_SERVER [ 'DOCUMENT_ROOT' ];
if ( strstr ( $documentRoot , '/' ) || strstr ( $documentRoot , '\\' )) if ( strstr ( $documentRoot , '/' )) $documentRoot = str_replace ( '/' , DIRECTORY_SEPARATOR , $documentRoot );
>
elseif ( strstr ( $documentRoot , '\\' )) $documentRoot = str_replace ( '\\' , DIRECTORY_SEPARATOR , $documentRoot );
>
>
if ( preg_match ( '/[^\\/]\\[^\\/]/' , $documentRoot )) $documentRoot = preg_replace ( '/([^\\/])\\([^\\/])/' , '\\1DIR_SEP\\2' , $documentRoot );
$documentRoot = str_replace ( 'DIR_SEP' , '\\\\' , $documentRoot );
>
>
else /**
* I usually store this file in the Includes folder at the root of my
* virtual host. This can be changed to wherever you store this file.
*
* Example:
* If you store this file in the Application/Settings/DocRoot folder at the
* base of your site, you would change this array to include each of those
* folders.
*
*
* $directories = array(
* 'Application',
* 'Settings',
* 'DocRoot'
* );
*
*/
$directories = array(
'Includes'
);
if ( defined ( '__DIR__' )) $currentDirectory = __DIR__ ;
>
else $currentDirectory = dirname ( __FILE__ );
>
$currentDirectory = rtrim ( $currentDirectory , DIRECTORY_SEPARATOR );
$currentDirectory = $currentDirectory . DIRECTORY_SEPARATOR ;
foreach ( $directories as $directory ) $currentDirectory = str_replace (
DIRECTORY_SEPARATOR . $directory . DIRECTORY_SEPARATOR ,
DIRECTORY_SEPARATOR ,
$currentDirectory
);
>
$currentDirectory = rtrim ( $currentDirectory , DIRECTORY_SEPARATOR );
>
define ( 'SERVER_DOC_ROOT' , $documentRoot );
?>
Using this file, you can include files using the defined SERVER_DOC_ROOT constant and each file included that way will be included from the correct location and no errors/warnings will be thrown.
Когда происходит отправка данных формы PHP-скрипту, информация из этой формы автоматически становится доступной ему. Существует несколько способов получения этой информации, например:
Есть только два способа получить доступ к данным из форм HTML. Доступные сейчас способы приведены ниже:
Замечание:
Точки и пробелы в именах переменных преобразуется в знаки подчёркивания. Например, станет $_REQUEST["a_b"] .
PHP также понимает массивы в контексте переменных формы (смотрите соответствующие ЧАВО). К примеру, вы можете сгруппировать связанные переменные вместе или использовать эту возможность для получения значений списка множественного выбора select. Например, давайте отправим форму самой себе, а после отправки отобразим данные:
Замечание: Если внешнее имя переменной начинается с корректного синтаксиса массива, завершающие символы молча игнорируются. Например, станет $_REQUEST['foo']['bar'] .
Имена переменных кнопки-изображения
При отправке формы вместо стандартной кнопки можно использовать изображение с помощью тега такого вида:
Когда пользователь щёлкнет где-нибудь на изображении, соответствующая форма будет передана на сервер с двумя дополнительными переменными - sub_x и sub_y . Они содержат координаты нажатия пользователя на изображение. Опытные программисты могут заметить, что на самом деле имена переменных, отправленных браузером, содержат точку, а не подчёркивание, но PHP автоматически преобразует точку в подчёркивание.
Замечание: Начиная с PHP 7.2.34, 7.3.23 и 7.4.11, соответственно, имена входящих cookie больше не декодируются из URL-закодированной строки из соображений безопасности.
Если вы хотите присвоить множество значений одной переменной cookie, вы можете присвоить их как массив. Например:
setcookie ( "MyCookie[foo]" , 'Testing 1' , time ()+ 3600 );
setcookie ( "MyCookie[bar]" , 'Testing 2' , time ()+ 3600 );
?>?php
Это создаст две разные cookie, хотя в вашем скрипте MyCookie будет теперь одним массивом. Если вы хотите установить именно одну cookie со множеством значений, сначала рассмотрите возможность использования к значениям такие функции, как serialize() или explode() .
Обратите внимание, что cookie заменит предыдущую cookie с тем же именем в вашем браузере, если только путь или домен не отличаются. Так, для приложения корзины покупок вы, возможно, захотите сохранить счётчик. То есть:
if (isset( $_COOKIE [ 'count' ])) $count = $_COOKIE [ 'count' ] + 1 ;
> else $count = 1 ;
>
setcookie ( 'count' , $count , time ()+ 3600 );
setcookie ( "Cart[ $count ]" , $item , time ()+ 3600 );
?>?php
User Contributed Notes 37 notes
File put contents fails if you try to put a file in a directory that doesn't exist. This creates the directory.
function file_force_contents ( $dir , $contents ) $parts = explode ( '/' , $dir );
$file = array_pop ( $parts );
$dir = '' ;
foreach( $parts as $part )
if(! is_dir ( $dir .= "/ $part " )) mkdir ( $dir );
file_put_contents ( " $dir / $file " , $contents );
>
?>
It should be obvious that this should only be used if you're making one write, if you are writing multiple times to the same file you should handle it yourself with fopen and fwrite, the fclose when you are done writing.
file_put_contents() for 1,000,000 writes - average of 3 benchmarks:
real 0m3.932s
user 0m2.487s
sys 0m1.437s
fopen() fwrite() for 1,000,000 writes, fclose() - average of 3 benchmarks:
real 0m2.265s
user 0m1.819s
sys 0m0.445s
function file_force_contents ( $fullPath , $contents , $flags = 0 ) $parts = explode ( '/' , $fullPath );
array_pop ( $parts );
$dir = implode ( '/' , $parts );
if( ! is_dir ( $dir ) )
mkdir ( $dir , 0777 , true );
file_put_contents ( $fullPath , $contents , $flags );
>
file_force_contents ( ROOT . '/newpath/file.txt' , 'message' , LOCK_EX );
?>
Please note that when saving using an FTP host, an additional stream context must be passed through telling PHP to overwrite the file.
/* set the FTP hostname */
$user = "test" ;
$pass = "myFTP" ;
$host = "example.com" ;
$file = "test.txt" ;
$hostname = $user . ":" . $pass . "@" . $host . "/" . $file ;
/* the file content */
$content = "this is just a test." ;
/* create a stream context telling PHP to overwrite the file */
$options = array( 'ftp' => array( 'overwrite' => true ));
$stream = stream_context_create ( $options );
/* and finally, put the contents */
file_put_contents ( $hostname , $content , 0 , $stream );
?>
It's important to understand that LOCK_EX will not prevent reading the file unless you also explicitly acquire a read lock (shared locked) with the PHP 'flock' function.
i.e. in concurrent scenarios file_get_contents may return empty if you don't wrap it like this:
$myfile = fopen ( 'test.txt' , 'rt' );
flock ( $myfile , LOCK_SH );
$read = file_get_contents ( 'test.txt' );
fclose ( $myfile );
?>
If you have code that does a file_get_contents on a file, changes the string, then re-saves using file_put_contents, you better be sure to do this correctly or your file will randomly wipe itself out.
Make sure not to corrupt anything in case of failure.
function file_put_contents_atomically ( $filename , $data , $flags = 0 , $context = null ) if ( file_put_contents ( $filename . "~" , $data , $flags , $context ) === strlen ( $contents )) return rename ( $filename . "~" , $filename , $context );
>
@ unlink ( $filename . "~" , $context );
return FALSE ;
>
This functionality is now implemented in the PEAR package PHP_Compat.
More information about using this function without upgrading your version of PHP can be found on the below link:
It's worth noting that you must make sure to use the correct path when working with this function. I was using it to help with logging in an error handler and sometimes it would work - while other times it wouldn't. In the end it was because sometimes it was called from different paths resulting in a failure to write to the log file.
__DIR__ is your friend.
File put contents fails if you try to put a file in a directory that doesn't exist. This function creates the directory.
file_force_contents ( 'test1.txt' , 'test1 content' ); // test1.txt created
file_force_contents ( 'test2/test2.txt' , 'test2 content' );
// test2/test2.txt created "test2" folder.
file_force_contents ( '~/test3/test3.txt' , 'test3 content' );
// /path/to/user/directory/test3/test3.txt created "test3" folder in user directory (check on linux "ll ~/ | grep test3").
?>
In reply to the previous note:
If you want to emulate this function in PHP4, you need to return the bytes written as well as support for arrays, flags.
I can only figure out the FILE_APPEND flag and array support. If I could figure out "resource context" and the other flags, I would include those too.
define('FILE_APPEND', 1);
function file_put_contents($n, $d, $flag = false) $mode = ($flag == FILE_APPEND || strtoupper($flag) == 'FILE_APPEND') ? 'a' : 'w';
$f = @fopen($n, $mode);
if ($f === false) return 0;
> else if (is_array($d)) $d = implode($d);
$bytes_written = fwrite($f, $d);
fclose($f);
return $bytes_written;
>
>
A more simplified version of the method that creates subdirectories:
function path_put_contents($filePath, $contents, $flags = 0)
if (! is_dir($dir = implode('/', explode('/', $filePath, -1))))
mkdir($dir, 0777, true);
file_put_contents($filePath, $contents, $flags);
>
To upload file from your localhost to any FTP server.
pease note 'ftp_chdir' has been used instead of putting direct remote file path. in ftp_put . remoth file should be only file name
$host = '*****' ;
$usr = '*****' ;
$pwd = '**********' ;
$local_file = './orderXML/order200.xml' ;
$ftp_path = 'order200.xml' ;
$conn_id = ftp_connect ( $host , 21 ) or die ( "Cannot connect to host" );
ftp_pasv ( $resource , true );
ftp_login ( $conn_id , $usr , $pwd ) or die( "Cannot login" );
// perform file upload
ftp_chdir ( $conn_id , '/public_html/abc/' );
$upload = ftp_put ( $conn_id , $ftp_path , $local_file , FTP_ASCII );
if( $upload ) < $ftpsucc = 1 ; >else < $ftpsucc = 0 ; >
// check upload status:
print (! $upload ) ? 'Cannot upload' : 'Upload complete' ;
print "\n" ;
// close the FTP stream
ftp_close ( $conn_id );
?>
I'm updating a function that was posted, as it would fail if there was no directory. It also returns the final value so you can determine if the actual file was written.
public static function file_force_contents($dir, $contents) $parts = explode('/', $dir);
$file = array_pop($parts);
$dir = '';
foreach($parts as $part) if (! is_dir($dir .= "/")) mkdir($dir);
>
return file_put_contents("", $contents);
>
I suggest to expand file_force_contents() function of TrentTompkins at gmail dot com by adding verification if patch is like: "../foo/bar/file"
if (strpos($dir, "../") === 0)
$dir = str_replace("..", substr(__DIR__, 0, strrpos(__DIR__, "/")), $dir);
file_put_contents does not issue an error message if file name is incorrect(for example has improper symbols on the end of it /n,/t)
that is why use trim() for file name.
$name=trim($name);
file_put_contents($name,$content);
I had some troubles using file_put_contents with an absolute but no canonicalized path (eg. w:/htdocs/pri/../test/log.txt): on windows environment php was unable to create the file also using the realpath function .
I had to use fopen and frwite functions to write the data.
I wrote this script implementing the file_put_contents() and file_get_contents() functions to be compatible with both php4.* and php 5.*. It is a PHP Command line interface script which searches and replaces a specific word recursively through all files in the supplied directory hierarchy.
Usage from a Linux command line: ./scriptname specifieddirectory searchString replaceString
if( $argc != 4 )
echo "This command replaces a search string with a replacement string\n for the contents of all files in a directory hierachy\n" ;
echo "command usage: $argv [ 0 ] directory searchString replaceString\n" ;
echo "\n" ;
exit;
>
?>
if (! function_exists ( 'file_put_contents' )) function file_put_contents ( $filename , $data ) $f = @ fopen ( $filename , 'w' );
if (! $f ) return false ;
> else $bytes = fwrite ( $f , $data );
fclose ( $f );
return $bytes ;
>
>
>
function get_file_contents ( $filename )
/* Returns the contents of file name passed
*/
if (! function_exists ( 'file_get_contents' ))
$fhandle = fopen ( $filename , "r" );
$fcontents = fread ( $fhandle , filesize ( $filename ));
fclose ( $fhandle );
>
else
$fcontents = file_get_contents ( $filename );
>
return $fcontents ;
>
?>
function openFileSearchAndReplace ( $parentDirectory , $searchFor , $replaceWith )
//echo "debug here- line 1a\n";
//echo "$parentDirectory\n";
//echo "$searchFor\n";
//echo "$replaceWith\n";
if ( $handle = opendir ( " $parentDirectory " )) while ( false !== ( $file = readdir ( $handle ))) if (( $file != "." && $file != ".." ) && ! is_dir ( $file )) chdir ( " $parentDirectory " ); //to make sure you are always in right directory
// echo "$file\n";
$holdcontents = file_get_contents ( $file );
$holdcontents2 = str_replace ( $searchFor , $replaceWith , $holdcontents );
file_put_contents ( $file , $holdcontents2 );
// echo "debug here- line 1\n";
// echo "$file\n";
>
if( is_dir ( $file ) && ( $file != "." && $file != ".." ))
$holdpwd = getcwd ();
//echo "holdpwd = $holdpwd \n";
$newdir = " $holdpwd " . "/ $file " ;
//echo "newdir = $newdir \n"; //for recursive call
openFileSearchAndReplace ( $newdir , $searchFor , $replaceWith );
//echo "debug here- line 2\n";
//echo "$file\n";
>
>
closedir ( $handle );
>
>
$parentDirectory2 = $argv [ 1 ];
$searchFor2 = $argv [ 2 ];
$replaceWith2 = $argv [ 3 ];
//Please do not edit below to keep the rights to this script
//Free license, if contents below this line is not edited
echo "REPLACED\n' $searchFor2 ' with ' $replaceWith2 ' recursively through directory listed below\nFor all files that current user has write permissions for\nDIRECTORY: ' $parentDirectory2 '\n" ;
echo "command written by Kolapo Akande :) all rights reserved :)\n" ;
$holdpwd = getcwd ();
//echo "$holdpwd\n";
chdir ( $parentDirectory2 );
openFileSearchAndReplace ( $parentDirectory2 , $searchFor2 , $replaceWith2 );
exit;
?>
Приветствую читателей блога! У вас наверняка уже есть небольшой опыт в кодинге на PHP. Возможно, вы уже разобрались с использованием переменных и базовых конструкций этого языка, а значит, логика вашего приложения увеличивается, как и количества кода.
Конечно, пока вся программа уменьшается в десяток строк, разбивать её на части не нужно. Но вы уже понимаете, что так будет не всегда: авторизация, отправка писем, взаимодействия с базой данных и т.д. – все это приведет к увеличению кода приложения.
Вы спросите: «Ну и что с того? Разве плохо писать всю логику в одном файле?». Стопроцентного ответа на этот вопрос нет, но мой опыт говорит, что код приложения, написанный в одном файле:
- при дополнении и внесении новой логики приводит к частым ошибкам
- требует большего времени для изучения другим разработчиком
- через месяц-два при необходимости маленькой правки потребует у тебя гораздо больше времени на понимание кода, чем на саму правку.
Если этих доводов недостаточно – советую почитать книгу Роберта Мартина «Чистый код». А пока продолжу.
Представим, что у нас есть 2 файла: `index.php` и `1.php`, лежащих в одной директории.
Задача: вывести содержимое файла "1.php" в контейнере `body`, при запуске файла "index.php". Решить её можно разными способами, и в этом посте мы рассмотрим некоторые из них. Подключение PHP возможно с помощью разных инструкций:
- `include`
- `include_once`
- `require`
- `require_once`
Самый простой пример решения с `include`:
Результат запуска в браузере:
Примечания
Замечание: Эта функция безопасна для обработки данных в двоичной форме.
Для этой функции вы можете использовать URL в качестве имени файла, если была включена опция fopen wrappers. Смотрите более подробную информацию об определении имени файла в описании функции fopen() . Смотрите также список поддерживаемых обёрток URL, их возможности, замечания по использованию и список предопределённых констант в разделе Поддерживаемые протоколы и обёртки.
Возвращаемые значения
Функция возвращает количество записанных байт в файл, или false в случае возникновения ошибки.
Эта функция может возвращать как логическое значение false , так и значение не типа boolean, которое приводится к false . За более подробной информацией обратитесь к разделу Булев тип. Используйте оператор === для проверки значения, возвращаемого этой функцией.
User Contributed Notes 21 notes
This might be useful:
include $_SERVER [ 'DOCUMENT_ROOT' ]. "/lib/sample.lib.php" ;
?>
So you can move script anywhere in web-project tree without changes.
If you want to have include files, but do not want them to be accessible directly from the client side, please, please, for the love of keyboard, do not do this:
// check if what is defined and die if not
?>
The reason you should not do this is because there is a better option available. Move the includeFile(s) out of the document root of your project. So if the document root of your project is at "/usr/share/nginx/html", keep the include files in "/usr/share/nginx/src".
include __DIR__ . '/../src/includeFile.php' ;
?>
Since user can't type 'your.site/../src/includeFile.php', your includeFile(s) would not be accessible to the user directly.
Before using php's include, require, include_once or require_once statements, you should learn more about Local File Inclusion (also known as LFI) and Remote File Inclusion (also known as RFI).
The LFI and RFI vulnerabilities occur when you use an input variable in the include statement without proper input validation. Suppose you have an example.php with code:
// Bad Code
$path = $_GET [ 'path' ];
include $path . 'example-config-file.php' ;
?>
As a programmer, you might expect the user to browse to the path that you specify.
The example.php would download my evil.txt and process the operating system command that I passed in as the command variable. In this case, it is whoami. I ended the path variable with a %00, which is the null character. The original include statement in the example.php would ignore the rest of the line. It should tell me who the web server is running as.
Please use proper input validation if you use variables in an include statement.
I cannot emphasize enough knowing the active working directory. Find it by: echo getcwd();
Remember that if file A includes file B, and B includes file C; the include path in B should take into account that A, not B, is the active working directory.
When including a file using its name directly without specifying we are talking about the current working directory, i.e. saying (include "file") instead of ( include "./file") . PHP will search first in the current working directory (given by getcwd() ) , then next searches for it in the directory of the script being executed (given by __dir__).
This is an example to demonstrate the situation :
We have two directory structure :
-dir1
----script.php
----test
----dir1_test
-dir2
----test
----dir2_test
dir1/test contains the following text :
This is test in dir1
dir2/test contains the following text:
This is test in dir2
dir1_test contains the following text:
This is dir1_test
dir2_test contains the following text:
This is dir2_test
script.php contains the following code:
echo 'Directory of the current calling script: ' . __DIR__ ;
echo '
' ;
echo 'Current working directory: ' . getcwd ();
echo '
' ;
echo 'including "test" . ' ;
echo '
' ;
include 'test' ;
echo '
' ;
echo 'Changing current working directory to dir2' ;
chdir ( '../dir2' );
echo '
' ;
echo 'Directory of the current calling script: ' . __DIR__ ;
echo '
' ;
echo 'Current working directory: ' . getcwd ();
echo '
' ;
echo 'including "test" . ' ;
echo '
' ;
include 'test' ;
echo '
' ;
echo 'including "dir2_test" . ' ;
echo '
' ;
include 'dir2_test' ;
echo '
' ;
echo 'including "dir1_test" . ' ;
echo '
' ;
include 'dir1_test' ;
echo '
' ;
echo 'including "./dir1_test" . ' ;
echo '
' ;
(@include './dir1_test' ) or die( 'couldn\'t include this file ' );
?>
The output of executing script.php is :
Directory of the current calling script: C:\dev\www\php_experiments\working_directory\example2\dir1
Current working directory: C:\dev\www\php_experiments\working_directory\example2\dir1
including "test" .
This is test in dir1
Changing current working directory to dir2
Directory of the current calling script: C:\dev\www\php_experiments\working_directory\example2\dir1
Current working directory: C:\dev\www\php_experiments\working_directory\example2\dir2
including "test" .
This is test in dir2
including "dir2_test" .
This is dir2_test
including "dir1_test" .
This is dir1_test
including "./dir1_test" .
couldn't include this file
If you're doing a lot of dynamic/computed includes (>100, say), then you may well want to know this performance comparison: if the target file doesn't exist, then an @include() is *ten* *times* *slower* than prefixing it with a file_exists() check. (This will be important if the file will only occasionally exist - e.g. a dev environment has it, but a prod one doesn't.)
As a rule of thumb, never include files using relative paths. To do this efficiently, you can define constants as follows:
----
define ( 'MAINDIR' , dirname ( __FILE__ ) . '/' );
define ( 'DL_DIR' , MAINDIR . 'downloads/' );
define ( 'LIB_DIR' , MAINDIR . 'lib/' );
?>
----
and so on. This way, the files in your framework will only have to issue statements such as this:
require_once( LIB_DIR . 'excel_functions.php' );
?>
This also frees you from having to check the include path each time you do an include.
If you're running scripts from below your main web directory, put a prepend.php file in each subdirectory:
--
include( dirname ( dirname ( __FILE__ )) . '/prepend.php' );
?>
--
This way, the prepend.php at the top always gets executed and you'll have no path handling headaches. Just remember to set the auto_prepend_file directive on your .htaccess files for each subdirectory where you have web-accessible scripts.
Ideally includes should be kept outside of the web root. That's not often possible though especially when distributing packaged applications where you don't know the server environment your application will be running in. In those cases I use the following as the first line.
( __FILE__ != $_SERVER['SCRIPT_FILENAME'] ) or exit ( 'No' );
It's worth noting that PHP provides an OS-context aware constant called DIRECTORY_SEPARATOR. If you use that instead of slashes in your directory paths your scripts will be correct whether you use *NIX or (shudder) Windows. (In a semi-related way, there is a smart end-of-line character, PHP_EOL)
Example:
$cfg_path
= 'includes'
. DIRECTORY_SEPARATOR
. 'config.php'
;
require_once( $cfg_path );
I would like to point out the difference in behavior in IIS/Windows and Apache/Unix (not sure about any others, but I would think that any server under Windows will be have the same as IIS/Windows and any server under Unix will behave the same as Apache/Unix) when it comes to path specified for included files.
Consider the following:
include '/Path/To/File.php' ;
?>
In IIS/Windows, the file is looked for at the root of the virtual host (we'll say C:\Server\Sites\MySite) since the path began with a forward slash. This behavior works in HTML under all platforms because browsers interpret the / as the root of the server.
However, Unix file/folder structuring is a little different. The / represents the root of the hard drive or current hard drive partition. In other words, it would basically be looking for root:/Path/To/File.php instead of serverRoot:/Path/To/File.php (which we'll say is /usr/var/www/htdocs). Thusly, an error/warning would be thrown because the path doesn't exist in the root path.
I just thought I'd mention that. It will definitely save some trouble for those users who work under Windows and transport their applications to an Unix-based server.
A work around would be something like:
$documentRoot = null ;
if (isset( $_SERVER [ 'DOCUMENT_ROOT' ])) $documentRoot = $_SERVER [ 'DOCUMENT_ROOT' ];
if ( strstr ( $documentRoot , '/' ) || strstr ( $documentRoot , '\\' )) if ( strstr ( $documentRoot , '/' )) $documentRoot = str_replace ( '/' , DIRECTORY_SEPARATOR , $documentRoot );
>
elseif ( strstr ( $documentRoot , '\\' )) $documentRoot = str_replace ( '\\' , DIRECTORY_SEPARATOR , $documentRoot );
>
>
if ( preg_match ( '/[^\\/]\\[^\\/]/' , $documentRoot )) $documentRoot = preg_replace ( '/([^\\/])\\([^\\/])/' , '\\1DIR_SEP\\2' , $documentRoot );
$documentRoot = str_replace ( 'DIR_SEP' , '\\\\' , $documentRoot );
>
>
else /**
* I usually store this file in the Includes folder at the root of my
* virtual host. This can be changed to wherever you store this file.
*
* Example:
* If you store this file in the Application/Settings/DocRoot folder at the
* base of your site, you would change this array to include each of those
* folders.
*
*
* $directories = array(
* 'Application',
* 'Settings',
* 'DocRoot'
* );
*
*/
$directories = array(
'Includes'
);
if ( defined ( '__DIR__' )) $currentDirectory = __DIR__ ;
>
else $currentDirectory = dirname ( __FILE__ );
>
$currentDirectory = rtrim ( $currentDirectory , DIRECTORY_SEPARATOR );
$currentDirectory = $currentDirectory . DIRECTORY_SEPARATOR ;
foreach ( $directories as $directory ) $currentDirectory = str_replace (
DIRECTORY_SEPARATOR . $directory . DIRECTORY_SEPARATOR ,
DIRECTORY_SEPARATOR ,
$currentDirectory
);
>
$currentDirectory = rtrim ( $currentDirectory , DIRECTORY_SEPARATOR );
>
define ( 'SERVER_DOC_ROOT' , $documentRoot );
?>
Using this file, you can include files using the defined SERVER_DOC_ROOT constant and each file included that way will be included from the correct location and no errors/warnings will be thrown.
Когда происходит отправка данных формы PHP-скрипту, информация из этой формы автоматически становится доступной ему. Существует несколько способов получения этой информации, например:
Есть только два способа получить доступ к данным из форм HTML. Доступные сейчас способы приведены ниже:
Замечание:
Точки и пробелы в именах переменных преобразуется в знаки подчёркивания. Например, станет $_REQUEST["a_b"] .
PHP также понимает массивы в контексте переменных формы (смотрите соответствующие ЧАВО). К примеру, вы можете сгруппировать связанные переменные вместе или использовать эту возможность для получения значений списка множественного выбора select. Например, давайте отправим форму самой себе, а после отправки отобразим данные:
Замечание: Если внешнее имя переменной начинается с корректного синтаксиса массива, завершающие символы молча игнорируются. Например, станет $_REQUEST['foo']['bar'] .
Имена переменных кнопки-изображения
При отправке формы вместо стандартной кнопки можно использовать изображение с помощью тега такого вида:
Когда пользователь щёлкнет где-нибудь на изображении, соответствующая форма будет передана на сервер с двумя дополнительными переменными - sub_x и sub_y . Они содержат координаты нажатия пользователя на изображение. Опытные программисты могут заметить, что на самом деле имена переменных, отправленных браузером, содержат точку, а не подчёркивание, но PHP автоматически преобразует точку в подчёркивание.
Замечание: Начиная с PHP 7.2.34, 7.3.23 и 7.4.11, соответственно, имена входящих cookie больше не декодируются из URL-закодированной строки из соображений безопасности.
Если вы хотите присвоить множество значений одной переменной cookie, вы можете присвоить их как массив. Например:
setcookie ( "MyCookie[foo]" , 'Testing 1' , time ()+ 3600 );
setcookie ( "MyCookie[bar]" , 'Testing 2' , time ()+ 3600 );
?>?php
Это создаст две разные cookie, хотя в вашем скрипте MyCookie будет теперь одним массивом. Если вы хотите установить именно одну cookie со множеством значений, сначала рассмотрите возможность использования к значениям такие функции, как serialize() или explode() .
Обратите внимание, что cookie заменит предыдущую cookie с тем же именем в вашем браузере, если только путь или домен не отличаются. Так, для приложения корзины покупок вы, возможно, захотите сохранить счётчик. То есть:
if (isset( $_COOKIE [ 'count' ])) $count = $_COOKIE [ 'count' ] + 1 ;
> else $count = 1 ;
>
setcookie ( 'count' , $count , time ()+ 3600 );
setcookie ( "Cart[ $count ]" , $item , time ()+ 3600 );
?>?php
Различия `include`, `include_once`, `require`, `require_once`
Переименуем файл "1.php"в файл "2.php" и обратимся к "index.php":
В итоге получаем ошибку. Но обратите внимание на то, что после вывода ошибки код PHP все равно продолжил выполнение и вывел `End`. Заменим `include` на `require` и запустим на выполнение.
В итоге видим похожие ошибки, но не видим вывода `End` в конце: после ошибки код php прекратил свою работу.
Разница между `include` и `require` заключается в том, что при подключении файла PHP первая инструкция позволяет продолжить выполнения скрипта, если не найден файл, а `require` завершает его, выводя фатальную ошибку.
Теперь рассмотрим отличие инструкций `require` и `require_once`. Внесем небольшие правки в наши файлы. Вот новый "index.php":
Как видно на скриншоте, с помощью `require` мы успешно подключили файл несколько раз. Снова внесем изменение в файлы. Новый файл "index.php":
И новый файл "2.php" — на этот раз объявим там функцию:
Второе подключение файла "2.php" приводит к ошибке, как раз потому что в этом файле происходит объявление функции. А в PHP-скрипте двух одинаковых функций быть не должно.
Теперь заменим все `require` на `require_once` и запустим снова:
Ура, работает! Но обратим внимание на то, что файл подключился только один раз.
Теперь вновь переименуем файл `2.php` в `1.php` и запустим "index.php".
`Require_once`, так же как и `require` завершает выполнение скрипта, если не найден файл указанный для подключения. Заменим `require_once` на `include_once`:
Ошибок стало больше, но код по-прежнему отработал до конца: end в конце картинки это подтверждает. Внесем правки в "index.php":
Список параметров
Путь к записываемому файлу.
Записываемые данные. Может быть типа string , array или ресурсом потока.
Если data является потоковым ресурсом ( stream ), оставшийся буфер этого потока будет скопирован в указанный файл. Это похоже на использование функции stream_copy_to_stream() .
Также вы можете передать одномерный массив в качестве параметра data . Это будет эквивалентно вызову file_put_contents($filename, implode('', $array)) .
Значением параметра flags может быть любая комбинация следующих флагов, соединённых бинарным оператором ИЛИ ( | ).
Флаг | Описание |
---|---|
FILE_USE_INCLUDE_PATH | Ищет filename в подключаемых директориях. Подробнее смотрите директиву include_path. |
FILE_APPEND | Если файл filename уже существует, данные будут дописаны в конец файла вместо того, чтобы его перезаписать. |
LOCK_EX | Получить эксклюзивную блокировку на файл на время записи. Другими словами, между вызовами fopen() и fwrite() произойдёт вызов функции flock() . Это не одно и то же, что вызов fopen() с флагом "x". |
Корректный ресурс контекста, созданный с помощью функции stream_context_create() .
Читайте также: