Home > Articles

PHP Basics

This chapter is from the book

3.6 Working with Files

Workingwith files is easy in PHP. Files need not be located on the local machine to be accessible. It is also possible to work with remote files. In this section you learn to work with local and remote files efficiently.

3.6.1 Performing Basic Operations with Local Files

Working with files is an important issue for every programming language. The same applies to PHP. Functions for accessing the filesystem allow the user to build highly sophisticated applications. With the help of files it is possible to store information about what's going on in your application, or you can access external data sources. Nowadays a lot of information is stored in databases, but files are still a fundamental component of every applications. This section guides you through PHP's functions related to files and filesystems.

The first thing you have to know about files is how to open and close them:

<?php
    $handle = @fopen("data.file", "r") or 
        die ("cannot open file");
    echo 'File has successfully been opened<br>';
    fclose($handle);
?>

In this example fopen and fclose are used. These functions are available in many programming languages and have been borrowed from C.

In the script a file called data.file is opened for reading. This is done with the fopen function. The first parameter defines the name of the file that has to be opened. The second parameter tells PHP in which mode the file has to be opened. The following modes are supported by PHP:

  • r—Reading only

  • r+—Opens for reading and writing

  • w—Opens the file for writing and creates an empty file

  • w+—Opens the file for reading and writing

  • a—Opens the file for writing only and sets the pointer to the end of the file

  • a+—Opens the file for reading and writing and sets the pointer to the end of the file

Closing the file again is done by using fclose. Let's have a look at the content of the file the script has processed:

Hans::Vienna::Database Developer
Epi::Vienna::Consultant
Kuli::Vienna::Sales Manager
Sunny::Murau::Student

The file consists of four lines. Let's see what you can find out about the file using a Unix command:

[hs@athlon test]$ ls -l data.file
-rw-r--r--  1 hs    cybertec   107 Oct 21 13:21 data.file

The file is 107 bytes long and belongs to user hs in group cybertec.

Sometimes it is necessary to find out even more about a file. Therefore PHP provides a command called stat:

<?php
    $fileinfo = stat("data.file") or
        die ("cannot find information about file"); 

    echo "device: $fileinfo[0]<br>\n";
    echo "inode: $fileinfo[1]<br>\n";
    echo "inode protection mode: $fileinfo[2]<br>\n";
    echo "number of links: $fileinfo[3]<br>\n";
    echo "user id of owner: $fileinfo[4]<br>\n";
    echo "group id of owner: $fileinfo[5]<br>\n";
    echo "device type if inode device: $fileinfo[6]<br>\n";
    echo "size in bytes: $fileinfo[7]<br>\n";
    echo "time of last access: $fileinfo[8]<br>\n";
    echo "time of last modification: $fileinfo[9]<br>\n";
    echo "time of last change: $fileinfo[10]<br>\n";
    echo "blocksize for filesystem I/O: $fileinfo[11]<br>\n";
    echo "number of block allocated: $fileinfo[12]<br>\n";
?>

If you execute the script, a lot of information will be displayed on the screen:

device: 773
inode: 470215
inode protection mode: 33188
number of links: 1
user id of owner: 500
group id of owner: 500
device type if inode device: 2817
size in bytes: 107
time of last access: 1003663763
time of last modification: 1003663300
time of last change: 1003663300
blocksize for filesystem I/O: 4096
number of block allocated: 8

The output displayed by stat contains the same information that is also returned by the C function PHP's stat function is based on. To show you that PHP's functions for working with filesystems are based on C, we have included the structure returned by C's stat function:

struct stat {
    dev_t     st_dev;   /* device */
    ino_t     st_ino;   /* inode */
    mode_t    st_mode;   /* protection */
    nlink_t    st_nlink;  /* number of hard links */
    uid_t     st_uid;   /* user ID of owner */
    gid_t     st_gid;   /* group ID of owner */
    dev_t     st_rdev;   /* device type (if inode device) */
    off_t     st_size;   /* total size, in bytes */
    unsigned long st_blksize; /* blocksize for filesystem I/O */
    unsigned long st_blocks;  /* number of blocks allocated */
    time_t    st_atime;  /* time of last access */
    time_t    st_mtime;  /* time of last modification */
    time_t    st_ctime;  /* time of last change */
};

As you can see, the content of the result generated by PHP is nearly equal to the result generated by C. This shows clearly that PHP and C are strongly related. Knowing this will make it easy for you to understand the behavior and the functions of the PHP interpreter.

Up to now, you have learned to open and close files. You have also seen how to find out information about a file, but you haven't read and written data yet. Let's start with an example where you can see how data can be read from a file:

<?php
    $file = "data.file";
 
    $handle = fopen($file, "r") or
        die ("cannot open file");
    $fileinfo = stat($file);
 
    $data = fgets($handle, $fileinfo[7]);
    echo "data using fgets: <br>$data<br><br>";
 
    $data = fread($handle, $fileinfo[7]);
    echo "data using fread: <br>$data<br><br>";
 
    rewind($handle);
    echo "Pointer is at position: ".ftell($handle)."<br>";
 
    fseek($handle, 20);
    echo "Pointer is at position: ".ftell($handle);
 
    fclose($handle);
