PHP запись в файл
Есть простейших код удаления последней строки в файле
<?php
// load the data and delete the line from the array
$lines = file('filename.txt');
$last = sizeof($lines) - 1 ;
unset($lines[$last]);
// write the new data to the file
$fp = fopen('filename.txt', 'w');
fwrite($fp, implode('', $lines));
fclose($fp);
?>
Нужно доработать его так, чтобы в момент изменения файла, не могла произойти коллизий из-за запуска копии скрипта, т.е. перед записью нужно добавить блокировку файла. Либо я ошибаюсь и этото код вполне будет работать правильно без блокировку и коллизия произойти не сможет.
Пример взят здесь qaru.site/questions/798915/how-can-i-remove-the-last-line-of-a-file-using-php
-
68 1 0 Сделаю за час, большой опыт в РНР. Пишите, если заинтересует.
-
151 9 0 $fp = fopen ( "filename.txt","w" );
flock ( $fp,LOCK_EX ); // БЛОКИРОВКА ФАЙЛА
... //работа с файлом
flock ( $fp,LOCK_UN ); // СНЯТИЕ БЛОКИРОВКИ
fclose ( $fp );
if ( !is_writable ( "filename.txt" ) ) {
echo "файл filename.txt не доступен для записи";
}
…
источник http://www.php.su/flock()
-
1941 72 4 3 Добрый вечер!
Для Вашей задачи есть решения поизящнее, суть предельно ясна, готов выполнить.
Читайте отзывы, обращайтесь :)
-
418 142 0 Здравствуйте.
Возьмусь прямо сейчас. Сделаю все быстро и качественно.
-
2748 153 0 1 Здравствуйте. Готов сделать лучше этого.
-
117 Привет,
Я из Армении, и у меня 3-летний опыт работы в области веб-разработки, если хотите, я могу работать на вас.
Я посылаю это, чтобы попросить ваше одобрение, которое поможет мне создать мой профиль на freelancehunt.com и выиграть больше работы.
Нарек Варданян
-
это устаревший метод
-

Для защиты файла с которым работает текущий процесс от изменений со стороны любого другого процесса в операционных системах применяются так называемые блокировки (locks). Для этого в PHP используется функция flock(). Пока на файле стоит блокировка все остальные делающие записать что-либо в этот файл стоят в очереди и дожидаются снятия блокировки. Подробнее почитать можно вот здесь - https://metanit.com/web/php/5.3.php, но в принципе можно найти и другие инструкции с примерами. Так что вам просто надо пару строчек в код добавить и всё.
-
Current freelance projects in the category PHP
Resolve the loading issue on the PrestaShop website hostingThe website requires more and more resources each month. The host's response: During the server check, increased load from the MySQL database server was recorded. At times of the 500 error, the MySQL process uses a significant portion of CPU resources, which can lead to unstable… PHP, Databases & SQL ∙ 20 hours 50 minutes back ∙ 26 proposals |
Integration needed: KeyCRM → Cash Register KashalotIt is necessary to set up integration between KeyCRM and the Cash Register Kahalot. When placing an order in KeyCRM, the data must be automatically transmitted to Kahalot: • order information • products, nomenclature • prices • quantity More details in private. Content Management Systems, PHP ∙ 22 hours 10 minutes back ∙ 25 proposals |
A WordPress site using the Kadence theme and Kadence Blocks.
223 USD
We need to create a website on WordPress using the Kadence theme and Kadence Blocks. There will be no online store (although it may be added in the future). We need a homepage and several internal pages. The graphics are already prepared, the layout structure is mostly defined,… Content Management Systems, PHP ∙ 2 days 7 hours back ∙ 37 proposals |
Development of 2 SEO-oriented websites for selling spare parts (ATVs and special equipment)Development of Two Specialized Websites for Selling Spare PartsGeneral Information It is necessary to develop two specialized websites: Spare parts for ATVs, UTVs, SSVs, and other similar equipment. Spare parts for special equipment. Existing company website:… PHP, Web Programming ∙ 3 days 5 hours back ∙ 76 proposals |
Development of a WordPress website
22 USD
We are looking for a contractor to develop a custom website on WordPress for a jewelry store. The first stage will be a consultation. Content Management Systems, PHP ∙ 5 days 20 hours back ∙ 72 proposals |