Welcome to the PHP readfile() tutorial! In this lesson, we'll learn about the readfile() function, a handy tool for reading the contents of a file in PHP. Let's dive in! π³
readfile() Function πThe readfile() function is used to read and output the contents of a file directly to the browser. It's an easy way to send the contents of a file as a response, which is useful for displaying static content like HTML or CSS files.
readfile() Function π‘To use the readfile() function, you just need to pass the file path as an argument. Let's see a simple example:
<?php
// File path to our sample.txt
$file = 'sample.txt';
// Use readfile() to output the contents of the file
readfile($file);
?>In this example, we're reading the contents of sample.txt and outputting it directly to the browser.
readfile() can be useful when you have static files like HTML, CSS, JavaScript, or images that you want to serve from your PHP scripts. This can simplify your project structure and make it more manageable.
In this advanced example, we'll read the contents of a text file and parse the data. Here, we assume we have a CSV file with user data.
<?php
// File path to our userdata.csv
$file = 'userdata.csv';
// Use readfile() to get the contents of the file
$data = readfile($file);
// Convert the contents to an associative array using str_getcsv()
$users = array();
$line = str_getcsv($data);
foreach ($line as $key => $value) {
$users[] = [
'name' => $value[0],
'email' => $value[1]
];
}
// Now we can use the array as needed
print_r($users);
?>In this example, we're reading the contents of a CSV file, parsing it into an associative array, and then using the data as needed.
What does the `readfile()` function do in PHP?