PHP has multiple functions to handle files. First, it's important to know that if the PHP server runs on a Linux server, to create or alter files, you normally need to set global access permissions of 0777.
If you use PHP server (WampServer, XAMPP) on Windows you don't need to set these CHMOD permissions.
file_put_contents('filename', 'string', flag)
If "filename" doesn't exist, the file is created with the "string" content. Otherwise, the existing file is overwritten, unless the FILE_APPEND flag is set.<?php $filename = 'files/test.txt'; $str = 'Free PHP course and tutorials.'. PHP_EOL. 'Web site: https://coursesweb.net'; // creates the 'text.txt' file in the 'files' folder if (file_put_contents($filename, $str)) echo 'The file was created'; else echo 'The test.txt file can not be created'; ?>- PHP_EOL is a PHP constant that represents a new line on any operating system.
<?php $filename = 'files/test.txt'; // check if the file exists if (file_exists($filename)) { $get_data = file_get_contents($filename); // store the file content in $get_data echo $get_data; // outputs the content } ?>- Example (with readfile):
<?php $filename = 'files/test.txt'; // check if the file exists if (file_exists($filename)) { readfile($filename); // gets and outputs the content } ?>These examples use the "text.txt" file created in the previous example.
file('filename', flag)
The argument for "flag" is optional. This parameter can have the fallowing values:
<?php $filename = 'files/test.txt'; // check if the file exists if (file_exists($filename)) { $ar_rows = file($filename, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES); // gets the lines in an array var_export($ar_rows); // outputs the structure of the $ar_rows array } ?>Assuming that the "test.txt" is the file created in the first example, this code will output:
<div>Web Programming and Development</div>
h2 { text-decoration: underline; }
function someFunction() { alert("CoursesWeb.net"); } setTimeout("someFunction()", 2000);
$food =["fruits" =>["banana", "apple"), "veggie" =>["collard", "pea")); $nr_food = count($food, 1); echo $nr_food; // 6