Using fopen() in PHP: Syntax, Parameters, and Practical Examples
This article explains the PHP fopen() function, detailing its syntax, parameters, and providing multiple code examples for reading, writing, appending files and opening URLs, while emphasizing proper mode selection and resource cleanup.
In PHP, the fopen() function can open a file or URL for reading or writing.
Syntax:
resource fopen ( string $filename , string $mode [, bool $use_include_path = false [, resource $context ]] )Parameters:
$filename : required, specifies the file or URL to open.
$mode : required, specifies the opening mode such as "r" (read), "w" (write), "a" (append), "x" (create), optionally with "b" for binary.
$use_include_path : optional, boolean indicating whether to search the include_path.
$context : optional, stream context resource for additional options.
Below are several common usage examples.
Example 1: Read file contents
<?php
$filename = "example.txt";
$file = fopen($filename, "r");
if ($file) {
while (!feof($file)) {
echo fgets($file);
}
fclose($file);
} else {
echo "Unable to open file!";
}
?>Example 2: Write file contents
<?php
$filename = "example.txt";
$file = fopen($filename, "w");
if ($file) {
fwrite($file, "Hello, World!");
fclose($file);
} else {
echo "Unable to open file!";
}
?>Example 3: Append to a file
<?php
$filename = "example.txt";
$file = fopen($filename, "a");
if ($file) {
fwrite($file, "Hello, PHP!");
fclose($file);
} else {
echo "Unable to open file!";
}
?>Example 4: Open a URL
<?php
$url = "http://www.example.com";
$file = fopen($url, "r");
if ($file) {
while (!feof($file)) {
echo fgets($file);
}
fclose($file);
} else {
echo "Unable to open URL!";
}
?>In summary, fopen() is a versatile PHP function for accessing files and URLs; choose the correct filename/URL and mode, handle optional parameters as needed, and always close the handle after operations to release resources.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
php Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
