php create text file

PHP File Create/Write

In this chapter we will teach you how to create and write to a file on the server.

The fopen() function is also used to create a file. Maybe a little confusing, but in PHP, a file is created using the same function used to open files.

If you use fopen() on a file that does not exist, it will create it, given that the file is opened for writing (w) or appending (a).

The example below creates a new file called «testfile.txt». The file will be created in the same directory where the PHP code resides:

Example

PHP File Permissions

If you are having errors when trying to get this code to run, check that you have granted your PHP file access to write information to the hard drive.

The fwrite() function is used to write to a file.

The first parameter of fwrite() contains the name of the file to write to and the second parameter is the string to be written.

The example below writes a couple of names into a new file called «newfile.txt»:

Example

If we open the «newfile.txt» file it would look like this:

PHP Overwriting

Now that «newfile.txt» contains some data we can show what happens when we open an existing file for writing. All the existing data will be ERASED and we start with an empty file.

In the example below we open our existing file «newfile.txt», and write some new data into it:

Example

If we now open the «newfile.txt» file, both John and Jane have vanished, and only the data we just wrote is present:

Complete PHP Filesystem Reference

For a complete reference of filesystem functions, go to our complete PHP Filesystem Reference.

Источник

file_put_contents

file_put_contents — Пишет данные в файл

Описание

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

Путь к записываемому файлу.

Значением параметра flags может быть любая комбинация следующих флагов, соединённых бинарным оператором ИЛИ ( | ).

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

Функция возвращает количество записанных байт в файл, или false в случае возникновения ошибки.

Примеры

Пример #1 Пример простого использования

Пример #2 Использование флагов

Примечания

Замечание: Эта функция безопасна для обработки данных в двоичной форме.

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

User Contributed Notes 36 notes

File put contents fails if you try to put a file in a directory that doesn’t exist. This creates the directory.

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.

real 0m3.932s
user 0m2.487s
sys 0m1.437s

real 0m2.265s
user 0m1.819s
sys 0m0.445s

Please note that when saving using an FTP host, an additional stream context must be passed through telling PHP to overwrite the file.

/* the file content */
$content = «this is just a test.» ;

I faced the problem of converting a downloaded csv file that had Windows-1252 encoding, so to convert it to UTF-8 this worked for me:

$from = ‘Windows-1252’;
$to = ‘UTF-8’;

where «$this->path()» has the path of the file. Using this the file is converted from Windows-1252 to UTF-8.

With this you can import it with mysqlimport with no problems.

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:

I suggest to expand file_force_contents() function of TrentTompkins at gmail dot com by adding verification if patch is like: «../foo/bar/file»

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:

Make sure not to corrupt anything in case of failure.

__DIR__ is your friend.

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.

File put contents fails if you try to put a file in a directory that doesn’t exist. This function creates the directory.

file name including folder.
* example :: /path/to/file/filename.ext or filename.ext

This function doesn’t return False if all data isn’t write, especially when data is a stream resource

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.

As to the previous user note, it would be wise to include that code within a conditional statement, as to prevent re-defining file_put_contents and the FILE_APPEND constant in PHP 5:

file_put_contents() strips the last line ending

If you really want an extra line ending at the end of a file when writing with file_put_contents(), you must append an extra PHP_EOL to the end of the line as follows.

I made ​​a ftp_put_contents function.

//FTP username
$cfg_user = «user» ;

//FTP password
$cfg_pass = «password» ;

//Document Root of FTP
$cfg_document_root = «DOCUMENT ROOT OF FTP» ;

//Link to the website
$cfg_site_link = «Link to the website» ;

Источник

Create or write/append in text file

I have a website that every time a user logs in or logs out I save it to a text file.

My code doesn’t work in appending data or creating a text file if it does not exist.. Here is the sample code

It seems it does not append to next line after I open it again.

Also I think it would also have an error in a situation when 2 users login at the same time, would it affect opening the text file and saving it afterwards?

7 Answers 7

Try something like this:

php create text file. Смотреть фото php create text file. Смотреть картинку php create text file. Картинка про php create text file. Фото php create text file

You can do it the OO way, just an alternative and flexible:

Check your log with this:

php create text file. Смотреть фото php create text file. Смотреть картинку php create text file. Картинка про php create text file. Фото php create text file

This is working for me, Writing(creating as well) and/or appending content in the same mode.

php create text file. Смотреть фото php create text file. Смотреть картинку php create text file. Картинка про php create text file. Фото php create text file

I always use it like this, and it works.

php create text file. Смотреть фото php create text file. Смотреть картинку php create text file. Картинка про php create text file. Фото php create text file

php create text file. Смотреть фото php create text file. Смотреть картинку php create text file. Картинка про php create text file. Фото php create text file

There is no such file open mode as «wr» in your code:

There are the following main open modes «r» for read, «w» for write and «a» for append, and you cannot combine them. You can add other modifiers like «+» for update, «b» for binary. The new C standard adds a new standard subspecifier («x»), supported by PHP, that can be appended to any «w» specifier (to form «wx», «wbx», «w+x» or «w+bx»/»wb+x»). This subspecifier forces the function to fail if the file exists, instead of overwriting it.

