Запись и чтение файлов в PHP
Примеры сохранения и чтения текстовых данных и массивов в файлы.
Сохранение в файл
Функция file_put_contents() записывает содержимое переменной в файл, если файла не существует. то пытается его создать, если существует то полностью перезапишет его.
File_put_contents:
$text = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.'; $filename = __DIR__ . '/file.txt'; file_put_contents($filename, $text);
Fopen / fwrite:
Набор функций fopen, fwrite, fclose предназначены для более гибкой работы с файлами.
- fopen – открытие или создание файла.
- fwrite – запись данных.
- fclose – закрытие файла.
$text = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.'; $filename = __DIR__ . '/file.txt'; $fh = fopen($filename, 'w'); fwrite($fh, $text); fclose($fh);
Возможные режимы fopen():
| Mode | Описание |
|---|---|
| r | Открывает файл только для чтения, помещает указатель в начало файла. |
| r+ | Открывает файл для чтения и записи, помещает указатель в начало файла. |
| w | Открывает файл только для записи, помещает указатель в начало файла и обрезает файл до нулевой длины. Если файл не существует – пробует его создать. |
| w+ | Открывает файл для чтения и записи, помещает указатель в начало файла и обрезает файл до нулевой длины. Если файл не существует – пытается его создать. |
| a | Открывает файл только для записи, помещает указатель в конец файла. Если файл не существует – пытается его создать. |
| a+ | Открывает файл для чтения и записи, помещает указатель в конец файла. Если файл не существует – пытается его создать. |
| x | Создаёт и открывает только для записи; помещает указатель в начало файла. Если файл уже существует, вызов fopen() закончится неудачей, вернёт false и выдаст ошибку. Если файл не существует, попытается его создать. |
| x+ | Создаёт и открывает для чтения и записи, в остальном имеет то же поведение, что и « x ». |
| c | Открывает файл только для записи. Если файл не существует, то он создаётся. Если же файл существует, то он не обрезается (в отличие от « w »), и вызов к этой функции не вызывает ошибку (также как и в случае с « x »). Указатель на файл будет установлен на начало файла. |
| c+ | Открывает файл для чтения и записи, в остальном имеет то же поведение, что и « c ». |
Доступно в место fwrite() используют fputs() , разницы ни какой т.к. эта функция является псевдонимом.
Дописать строку в начало файла
$new_str = 'New line of text.'; $filename = __DIR__ . '/file.txt'; $text = file_get_contents($filename); file_put_contents($filename, $new_str . PHP_EOL . $text);
Дописать строку в конец файла
$new_str = 'New line of text.'; $filename = __DIR__ . '/file.txt'; file_put_contents($filename, PHP_EOL . $new_str, FILE_APPEND);
Или fopen с флагом « c »:
$new_str = 'New line of text.'; $filename = __DIR__ . '/file.txt'; $fh = fopen($filename, 'c'); fseek($fh, 0, SEEK_END); fwrite($fh, PHP_EOL . $new_str); fclose($fh);
Чтение из файла
Чтение всего файла
$filename = __DIR__ . '/file.txt'; $text = file_get_contents($filename); echo $text;
$filename = __DIR__ . '/file.txt'; $text = ''; $fh = fopen($filename, 'r'); while (!feof($fh)) < $line = fgets($fh); $text .= $line . PHP_EOL; >fclose($fh); echo $text;
Чтение файла в массив
Функция file() – читает содержимое файла и помещает его в массив, доступны опции:
- FILE_IGNORE_NEW_LINES – пропускать новую строку в конце каждого элемента массива.
- FILE_SKIP_EMPTY_LINES – пропускать пустые строки.
$filename = __DIR__ . '/file.txt'; $array = file($filename); print_r($array);
Чтение файла сразу в браузер
$filename = __DIR__ . '/file.txt'; readfile($filename);
Получить первую строку из файла
$filename = __DIR__ . '/file.txt'; $fh = fopen($filename, 'r'); echo fgets($fh); fclose($fh); /* или */ $filename = __DIR__ . '/file.txt'; $array = file($filename); echo $array[0];
Первые три строки из файла:
$filename = __DIR__ . '/file.txt'; $array = file($filename); $first_3 = array_slice($array, 0, 3); print_r($first_3);
Получить последнюю строку из файла
$filename = __DIR__ . '/file.txt'; $array = file($filename); $last = array_slice($array, -1); echo $last[0];
Последние три строки из файла:
$filename = __DIR__ . '/file.txt'; $array = file($filename); $last_3 = array_slice($array, -3); print_r($last_3);
Запись и чтение массивов в файл
Serialize
Не очень удачное хранение данных в сериализованном виде т.к. изменение одного символа может привести к ошибке чтения всех данных в файле. Подробнее в статье «Функция serialize, возможные проблемы»
Запись:
$array = array('foo', 'bar', 'hallo', 'world'); $text = base64_encode(serialize($array)); file_put_contents(__DIR__ . '/array.txt', $text);
Чтение:
$array = unserialize(base64_decode($text)); print_r($array);
JSON
Запись:
$array = array('foo', 'bar', 'hallo', 'world'); $json = json_encode($array, JSON_UNESCAPED_UNICODE); file_put_contents(__DIR__ . '/array.json', $json);
Чтение:
$json = file_get_contents(__DIR__ . '/array.json'); $array = json_decode($json, true); print_r($array);
fwrite
fwrite() записывает содержимое data в файловый поток stream .
Список параметров
Указатель ( resource ) на файл, обычно создаваемый с помощью функции fopen() .
Если параметр length является целым числом ( int ), запись остановится после того, как length байтов будут записаны или будет достигнут конец строки data , смотря что произойдёт раньше.
Возвращаемые значения
fwrite() возвращает количество записанных байт или false в случае возникновения ошибки.
Ошибки
Функция fwrite() выдаёт ошибку уровня E_WARNING в случае возникновения ошибки.
Список изменений
| Версия | Описание |
|---|---|
| 8.0.0 | Параметр length теперь допускает значение null . |
Примеры
Пример #1 Простой пример использования fwrite()
$filename = ‘test.txt’ ;
$somecontent = «Добавить это к файлу\n» ;
?php
// Вначале давайте убедимся, что файл существует и доступен для записи.
if ( is_writable ( $filename ))
// В нашем примере мы открываем $filename в режиме «записи в конец».
// Таким образом, смещение установлено в конец файла и
// наш $somecontent допишется в конец при использовании fwrite().
if (! $fp = fopen ( $filename , ‘a’ )) echo «Не могу открыть файл ( $filename )» ;
exit;
>
// Записываем $somecontent в наш открытый файл.
if ( fwrite ( $fp , $somecontent ) === FALSE ) echo «Не могу произвести запись в файл ( $filename )» ;
exit;
>
echo «Ура! Записали ( $somecontent ) в файл ( $filename )» ;
> else echo «Файл $filename недоступен для записи» ;
>
?>
Примечания
Замечание:
Запись в сетевой поток может прекратиться до того, как будут записаны все данные. Это можно контролировать с помощью проверки возвращаемого значения функции fwrite() :
function fwrite_stream ( $fp , $string ) for ( $written = 0 ; $written < strlen ( $string ); $written += $fwrite ) $fwrite = fwrite ( $fp , substr ( $string , $written ));
if ( $fwrite === false ) return $written ;
>
>
return $written ;
>
?>?php
Замечание:
В системах, различающих двоичные и текстовые файлы (к примеру, Windows), файл должен быть открыт используя флаг ‘b’ в конце аргумента mode функции fopen() .
Замечание:
Если дескриптор stream был открыт функцией fopen() в режиме «добавление в конец», то вызовы fwrite() будут атомарными (за исключением случая, если размер data превысит размер блока файловой системы, на некоторых платформах, и пока файл хранится на локальной файловой системе). То есть нет необходимости блокировать ресурс с помощью flock() перед вызовом fwrite() , и все данные будут записаны без прерываний.
Замечание:
При повторной записи в файловый указатель, данные будут добавлены в конец содержимого файла:
$fp = fopen ( ‘data.txt’ , ‘w’ );
fwrite ( $fp , ‘1’ );
fwrite ( $fp , ’23’ );
fclose ( $fp );
?php
// содержимое ‘data.txt’ теперь 123, а не 23!
?>
Смотрите также
- fread() — Бинарно-безопасное чтение файла
- fopen() — Открывает файл или URL
- fsockopen() — Открывает соединение с интернет-сокетом или доменным сокетом Unix
- popen() — Открывает файловый указатель процесса
- file_get_contents() — Читает содержимое файла в строку
- pack() — Упаковать данные в бинарную строку
User Contributed Notes 33 notes
13 years ago
After having problems with fwrite() returning 0 in cases where one would fully expect a return value of false, I took a look at the source code for php’s fwrite() itself. The function will only return false if you pass in invalid arguments. Any other error, just as a broken pipe or closed connection, will result in a return value of less than strlen($string), in most cases 0.
Therefore, looping with repeated calls to fwrite() until the sum of number of bytes written equals the strlen() of the full value or expecting false on error will result in an infinite loop if the connection is lost.
This means the example fwrite_stream() code from the docs, as well as all the «helper» functions posted by others in the comments are all broken. You *must* check for a return value of 0 and either abort immediately or track a maximum number of retries.
Below is the example from the docs. This code is BAD, as a broken pipe will result in fwrite() infinitely looping with a return value of 0. Since the loop only breaks if fwrite() returns false or successfully writes all bytes, an infinite loop will occur on failure.
// BROKEN function — infinite loop when fwrite() returns 0s
function fwrite_stream ( $fp , $string ) <
for ( $written = 0 ; $written < strlen ( $string ); $written += $fwrite ) <
$fwrite = fwrite ( $fp , substr ( $string , $written ));
if ( $fwrite === false ) <
return $written ;
>
>
return $written ;
>
?>
2 years ago
if you need a function that writes all data, maybe try
/**
* writes all data or throws
*
* @param mixed $handle
* @param string $data
* @throws \RuntimeException when fwrite returned * @return void
*/
/*private static*/ function fwrite_all ( $handle , string $data ): void
$original_len = strlen ( $data );
if ( $original_len > 0 ) $len = $original_len ;
$written_total = 0 ;
for (;;) $written_now = fwrite ( $handle , $data );
if ( $written_now === $len ) return;
>
if ( $written_now < 1 ) throw new \RuntimeException ( "could only write < $written_total >/ < $original_len >bytes!» );
>
$written_total += $written_now ;
$data = substr ( $data , $written_now );
$len -= $written_now ;
// assert($len > 0);
// assert($len === strlen($data));
>
>
>
3 years ago
$handles can also be used to output in console like below example
fwrite(STDOUT, «Console Output»);
file_put_contents
Функция идентична последовательным успешным вызовам функций fopen() , fwrite() и fclose() .
Если filename не существует, файл будет создан. Иначе, существующий файл будет перезаписан, за исключением случая, если указан флаг FILE_APPEND .
Список параметров
Путь к записываемому файлу.
Записываемые данные. Может быть типа 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() .
Возвращаемые значения
Функция возвращает количество записанных байт в файл, или false в случае возникновения ошибки.
Внимание
Эта функция может возвращать как логическое значение false , так и значение не типа boolean, которое приводится к false . За более подробной информацией обратитесь к разделу Булев тип. Используйте оператор === для проверки значения, возвращаемого этой функцией.
Примеры
Пример #1 Пример простого использования
$file = ‘people.txt’ ;
// Открываем файл для получения существующего содержимого
$current = file_get_contents ( $file );
// Добавляем нового человека в файл
$current .= «John Smith\n» ;
// Пишем содержимое обратно в файл
file_put_contents ( $file , $current );
?>?php
Пример #2 Использование флагов
$file = ‘people.txt’ ;
// Новый человек, которого нужно добавить в файл
$person = «John Smith\n» ;
// Пишем содержимое в файл,
// используя флаг FILE_APPEND для дописывания содержимого в конец файла
// и флаг LOCK_EX для предотвращения записи данного файла кем-нибудь другим в данное время
file_put_contents ( $file , $person , FILE_APPEND | LOCK_EX );
?>?php
Примечания
Замечание: Эта функция безопасна для обработки данных в двоичной форме.
Подсказка
Для этой функции вы можете использовать URL в качестве имени файла, если была включена опция fopen wrappers. Смотрите более подробную информацию об определении имени файла в описании функции fopen() . Смотрите также список поддерживаемых обёрток URL, их возможности, замечания по использованию и список предопределённых констант в разделе Поддерживаемые протоколы и обёртки.
Смотрите также
- fopen() — Открывает файл или URL
- fwrite() — Бинарно-безопасная запись в файл
- file_get_contents() — Читает содержимое файла в строку
- stream_context_create() — Создаёт контекст потока
User Contributed Notes 37 notes
15 years ago
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 );
>
?>
1 year ago
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);
>
12 years ago
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
4 years ago
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 );
?>
13 years ago
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 );
?>
10 years ago
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.
6 years ago
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 ;
>
17 years ago
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;
>
>
7 years ago
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);
19 years ago
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:
12 years ago
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 );
?>
6 years ago
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);
>
9 years ago
File put contents fails if you try to put a file in a directory that doesn’t exist. This function creates the directory.
i have updated code of «TrentTompkins at gmail dot com». thanks
/**
* @param string $filename
file name including folder.
* example :: /path/to/file/filename.ext or filename.ext
* @param string $data
The data to write.
*
* @param int $flags same flags used for file_put_contents.
* more info: http://php.net/manual/en/function.file-put-contents.php
* @return bool TRUE file created succesfully
FALSE failed to create file.
*/
function file_force_contents ( $filename , $data , $flags = 0 ) if(! is_dir ( dirname ( $filename )))
mkdir ( dirname ( $filename ). ‘/’ , 0777 , TRUE );
return file_put_contents ( $filename , $data , $flags );
>
// usage
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»).
?>
11 years ago
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);
12 years ago
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.
14 years ago
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.
$a_str = array( «these» , «are» , «new» , «lines» );
$contents = implode ( PHP_EOL , $a_str );
$contents .= PHP_EOL . PHP_EOL ;
file_put_contents ( «newfile.txt» , $contents );
print( «| $contents |» );
?>
You can see that when you print $contents you get two extra line endings, but if you view the file newfile.txt, you only get one.
12 years ago
Calling file_put_contents within a destructor will cause the file to be written in SERVER_ROOT.
14 years ago
I use file_put_contents() as a method of very simple hit counters. These are two different examples of extremely simple hit counters, put on one line of code, each.
Keep in mind that they’re not all that efficient. You must have a file called counter.txt with the initial value of 0.
For a text hit counter:
$counter = file_get_contents ( «counter.txt» ); $counter ++; file_put_contents ( «counter.txt» , $counter ); echo $counter ;
?>
Or a graphic hit counter:
$counter = file_get_contents ( «counter.txt» ); $counter ++; file_put_contents ( «counter.txt» , $counter ); for( $i = 0 ; $i < strlen ( $counter ); $i ++) echo "" ;
?>
12 years ago
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.
16 years ago
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:
if ( ! function_exists ( ‘file_put_contents’ ) && ! defined ( ‘FILE_APPEND’ ) ) .
>
?>
Also, if the file could not be accessed for writing, the function should return boolean false, not 0. An error is different from 0 bytes written, in this case.
5 years ago
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’;
file_put_contents($this->path(), mb_convert_encoding($content, $to, $from));
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.
5 years ago
Here is a stupid pitfall I just fell into.
I think it may happen rather frequently, so I report it.
A common situation is that the $filename argument is built from two variables:
file_put_contents($path . $file, $content);
Say that $path = ‘path/to’ and $file = ‘file.txt’: you see that $path lacks its ending «/», so the resulting full path is ‘path/tofile.txt’.
Then you look at ‘path/to’ and don’t see any ‘file.txt’, although no warning or notice was thrown!
And may be (like for me :D) it’ll take time before you realize that a bad ‘tofile.txt’ was created in the *parent* directory of the one where you were looking for your file.
15 years ago
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
#!/usr/bin/php
$argc = $_SERVER [ ‘argc’ ];
$argv = $_SERVER [ ‘argv’ ];
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;
?>
12 years ago
I made a ftp_put_contents function.
function ftp_put_contents ( $fpc_path_and_name , $fpc_content )
//Temporary folder in the server
$cfg_temp_folder = str_replace ( «//» , «/» , $_SERVER [ ‘DOCUMENT_ROOT’ ]. «/_temp/» );
//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» ;
//Check if conteins slash on the path of the file
$cotains_slash = strstr ( $fpc_path_and_name , «/» );
//Get filename and paths
if ( $cotains_slash ) $fpc_path_and_name_array = explode ( «/» , $fpc_path_and_name );
$fpc_file_name = end ( $fpc_path_and_name_array );
>
else $fpc_file_name = $fpc_path_and_name ;
>
//Create local temp dir
if (! file_exists ( $cfg_temp_folder )) if (! mkdir ( $cfg_temp_folder , 0777 )) echo «Unable to generate a temporary folder on the local server — $cfg_temp_folder .
» ;
die();
>
>
//Create local file in temp dir
if (! file_put_contents ( str_replace ( «//» , «/» , $cfg_temp_folder . $fpc_file_name ), $fpc_content )) echo «Unable to generate the file in the temporary location — » . str_replace ( «//» , «/» , $cfg_temp_folder . $fpc_file_name ). «.
» ;
die();
>
//Connection to the FTP Server
$fpc_ftp_conn = ftp_connect ( » $cfg_ftp_server » );
//Check connection
if (! $fpc_ftp_conn ) echo «Could not connect to server $cfg_ftp_server .
» ;
die();
>
else
// login
// check username and password
if (! ftp_login ( $fpc_ftp_conn , » $cfg_user » , » $cfg_pass » )) echo «User or password.
» ;
die();
>
else
//Document Root
if (! ftp_chdir ( $fpc_ftp_conn , $cfg_document_root )) echo «Error to set Document Root.
» ;
die();
>
//Check if there are folders to create
if ( $cotains_slash )
//Check if have folders and is not just the file name
if ( count ( $fpc_path_and_name_array ) > 1 )
//Remove last array
$fpc_remove_last_array = array_pop ( $fpc_path_and_name_array );
//Checks if there slashs on the path
if ( substr ( $fpc_path_and_name , 0 , 1 ) == «/» ) $fpc_remove_first_array = array_shift ( $fpc_path_and_name_array );
>
//Create each folder on ftp
foreach ( $fpc_path_and_name_array as $fpc_ftp_path ) if (!@ ftp_chdir ( $fpc_ftp_conn , $fpc_ftp_path )) if (! ftp_mkdir ( $fpc_ftp_conn , $fpc_ftp_path )) echo «Error creating directory $fpc_ftp_path .
» ;
>
else if (! ftp_chdir ( $fpc_ftp_conn , $fpc_ftp_path )) echo «Error go to the directory $fpc_ftp_path .
» ;
>
>
>
>
>
else
//Close connection to FTP server
ftp_close ( $fpc_ftp_conn );
>
>
>
ftp_put_contents ( «test.php» , $content_file );
?>
Работа с файловой системой
Как и большинство языков программирования, PHP поддерживает работу с файлами, которые являются одним из способов хранения информации.
Чтение и запись файлов
Открытие и закрытие файлов
Для открытия файлов в PHP определена функция fopen() . Она имеет следующее определение: resource fopen(string $filename, string $mode) . Первый параметр $filename представляет путь к файлу, а второй — режим открытия. В зависимости от цели открытия и типа файла данный параметр может принимать следующие значения:
- ‘r’ : файл открывается только для чтения. Если файла не существует, возвращает false
- ‘r+’ : файл открывается только для чтения с возможностью записи. Если файла не существует, возвращает false
- ‘w’ : файл открывается для записи. Если такой файл уже существует, то он перезаписывается, если нет — то он создается
- ‘w+’ : файл открывается для записи с возможностью чтения. Если такой файл уже существует, то он перезаписывается, если нет — то он создается
- ‘a’ : файл открывается для записи. Если такой файл уже существует, то данные записываются в конец файла, а старые данные остаются. Если файл не существует, то он создается
- ‘a+’ : файл открывается для чтения и записи. Если файл уже существует, то данные дозаписываются в конец файла. Если файла нет, то он создается
Результатом функции fopen будет дескриптор файла. Этот дескриптор используется для операций с файлом и для его закрытия.
После окончания работы файл надо закрыть с помощью функции fclose() , которая принимает в качестве параметра дескриптор файла. Например, откроем и закроем файл:
$fd = fopen("form.php", 'r') or die("не удалось открыть файл"); fclose($fd);
Конструкция or die(«текст ошибки») позволяет прекратить работу скрипта и вывесте некоторое сообщение об ошибке, если функция fopen не смогла открыть файл.
Чтение файла
Для чтения файла можно использовать несколько функций. Для построчного чтения используется функция fgets() , которая получает дескриптор файла и возвращает одну считанную строку. Пройдем построчно по всему файлу:
fclose($fd); ?>
При каждом вызове fgets() PHP будет помещать указатель в конец считанной строки. Чтобы проследить окончание файла, используется функция feof() , которая возвращает true при завершении файла. И пока не будет достигнут конец файла, мы можем применять функцию fgets().
Чтение файла полностью
Если нам надо прочитать файл полностью, то мы можем облегчить себе жизнь, применив функцию file_get_contents() :
При этом нам не надо открывать явно файл, получать дескриптор, а затем закрывать файл.
Поблочное считывание
Также можно провести поблочное считывание, то есть считывать определенное количество байт из файла с помощью функции fread() :
fclose($fd); ?>
Функция fread() принимает два параметра: дескриптор считываемого файла и количество считываемых байтов. При считывании блока указатель в файле становится в конец этого блока. И также с помощью функции feof() можно отследить завершение файла.
Запись файла
Для записи файла применяется функция fwrite() , которая записывает в файл строку:
Аналогично работает другая функция fputs() :
Работа с указателем файла
При открытии файла для чтения или записи в режиме ‘w’, указатель в файле помещается в начало. При считывании данных PHP перемещает указатель в файле в конец блока считанных данных. Однако мы также вручную можем управлять указателем в файле и устанавливать его в произвольное место. Для этого надо использовать функцию fseek, которая имеет следующее формальное определение:
int fseek (resource $handle , int $offset [, int $whence = SEEK_SET ] )
Параметр $handle представляет дескриптор файла. Параметр $offset — смещение в байтах относительно начала файла, с которого начнется считывание/запись. Третий необязательный параметр задает способ установки смещения. Он может принимать три значения:
- SEEK_SET : значение по умолчанию, устанавливает смещение в offset байт относительно начала файла
- SEEK_CUR : устанавливает смещение в offset байт относительно начала текущей позиции в файле
- SEEK_END : устанавливает смещение в offset байт от конца файла
В случае удачной установки указателя функция fseek() возвращает 0, а при неудачной установке возвращает -1.
Пример использования функции:
$fd = fopen("hello.txt", 'w+') or die("не удалось открыть файл"); $str = "Привет мир!"; // строка для записи fwrite($fd, $str); // запишем строку в начало fseek($fd, 0); // поместим указатель файла в начало fwrite($fd, "Хрю"); // запишем в начало строку fseek($fd, 0, SEEK_END); // поместим указатель в конец fwrite($fd, $str); // запишем в конце еще одну строку fclose($fd);
