PHP fopen() Function – Description, Parameters, Return Value, and Usage Examples
The article explains PHP's fopen() function, detailing how it opens files or URLs, describing each parameter (filename, mode, use_include_path, context), listing supported mode strings, and providing multiple code examples that illustrate typical read, write, and remote‑file operations.
fopen() opens a file or URL and binds it to a stream, returning a resource handle on success or FALSE on failure.
Parameters
filename – The path or URL to open. If it matches a registered protocol (e.g., http:// , ftp:// ), PHP uses the corresponding wrapper; otherwise it treats it as a local file.
mode – A string that specifies the access type. Supported values are: 'r' – read‑only, pointer at start 'r+' – read/write, pointer at start 'w' – write‑only, truncate to zero, create if missing 'w+' – read/write, truncate to zero, create if missing 'a' – write‑only, pointer at end, create if missing 'a+' – read/write, pointer at end, create if missing 'x' – create and write, fail if file exists 'x+' – create and read/write, fail if file exists
use_include_path – Optional boolean; if TRUE , PHP also searches the include_path for the file.
context – Optional stream context resource (available since PHP 5.0.0).
Return value
On success, fopen() returns a file‑pointer resource; on failure it returns FALSE .
Example usage
<?php
$handle = fopen("/home/rasmus/file.txt", "r");
$handle = fopen("/home/rasmus/file.gif", "wb");
$handle = fopen("http://www.example.com/", "r");
$handle = fopen("ftp://user:[email protected]/somefile.txt", "w");
?>The examples demonstrate opening a local file for reading, opening a local file for binary writing, reading from a remote HTTP resource, and writing to a remote FTP resource.
Laravel Tech Community
Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.
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.