Besides that, in PHP 5.2.6, the ‘c’ main open mode was added. You cannot combine ‘c’ with ‘a’, ‘r’, ‘w’. The ‘c’ opens the file for writing only. If the file does not exist, it is created. If it exists, it is neither truncated (as opposed to ‘w’), nor the call to this function fails (as is the case with ‘x’). ‘c+’ Open the file for reading and writing; otherwise it has the same behavior as ‘c’.

Additionally, and in PHP 7.1.2 the ‘e’ option was added that can be combined with other modes. It set close-on-exec flag on the opened file descriptor. Only available in PHP compiled on POSIX.1-2008 conform systems.

So, for the task as you have described it, the best file open mode would be ‘a’. It opens the file for writing only. It places the file pointer at the end of the file. If the file does not exist, it attempts to create it. In this mode, fseek() has no effect, writes are always appended.

Here is what you need, as has been already pointed out above:

Источник

Write text file php

I want to write a php page to get parameters from another page and write to a file text. And:

If already have file text, it write to a new line

Each day create one file text

6 Answers 6

Use the file_get_contents() and file_put_contents() functions.

Example:

try below code, i have made some change in code and test it.

php create text file. Смотреть фото php create text file. Смотреть картинку php create text file. Картинка про php create text file. Фото php create text file

w Open for writing only; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it.

a Open for writing only; place the file pointer at the end of the file. If the file does not exist, attempt to create it.

So you want to append, not write.

If the file doesn’t exist, it’ll try to create it. So just give the file a unique name that changes with the day. See date docs for examples.

Above is simple example to do it in php

I haven’t written a lot of php, but if you replace «w» with «w+» in fopen() it’ll open the file and place the pointer at the end of it if the file already exists, making any fwrite() calls append to the file.

edit: saw sachleen’s answer and yes, you could combine the date (down to the day) with the file name. So that on a new day a new file would be created for that day and if the file exists for that day, it will be appended to.

Not the answer you’re looking for? Browse other questions tagged php or ask your own question.

Linked

Related

Hot Network Questions

Subscribe to RSS

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.9.17.40238

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Источник

Работа с файлами в PHP

Чтение файла: file_get_contents()

С помощью функции file_get_contents() можно получить содержимое файла:

Также мы можем получить html-код какой-либо страницы в интернете:

Но работает это далеко не для всех сайтов, у многих есть защита от такого примитивного парсинга.

Чтение файла: file()

Функция file() позволяет получить содержимое файла в виде массива. Разделителем элементов является символ переноса строки.

Создадим в корне сайта файл data.txt со следующим содержимым:

Теперь запустим скрипт index.php со следующим кодом:

При запуске этого скрипта мы получим в браузере:

Заметили, что у первых двух строк длина 7 символов вместо пяти? Это из-за того, что каждая строка содержит в конце символы переноса строки.

Чаще всего они нам не нужны, поэтому их можно убрать, передав вторым параметром константу FILE_IGNORE_NEW_LINES :

Теперь у всех строк будет по 5 символов.

Если нам необходимо получить только заполненные строки в файле и пропустить пустые, можно передать вторым параметром константу FILE_SKIP_EMPTY_LINES :

Разумеется, мы можем передать сразу две константы:

Создание файла и запись в файл: file_put_contents()

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

Чтобы не перезаписывать данные, а добавить их в конец файла, нужно передать третьим параметром константу FILE_APPEND :

Также вторым параметром можно передать массив:

Но этот вариант не очень удобен, поскольку все элементы массива запишутся подряд, без каких-либо разделителей. Чтобы их добавить, можно использовать функцию implode:

Создание папки или структуры папок

Создать папку можно с помощью функции mkdir() (make directory):

Кроме этого, второй параметр может игнорироваться при заданной umask (пользовательская маска (user mask), которая нужна для определения конечных прав доступа). В этом случае принудительно сменить права можно функцией chmod() :

Также мы можем создать структуру папок рекурсивно, для этого нужно третьим параметром передать true :

Но в этом случае права доступа будут заданы только для конечной папки. Для изменения прав у каждой из папок придётся указывать права вручную:

Проверка существования файла или папки

Проверить существование папки или файла можно с помощью функции file_exists() :

Если вы хотите проверить существование только папки или только файла, для этого есть специальные функции is_dir() и is_file() :

Проверка прав доступа

Функции is_readable() и is_writable() проверяют, есть ли у пользователя, от имени которого запущен PHP, права на чтение и запись файла или папки:

Копирование, перенос и удаление файла

Для удаления файлов используется функция unlink() :

Чтобы скопировать файл, используем функцию copy() :

Для переименования и переноса файла в другую папку используется функция rename() :

Работа с файлами с помощью fopen()

Но иногда возникают ситуации, когда нам необходимы более продвинутые инструменты. Например, если у нас есть большой текстовый файл и мы хотим читать его построчно, а не весь сразу, для экономии оперативной памяти.

Итак, открыть (или создать и открыть) файл можно с помощью функции fopen() :

Для построчного чтения файла используется функция fgets() :

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

Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *