Simple Machines Community Forum

Archived Boards and Threads... => Archived Boards => Parham's PHP Tutorials => Topic started by: Parham on April 17, 2004, 12:22:32 AM

Title: PHP Lesson 18 - filesystem functions
Post by: Parham on April 17, 2004, 12:22:32 AM
Filesystem Functions

The filesystem functions in PHP allow you to manipulate files.  You can open file, write to files, and updates files as you see fit with this set of functions.  The four main functions (at least in my opinion) for this group of functions are:

fopen - open a file to work with
fread - read the contents of a file
fwrite - write some content to a file
fclose - close a file you were working with

Using these functions is no different from using any other functions.  You simply have to read the documentation to learn about their arguments and what they return.  Please note the following URLs for references to the functions you will see in this tutorial.

http://www.php.net/manual/en/function.fopen.php
http://www.php.net/manual/en/function.fread.php
http://www.php.net/manual/en/function.fwrite.php
http://www.php.net/manual/en/function.fclose.php

If your scripts are running on a Unix operating system, you have to take extra care to see if you're allowed to read/write to the file you're trying to access.  When opening a file, you must always pass as arguments the location of the file your trying to open (either relative or absolute) and what you want to do with that file (read/write/append).

When opening files, these are the extra arguments you should be aware of (not all were included):
'r' - Open for reading only; place the file pointer at the beginning of the file.  If the file doesn't exist, you'll get an error.
'r+' - Open for reading and writing; place the file pointer at the beginning of the file.  If the file doesn't exist, you'll get an error.
'w' - Open for writing only; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it.  Note that when writing, you lose all the other content in the file - you overwrite.
'w+' - Open for reading and writing; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it.  Note that when writing, you lose all the other content in the file - you overwrite.
'a' - Open for writing only; place the file pointer at the end of the file. If the file does not exist, attempt to create it.
'a+' - Open for reading and writing; place the file pointer at the end of the file. If the file does not exist, attempt to create it.
'b' - binary.  This little mode can take up about 4 paragraphs of explanation as the PHP documentation clearly shows.  This mode must be the last letter if your mode consists of several of the above.

For example, to open a file just to read:

$filehandle = fopen('/path/to/file', 'r');


If you were on a windows platform and the file wasn't a standard text file, this would be a more suitable line:

$filehandle = fopen('/path/to/file', 'rb'); //b for binary


To write to a file or append to a file, these might be suitable lines of code:

$filehandle = fopen('/path/to/file', 'w'); //write to the file
$filehandle = fopen('/path/to/file', 'a'); //append to the file


fopen can also take a URL as an argument, but you can only read ('r' argument) from a URL, you cannot write/append to one.  After opening a file to read/write/append to, you can begin working with it using fread/fwrite.

PHP reads files in chunks (bytes).  When reading from a file, you must specify how many bytes you want to read.  You can read the entire file into memory, or you can read it in chunks.  The two examples given below show both methods (these two methods are very standard):

Read the entire file all at once

$filehandle = fopen('/path/to/file', 'rb');
$contents = fread($filehandle, filesize('/path/to/file'));


Read the file in portions

$filehandle = fopen('/path/to/file', 'r'); //open the file in read mode
while (!feof($filehandle)) { //is there more to read?
  $contents .= fread($filehandle, 1024); //read the file in 1 meg portions
}

note: feof() tests to see if we've reached the end of the file yet

Remember that when you write to a file, you must have permission to do so.  Writing or appending to a file is as simple as:

Write:

$filehandle = fopen('/path/to/file', 'w'); //write
fwrite($filehandle, 'new contents of file'); //fputs() can be used as well


append:

$filehandle = fopen('/path/to/file', 'a'); //append
fwrite($filehandle, 'new contents added at the end of the file'); //fputs() can be used as well


If you wish to add new lines to a file, you can simply use "\n" to go to the next line.  Please remember that you'll need to either concatenate "\n" or include "\n" in double quotes with all your text so it gets interpolated into the newline character.

After you open a file with fopen, and you read/write contents using fread/fwrite, you should ALWAYS close the file.  This doesn't take any extra effort.  Remember to always include code like:


fclose($filehandle);


If you don't close your file (with the filehandle) after you finish working with it, you risk problems occurring.  If you don't close a file after writing to it, you risk the contents of the file being lost.  If you open a file, but don't close it, you also risk corrupting the file (which means you'll lose partial or all parts of the file).