?>

First, a file is opened and information about that file is retrieved by using stat. $fileinfo[7] contains the size of the file. Although you have passed the content of $fileinfo[7] to fgets, only the first line will be read because fgets interprets newline characters. After reading the first line, the pointer is set to the beginning of the second line. Then fread is used. This time the rest of the file will be read and displayed on the screen because fread does not take care of newline characters. After reading all data, the file pointer is at the end of the file. To perform further reads, it is necessary to set it to a different position. Therefore rewind is used to set the pointer to the first position in the file. After that fseek sets the pointer to the 20th position in the file. Fseek and rewind are two essential functions when working with files because you can use them to go to any position within the file you are working with. Let's have a look at the output of the script:

data using fgets:
Hans::Vienna::Database Developer

data using fread:
Epi::Vienna::Consultant Kuli::Vienna::Sales Manager Sunny::Murau::Student

Pointer is at position: 0
Pointer is at position: 20

As you can see, the result is displayed on the screen correctly.

The next example shows how data can be written to a file:

<?php
    $file = "data.file2";
 
    $handle = fopen($file, "w") or
        die ("cannot open file");
    fputs($handle, "Hello World");
    fclose($handle);
?>

$handle contains the pointer of the new file created by fopen. Then fputs is calledand a string is written to the file before closing it.

Up to now, you have only used rudimentary I/O functions. In some cases, it is more comfortable to read an entire file into an array:

<?php
    $file = "data.file";
 
    $data = file($file);
 
    echo '<table border="1"><tr>';
    echo "<th>name</th><th>location</th><th>profession</th></tr>";
 
    foreach     ($data as $line)
    {
        $val = explode("::", $line);
        echo "<tr><td>$val[0]</td><td>$val[1]</td><td>
            $val[2]</td></tr>";
    }
    echo "</table>";
?>

Reading a file into an array can be done with a function called file. To use file, it is not necessary to open the file first with fopen becausethis done implicitly by file. An array is returned. In the example the array is processed line by line and the string in the line is split after every ::. That way an array called $val is initialized every time the loop is processed and a table can be generated, which you can see in Figure 3.2.

Figure 3.2Figure 3.2 A simple table.

If you want to display the content of the file on the screen without processing the data beforehand, you can use the readfile function instead. readfile(filename) opens a file and displays the content on the screen directly. This is very useful when the file already contains HTML code.

3.6.2 Performing Basic Operations with Remote Files

In the previous section you have seen how local files can be treated with PHP. Remote files can be processed in a similar way.

Here is the example you have just seen, but this time the data comes from a remote host:

<?php
    $file = "http://212.186.25.254:/test/data.file";
 
    $data = file($file);
 
    echo '<table border="1"><tr>';
    echo "<th>name</th><th>location</th><th>profession</th></tr>";
 
    foreach     ($data as $line)
    {
        $val = explode("::", $line);
        echo "<tr><td>$val[0]</td><td>$val[1]</td><td>
            $val[2]</td></tr>";
    }
    echo "</table>";
?>

As you can see, the only change that has to be made is that the position of the file is now defined by an URL. If you have the permissions to read that file, it can be processed like any other file.

Every time the script is processed, however, the Web server will add one line to the logfile:

212.186.25.254 - - [21/Oct/2001:16:30:02 +0200] "GET /test/data.file HTTP/1.0"
 200 107 "-" "PHP/4.0.4pl1"

As we have already mentioned, working with remote files works just the same way as with local files. However, some important things have to be taken into consideration:

<?php
    $file = "http://212.186.25.254:/test/data.file";
    $handle = fopen($file, "a+") or
        die ("cannot open $file");
    fputs($handle, "Pat::Indianapolis::Lawyer") or
        die ("cannot write to file");
    fclose($handle) or
        die ("cannot close file");
    echo "it works";
?>

Most people expect that the script will append data to the remote file, but this does not happen:

[hs@athlon test]$ cat data.file
Hans::Vienna::Database Developer
Epi::Vienna::Consultant
Kuli::Vienna::Sales Manager
Sunny::Murau::Student

Nothing has been appended to the remote file, although the output of the script is "it works" and no error has occurred while executing. This has to be taken into consideration when working with remote files; otherwise, you might wonder why your application returns no errors and produces no output.

3.6.3 Additional Filesystem Functions

As you have already seen, PHP offers functions for working with local and remote files. Up to now, you have seen how to perform all basic operations. In this section you will see that PHP provides a lot more functions than you have already seen:

  • string basename (string path [, string suffix])—If you pass a filename including the path to basename, the filename without path will be returned.

  • int chgrp (string filename, mixed group)chgrp can be used to change the group a file belongs to.

  • int chmod (string filename, int mode)chmod can be used to change the mode of a file. This function does not work on Windows servers.

  • int chown (string filename, mixed user)chown can be used to change the owner of a file.

  • void clearstatcache (void)—Clears file stat cache. Usually the result of stat is cached because it takes a lot of time to retrieve status information about a file. With the help of clearstatcache, you can force PHP to redo the status-checking function.

  • int copy (string source, string dest)copy can be used to copy files.

  • string dirname (string path)dirname is the counterpart of basenames—it returns the path to a file.

  • float diskfreespace (string directory)—Can be used to find out how much space is left in the current directory.

  • float disk_total_space (string directory)—Returns the total amount of storage provided by the partition the directory passed to the function provides.

  • bool fclose (int fp)—Closes an open file.

  • int feof (int fp)—Checks whether the pointer is set to EOF (end of file).

  • int fflush (int fp)—Flushes the buffered output to disk.

  • string fgetc (int fp)—Reads a single character from the file.

  • array fgetcsv (int fp, int length [, string delimiter])—Reads a comma-separated values (CSV) file and returns an array of values. The delimiter to split a line can be passed to the function optionally.

  • string fgets (int fp, int length)—Can be used to read from the file.

  • string fgetss (int fp, int length [, string allowable_tags])—Is equal to fgets but tries to strip HTML tags.

  • array file (string filename [, int use_include_path])—Returns the content of a file in an array.

  • bool file_exists (string filename)—Returns true if the file passed to it exists.

  • int fileatime (string filename)—Retrieves the access time of a file.

  • int filectime (string filename)—Returns the modification time of the inode number.

  • int filegroup (string filename)—Returns the group a file belongs to.

  • int fileinode (string filename)—Retrieves the inode number of file.

  • int filemtime (string filename)—Returns modification time.

  • int fileowner (string filename)—Returns owner of file.

  • int fileperms (string filename)—Returns the permissions of the file.

  • int filesize (string filename)—Returns the size of the file.

  • string filetype (string filename)—Returns the type of a file (fifo, char, dir, block, link, file, or unknown).

  • bool flock (int fp, int operation [, int wouldblock])—Can be used to lock files in an advisory way.

  • int fopen (string filename, string mode [, int use_include_path])—Opens a file or an URL and returns a file handle.

  • int fpassthru (int fp)—Writes all data from the current position of the file pointer to the end of the file on standard output.

  • int fputs (int fp, string str [, int length])—Writes data to a file starting at the current position of the file pointer.

  • string fread (int fp, int length)—Binary-safe file read.

  • mixed fscanf (int handle, string format [, string var1...])—Interprets the input based on a format.

  • int fseek (int fp, int offset [, int whence])—Can be used to move the file pointer within a file. whence can be—SEEK_SET (set position of the file pointer equal to offset bytes), SEEK_CUR (set position of file pointer to current location plus offset), or SEEK_END (set position of file pointer to end-of-file plus offset).

  • array fstat (int fp)—Retrieves information about a file.

  • int ftell (int fp)—Can be used to find out on which position the file pointer can be found.

  • int ftruncate (int fp, int size)—Can be used to truncate the file to a certain length.

  • int fwrite (int fp, string string, int [length])—Binary-safe file write.

  • int set_file_buffer (int fp, int buffer)—Modifies the file buffer to a certain size; by default the size is 8k.

  • bool is_dir (string filename)—Can be used to find out whether the filename is a directory.

  • bool is_executable (string filename)—Checks whether the given file is executable.

  • bool is_file (string filename)—Checks whether filename is a file.

  • bool is_link (string filename)—Checks whether filename is a symbolic link.

  • bool is_readable (string filename)—Checks whether a file is readable.

  • bool is_writable (string filename) and bool is_writeable (string filename)—Checks if a file is writable.

  • bool is_uploaded_file (string filename)—Returns true if file was uploaded using HTTP POST.

  • int link (string target, string link)—Creates a hard link.

  • int linkinfo (string path)—Returns information about a link.

  • int mkdir (string pathname, int mode)—Creates a new directory.

  • bool move_uploaded_file (string filename, string destination)—Can be used to change the location of an uploaded file.

  • array pathinfo (string path)—Returns information about a path in an array.

  • int pclose (int fp)—Closes a pipe opened with popen.

  • int popen (string command, string mode)—Opens a pipe.

  • int readfile (string filename, int [use_include_path])—Reads the data from a file and prints it on standard output.

  • string readlink (string path)—Returns the target of a symbolic link.

  • int rename (string oldname, string newname)—Renames a file.

  • int rewind (int fp)—Sets the pointer to the beginning of the file.

  • int rmdir (string dirname)—Removes a directory.

  • array stat (string filename)—Retrieves detailed information about a file.

  • array lstat (string filename)—Returns information about a symbolic link.

  • string realpath (string path)—Returns the canonicalized absolute pathname.

  • int symlink (string target, string link)—Generates a symbolic link to a file.

  • string tempnam (string dir, string prefix)—Creates a unique temporary filename.

  • int tmpfile (void)—Creates a temporary file with a unique filename.

  • int touch (string filename, int [time])—Sets modification time of the file to the current time.

  • int umask (int mask)—Modifies the current umask of a file.

  • int unlink (string filename)—Deletes a file.

As you can see, PHP provides an endless list of built-in functions. Most functions work with all common filesystems. Especially on Unix systems, PHP shows its tremendous power because some functions can only be used on Unix.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020