Working With Files Flashcards
How to check if a file named “example.txt” exists in PHP
if (file_exists(‘example.txt’)) {
echo “file exists”;
} else {
echo “file does not exist”;
}
How do you open a file named “example.txt” for reading in PHP
$handle = fopen(‘example.txt’, ‘r’);
if ($handle) {
// File is open and ready for reading.
} else {
echo “Failed to open the file.”;
}
How do you close:
$handle = fopen(‘example.txt’, ‘r’);
fclose($handle);
How do you get the size of a file named “example.txt”. Save it to a variable named $size
$size = filesize(‘example.txt’);
Create, open, write to, and then close a file named “example.txt”. The file should contain “Hello World” inside it.
Do it in one operation.
file_put_contents(‘example.txt’, “Hello World”);
How to read the entire content of a file named “example.txt” into a string. If there is no file found then it should echo “Failed to read the file.”
Save it to a variable called $content
$content = file_get_contents(‘example.txt’);
if ($content !== false) {
echo $content;
} else {
echo “Failed to read the file.”;
}
$content = file_get_contents(‘example.txt’);
Reads entire content of example.txt into $content.
file_exists(‘example.txt’);
Returns true if example.txt exists; false otherwise.
file_put_contents(‘example.txt’, “Hello, World!”);
Writes “Hello, World!” To example.txt, overwriting existing content.
What is this line of code likely doing?
define(‘APP_PATH’, dirname(__FILE__) . ‘/../‘;
Defines a constant ‘APP_PATH’ that holds the path to the parent directory of the current script file.
‘dirname(__FILE__)’ gets the directory of the current file, and appending ‘/../‘ navigates one directory up.