Extra notes:
- If you try to open a file to write/append to, and it doesn't exist, PHP will try to create it
- Depending on which operating system you're working on, you might have to use "\r\n" (carriage return and newline) to go to the next line.  If you don't open your files in binary mode (mode b), this will transparently be done for you.  Please refer to the PHP documentation located at http://www.php.net/manual/en/function.fopen.php for a clear explanation of when and how to use binary mode.
- You can open webpage URLs to read, but not to write.  You can open FTP URLs to read and write to.  Make sure to use the proper formatting for FTPs: "ftp:// username:password @ url.com"
- You must have permission to read/write to a file.  PHP reads and writes to files as user 'nobody'.  This is different from root access to the files.  A file created by the root does not belong to 'nobody', but a file created by 'nobody' does belong to the root.
- If you don't have root access or someone hosts your website for you, chances are you don't have root access.  Creating files through ftp and files through a PHP scripts are two different things, and neither has privileges to touch the other.  If you create a file with PHP, you cannot delete it with FTP software and visa versa.  Simple rule to remember is: "if it made it, it must take care of it"
- you can use file() to read the contents of a file or URL into an array.  You can use file_get_contents() to read an entire file into a variable.  Both functions are binary safe now so they should handle line endings properly.
Title: Re: PHP Lesson 18 - filesystem functions
Post by: Parham on April 17, 2004, 12:23:05 AM
Unknown, please add your comments, when I wrote it I KNOW I didn't include everything...
Title: Re: PHP Lesson 18 - filesystem functions
Post by: [Unknown] on April 17, 2004, 12:36:14 AM
I'd recommend a tutorial on reading the PHP/SMF prototype declarations.  Like, what is "void" and "int", etc.?

For r, r+, w, w+, a, a+ - I would put b as a note and make it clearer that you add that and when.

I'd make it clearer that basically:
  - r means READ.  If the file isn't there, you'll get an error.
  - r+ means read and write.  You'll still get an error if it's not already there.
  - w means OVERWRITE.  Whether the file was there or not, it will be deleted and replaced.
  - w+ means overwrite, but also read.  Whether the file was there or not, it will be deleted and replaced.
  - a means APPEND.  If the file isn't there, it will make it but otherwise it will leave it be.
  - a+ means append, but also read.  If it wasn't there already, it will create it.

> - Depending on which operating system you're working on, you might have to use "\r\n" (carriage return and newline) to go to the next line
Not entirely true.  If you don't open in binary on windows, it will make \n into \r\n.... you should just never write \r's.

> - You can open URLs to read, but not to write
Not entirely true; you can open FTP urls for write.

I also think the "file()" function is very useful, while not binary safe, and worth mentioning.

-[Unknown]
Title: Re: PHP Lesson 18 - filesystem functions
Post by: Parham on April 17, 2004, 11:46:00 AM
thanks unknown, i included all of your comments in there.  i think the lesson where i introduced php functions, i also explained what words like "void" and "int" were.
Title: Re: PHP Lesson 18 - filesystem functions
Post by: John on April 30, 2006, 07:25:04 PM
Its been a while since someone posted in here but i give it a go.

How do i read (fopen) an attachment? And do i have to do it in the Display.template.php?

if (file_exists(" <path> upload" )) {
      $file = fopen("<path> upload"","r"); // r = read
      $line = fgets($file,1000);
      echo #line;
Title: Re: PHP Lesson 18 - filesystem functions
Post by: Parham on May 08, 2006, 08:49:06 PM
Quote from: John on April 30, 2006, 07:25:04 PM
Its been a while since someone posted in here but i give it a go.

How do i read (fopen) an attachment? And do i have to do it in the Display.template.php?

if (file_exists(" <path> upload" )) {
      $file = fopen("<path> upload"","r"); // r = read
      $line = fgets($file,1000);
      echo #line;

this is something you should ask in the smf section of the website... though, it looks like you need a loop around your $line to read 1000 characters at a time.
Title: Re: PHP Lesson 18 - filesystem functions
Post by: nitins60 on September 17, 2006, 06:41:51 PM
One thing, i just want a simple .php script, which is able to show files in a directory(where it is installed),limited file name extensions, file size, date, hits. It should have an option to arrange files as per size, date,hits etc... Can you tell me/give me complete script for it. I don't have much knowledge in .php. So please
Title: Re: PHP Lesson 18 - filesystem functions
Post by: JayBachatero on September 28, 2006, 02:54:45 PM
http://mods.simplemachines.org/index.php?mod=477
Title: Re: PHP Lesson 18 - filesystem functions
Post by: thedrumchannell on October 12, 2006, 12:28:30 PM
Can you use fwrite(), or another function to change only parts of a page... here's an example:

Let's say we have a config.php page,

<?php

//  Settings
$apples 'something';
$oranges 'something else';

?>


In another file we have a form in which a user can input a new variable for oranges, "something new". I'm wanting the new file to change into this:

<?php

//  Settings
$apples 'something';
$oranges 'something new';

?>


How would someone go about doing this?
Title: Re: PHP Lesson 18 - filesystem functions
Post by: JayBachatero on October 12, 2006, 01:15:40 PM
No you can't use fwrite.  Try looking at how SMF does this for install.
Title: Re: PHP Lesson 18 - filesystem functions
Post by: thedrumchannell on October 12, 2006, 01:25:14 PM
I'm not that refined in PHP (this is why I am asking ;)) but in the SMF install file, all that I see is fwrite() when modifying the settings.php file.
Title: Re: PHP Lesson 18 - filesystem functions
Post by: JayBachatero on October 12, 2006, 01:31:46 PM
If I'm correct SMF reads the file.  Each line becomes an array and then it replaces the correct variables.  I started to work on something similar but its on my other HD.  If not I would show you.