Handling file locks in PHP
By: Cory Christison Printer Friendly Format
While can do wonders if you need something to queue writing to a file while something else has access to it.
Here is my simple example:
<?php
function write ($data, $file, $write_mode="w") {
$lock = $file . ".lock";
// run the write fix, to
stop any clashes that may occur
write_fix($lock);
// create a new lock file after
write_fix() for this writing session
touch( $lock
);
// write to your file
$open
= fopen($file, $write_mode);
fwrite($open,
$data);
fclose($open);
// kill
your current lock
unlink($lock);
}
function write_fix ($lock_file) {
while(
file_exists($lock_file){
// do something in
here?
// maybe sleep for a few
microseconds
// to maintain stability, if this
is going to
// take a while ?? [just a
suggestion]
}
}
?>
This method is not recommended for use with programs that will be needing a good few seconds to write to a file, as the while function will eat up alot of process cycles. However, this method does work, and is easy to implement. It also groups the writing functions into one easy to use function, making life easier.
Comment on this tutorial
- Data Science
- Android
- AJAX
- ASP.net
- C
- C++
- C#
- Cocoa
- Cloud Computing
- HTML5
- Java
- Javascript
- JSF
- JSP
- J2ME
- Java Beans
- EJB
- JDBC
- Linux
- Mac OS X
- iPhone
- MySQL
- Office 365
- Perl
- PHP
- Python
- Ruby
- VB.net
- Hibernate
- Struts
- SAP
- Trends
- Tech Reviews
- WebServices
- XML
- Certification
- Interview
categories
Subscribe to Tutorials
Related Tutorials
PHP code to import from CSV file to MySQL
PHP code to write to a CSV file from MySQL query
PHP code to write to a CSV file for Microsoft Applications
Password must include both numeric and alphabetic characters - Magento
PHP file upload prompts authentication for anonymous users
PHP file upload with IIS on windows XP/2000 etc
Error: Length parameter must be greater than 0
Multiple File Upload in PHP using IFRAME
Resume or Pause File Uploads in PHP
Exception in module wampmanager.exe at 000F15A0 in Windows 8
Archived Comments
1. Guys, txtWeb is back with their National Level Dev
View Tutorial By: rahul.del at 2012-08-16 10:01:09