15 1 0 4000 1 https://codeblock.co.za 300 true 0

fopen()

0 Comments

Programming Language

PHP [Versions: 4, 5, 7, 8]

Syntax

Typical Usage

Opens a file or a URL in PHP and binds a named resource, specified by filename, to a stream.

Accepted Parameters

  • $filename (string) (Required): The filename (specifically the full path to the file).
  • $mode (string) (Required): The type of access you require. Possible values include any one of the following:
    • ‘r’: Opens the file in read-only mode and places the file pointer at the beginning of the file.
    • ‘r+’: Opens the file for reading and writing and places the file pointer at the beginning of the file.
    • ‘w’: Opens for the file in write-only, places the file pointer at the beginning of the file and truncates the file to zero length. If the file does not exist, fopen() will attempt to create it.
    • ‘w+’ Open for reading and writing, places the file pointer at the beginning of the file and truncates the file to zero length. If the file does not exist, fopen() will attempt to create it.
    • ‘a’: Opens the file in write-only mode and places the file pointer at the end of the file. If the file does not exist, fopen() will attempt to create it.
    • ‘a+’: Opens the file for reading and writing and places the file pointer at the end of the file. If the file does not exist, fopen() will attempt to create it.
    • ‘x’: Creates a file and opens it for writing only, then places the file pointer at the beginning of the file. If the file already exists, fopen() will fail by returning false and generating an error of level E_WARNING.
    • ‘x+’: Creates a file and opens it for reading and writing then places the file pointer at the beginning of the file. If the file already exists, fopen() will fail by returning false and generating an error of level E_WARNING.
    • ‘c’: Opens the file in write-mode. If the file does not exist, fopen() will attempt to create it. If it exists, an won’t be thrown and the file will not be truncated. The file pointer is placed on the beginning of the file.
    • ‘c+’: Opens the file for reading and writing; otherwise it has the same behavior as ‘c’.
  • use_include_path (boolean) (Optional) (Default = false): Set this to true if you need to use include_path.
  • context (resource) (Optional):┬áContext support was added with PHP 5.0.0 For a description of contexts, refer to Streams on the PHP Manual.

Return Value(s)

Returns a file pointer resource on success, or false on failure.

Notes

  • Upon failure, an E_WARNING is emitted.

Examples of fopen()

Example 1

<?php
$uploaded_file =$_FILES['uploaded-csv']
$my_file= fopen($uploaded_file['tmp_name'], 'r');

The above code will open an uploaded file in read-only mode.

Was This Helpful?

Previous Post
pathinfo()
Next Post
fgetcsv()

0 Comments

Leave a Reply