PHP About files and directories (1) Writing files File permissions 3. Locking files
1. File permissions
In short, everything is to ensure the security of the directory. Ensuring the security of the directory is more important than ensuring the security of the files.
2. Write file
file_put_contents($file,$data); //If not, it will be created, if there is, the original file will be overwritten;
file_put_contents($file,$data,FILE_APPEND); //If not, it will be created, if there is, it will be appended;
file_put_contents($file,$data.PHP_EOL,FILE_APPEND);//With line breaks
[Example]:
// Identify the file to use:
$file ='../quotes.txt'; //This file is best placed in the parent directory for safety.
// Check for a form submission:
if ($_SERVER['REQUEST_METHOD'] == 'POST') { // Handle theform.
if ( !empty($_POST['quote'])&& ($_POST['quote'] != 'Enter yourquotation here.') ) { // Need some thing to write.
if(is_writable($file)) { // Confirm that the file iswritable.
file_put_contents($file,$_POST['quote'] . PHP_EOL, FILE_APPEND); // Write thedata.
//Print amessage:
print'
Your quotation has beenstored.
';
} else { // Could notopen the file.
print'
Yourquotation could not be stored due to a systemerror.
';
}
} else { // Failed to enter aquotation.
print 'Please enter aquotation!=color:>
';
}
} // End of submitted IF.
// Leave PHP and display the form:
?>
3. Lock files
file_put_contents($file,$data,FILE_APPEND|LOCK_EX); //The order in which the two variables are used does not matter
LOCK_SH Shared lock for reading
LOCK_EX Exclusive lock for writing
LOCK_UN Release a lock
LOCK_NB Non-blocking lock
4. Read files
The first method: $data=file_get_contents($file); //Read according to a string
The second method: $data=file($file); //Read the data of each line, which is more commonly used
[Example]: //Additional: Be cautious and you can use the is_readable() function before the file function to test whether the file is readable
http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd>
RandomQuetation
$data =file('../quotes.txt');
// Count the number of items in the array:
$n = count($data);
//Pick a random item: Generate a random number
$rand = rand(0, ($n -1));
// Print the quotation:
print '
' .trim($data[$rand]) .'
'; //file can place content information in an array, each element contains a row
?>
http://www.bkjia.com/PHPjc/907372.htmlwww.bkjia.comtruehttp: //www.bkjia.com/PHPjc/907372.htmlTechArticlePHP About files and directories (1) Writing files File permissions 3. Locking files 1. File permissions In short, everything It is to ensure the security of the directory. Ensuring the security of the directory is better than ensuring the security of the file...