文件锁定在PHP

编程入门 行业动态 更新时间:2024-10-28 03:18:20
本文介绍了文件锁定在PHP的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个新来的人(隔壁的少年)写一些php代码来跟踪我的网站上的一些用法.我不熟悉php,所以我想问一下有关并发文件访问的问题.

I had a newcomer (the next door teenager) write some php code to track some usage on my web site. I'm not familiar with php so I'm asking a bit about concurrent file access.

我的本​​机应用程序(在Windows上)有时会通过点击包含我的php脚本的URL将一些数据记录到我的站点中.本机应用程序不检查返回的数据.

My native app (on Windows), occasionally logs some data to my site by hitting the URL that contains my php script. The native app does not examine the returned data.

$fh = fopen($updateFile, 'a') or die("can't open file"); fwrite($fh, $ip); fwrite($fh, ', '); fwrite($fh, $date); fwrite($fh, ', '); fwrite($fh, implode(', ', $_GET)); fwrite($fh, "\r\n"); fclose($fh);

这是一个人流量低的站点,数据并不重要.但是,如果两个用户发生冲突,并且脚本的两个实例各自尝试向该文件添加一行,该怎么办? php中是否有任何隐式文件锁定?

This is a low traffic site, and the data is not critical. But what happens if two users collide and two instances of the script each try to add a line to the file? Is there any implicit file locking in php?

上面的代码至少可以安全地锁定并永远不会将控制权交还给我的用户吗?文件会损坏吗?如果我上面的脚本每个月都删除文件,那么如果该脚本的另一个实例正在写入文件,该怎么办?

Is the code above at least safe from locking up and never returning control to my user? Can the file get corrupted? If I have the script above delete the file every month, what happens if another instance of the script is in the middle of writing to the file?

推荐答案

您应该在文件上加锁:

<?php $fp = fopen($updateFile, 'w+'); if(flock($fp, LOCK_EX)) { fwrite($fp, 'a'); flock($fp, LOCK_UN); } else { echo 'can\'t lock'; } fclose($fp);

更多推荐

文件锁定在PHP

本文发布于:2023-06-04 19:05:36,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/503299.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:文件   PHP

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!