Creating or Opening a File in PHP
By: David Sklar
Use fopen( ):
$fh = fopen('file.txt','r') or die("can't open file.txt: $php_errormsg");
The first argument to fopen( )is the file to open; the second argument is the mode to open the file in. The mode specifies what operations can be performed on the file (reading and/or writing), where the file pointer is placed after the file is opened (at the beginning or end of the file), whether the file is truncated to zero length after opening, and whether the file is created if it doesn't exist, as shown in Table below.
Mode |
Readable? |
Writeable? |
File pointer |
Truncate? |
Create? |
---|---|---|---|---|---|
r |
Yes |
No |
Beginning |
No |
No |
r+ |
Yes |
Yes |
Beginning |
No |
No |
w |
No |
Yes |
Beginning |
Yes |
Yes |
w+ |
Yes |
Yes |
Beginning |
Yes |
Yes |
a |
No |
Yes |
End |
No |
Yes |
a+ |
Yes |
Yes |
End |
No |
Yes |
On non-POSIX systems, such as Windows, you need to add a b to the mode when opening a binary file, or reads and writes get tripped up on NUL (ASCII 0) characters:
$fh = fopen('c:/images/logo.gif','rb');
To operate on a file, pass the file handle returned from fopen( ) to other I/O functions such as fgets( ), fputs( ), and fclose( ).
If the file given to fopen( ) doesn't have a pathname, the file is opened in the directory of the running script (web context) or in the current directory (command-line context).
You can also tell fopen( ) to search for the file to open in the include_path specified in your php.ini file by passing 1 as a third argument. For example, this searches for file.inc in the include_path:
$fh = fopen('file.inc','r',1) or die("can't open file.inc: $php_errormsg");
Archived Comments
1. this work is good
View Tutorial By: sanath at 2008-12-15 01:18:43
Comment on this tutorial
- Data Science
- Android
- AJAX
- ASP.net
- C
- C++
- C#
- Cocoa
- Cloud Computing
- HTML5
- Java
- Javascript
- JSF
- JSP
- J2ME
- Java Beans
- EJB
- JDBC
- Linux
- Mac OS X
- iPhone
- MySQL
- Office 365
- Perl
- PHP
- Python
- Ruby
- VB.net
- Hibernate
- Struts
- SAP
- Trends
- Tech Reviews
- WebServices
- XML
- Certification
- Interview
categories
Related Tutorials
PHP code to write to a CSV file for Microsoft Applications
PHP code to write to a CSV file from MySQL query
PHP code to import from CSV file to MySQL
Password must include both numeric and alphabetic characters - Magento
Error: Length parameter must be greater than 0
PHP file upload prompts authentication for anonymous users
PHP file upload with IIS on windows XP/2000 etc
Multiple File Upload in PHP using IFRAME
Resume or Pause File Uploads in PHP
Exception in module wampmanager.exe at 000F15A0 in Windows 8