View Full Version : File handling question...

12-02-2010, 12:24 AM
I have an application that writes to a file, and uses that file to load a MySQL table. Here's the current code:

if (!empty($this->goesIntoDatabase)) {

$time->add("Start sql file writing");
$sqlfile = fopen('/tmp/sqlFile.sql', "w");

foreach ($this->goesIntoDatabase as $id => $text) {
$data = explode('|', $id);
fwrite ($sqlfile, $data[0]."\t".$data[1]."\t".$text."\n");

$time->add("End sql file writing");
$time->add("Start process()->data insertion");

LOAD DATA INFILE '/tmp/sqlFile.sql'
INTO TABLE `data` (@time, `author`, `text`)
`time` = UNIX_TIMESTAMP(@time),
`channelID` = ?",


$time->add("End process()->data insertion");

I'm worried that while one person is utilizing the script, another person starts it. And since the script uses the same file location, I'm worried that using the script two or more times at the same time will result in a conflict. Is this possible?

I already plan to append the filename with a semi-unique number, maybe PHP's session ID or microtime(), or both for safe measure, so that each run of the script has it's own file. But this post is more of a clarification on the way files work in PHP.


12-02-2010, 02:56 AM
You can add flock() to your process for an added bit of security, but according to many of the comments left in the PHP manual, it is not 100% foolproof. Read the comments for more information and for some ideas on what other people have done to make sure files don't become corrupted due to multiple simultaneous accesses.


12-02-2010, 08:17 AM
tempnam() would be perfect for your needs. It guarantees a unique filename, and you can override it to use a folder of your choice.


12-02-2010, 06:21 PM
Thank you both!

tmpfile() seems to be slightly better since it's removed when closed, which is one less thing I have to do. =D

12-02-2010, 09:17 PM
yeah that is way better. I've never used tmpfile() before and it is the perfect thing for what you're doing.

12-04-2010, 08:19 AM
Update: Tried it, turns out the permissions don't set right for MySQL to read the file via LOAD DATA INFILE.

=/ Oh well. I'll keep searching, but in the meantime I'm using md_rand().microtime(true) for a hopefully unique filename.

12-04-2010, 11:15 AM
Use chmod() to make MySQL happy?