0% found this document useful (0 votes)
8 views

Unit 3 PHP

The document discusses various PHP file handling functions including opening, reading, writing, appending, deleting, and uploading files. It provides code examples for using functions like fopen(), fread(), fwrite(), fgets(), unlink(), and move_uploaded_file() to perform common file operations in PHP.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

Unit 3 PHP

The document discusses various PHP file handling functions including opening, reading, writing, appending, deleting, and uploading files. It provides code examples for using functions like fopen(), fread(), fwrite(), fgets(), unlink(), and move_uploaded_file() to perform common file operations in PHP.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

Unit 3:

Working with File and Directories in php


PHP File Handling
PHP File System allows us to create file, read file line by line, read file character by
character, write file, append file, delete file and close file.

PHP Open File


PHP fopen() function is used to open file or URL and returns resource. The fopen()
function accepts two arguments: $filename and $mode. The $filename represents the
file to be opended and $mode represents the file mode for example read-only, read-
write, write-only etc.

Syntax

1. resource fopen ( string $filename , string $mode [, bool $use_include_path = f


alse [, resource $context ]] )

PHP Open File Mode

S.no Mode Description


1. r Opens file in read-only mode. It places the file pointer at the beginning of
the file.
2. r+ Opens file in read-write mode. It places the file pointer at the beginning of
the file.
3. w Opens file in write-only mode. It places the file pointer to the beginning of
the file and truncates the file to zero length. If file is not found, it creates a
new file.

4. w+ Opens file in read-write mode. It places the file pointer to the beginning of
the file and truncates the file to zero length. If file is not found, it creates a
new file.

5. a Opens file in write-only mode. It places the file pointer to the end of the
file. If file is not found, it creates a new file.

6. a+ Opens file in read-write mode. It places the file pointer to the end of the
file. If file is not found, it creates a new file.
7. x Creates and opens file in write-only mode. It places the file pointer at the
beginning of the file. If file is found, fopen() function returns FALSE.

8. x+ It is same as x but it creates and opens file in read-write mode.

9. c Opens file in write-only mode. If the file does not exist, it is created. If it
exists, it is neither truncated (as opposed to 'w'), nor the call to this
function fails (as is the case with 'x'). The file pointer is positioned on the
beginning of the file

10. c+ It is same as c but it opens file in read-write mode.

PHP Open File Example


1. <?php
2. $handle = fopen("c:\\folder\\file.txt", "r");
3. ?>

PHP Read File


PHP provides various functions to read data from file. There are different functions that
allow you to read all file data, read data line by line and read data character by
character.

The available PHP file read functions are given below.

o fread()
o fgets()
o fgetc()

PHP Read File - fread()


The PHP fread() function is used to read data of the file. It requires two arguments: file
resource and file size.

Syntax
1. string fread (resource $handle , int $length )

$handle represents file pointer that is created by fopen() function.


$length represents length of byte to be read.

Example
1. <?php
2. $filename = "c:\\file1.txt";
3. $fp = fopen($filename, "r");//open file in read mode
4.
5. $contents = fread($fp, filesize($filename));//read file
6.
7. echo "<pre>$contents</pre>";//printing data of file
8. fclose($fp);//close file
9. ?>

Output

this is first line


this is another line
this is third line

PHP Read File - fgets()


The PHP fgets() function is used to read single line from the file.

Syntax
1. string fgets ( resource $handle [, int $length ] )

Example
1. <?php
2. $fp = fopen("c:\\file1.txt", "r");//open file in read mode
3. echo fgets($fp);
4. fclose($fp);
5. ?>

Output

this is first line


PHP Read File - fgetc()
The PHP fgetc() function is used to read single character from the file. To get all data
using fgetc() function, use !feof() function inside the while loop.

Syntax
1. string fgetc ( resource $handle )
Example
1. <?php
2. $fp = fopen("c:\\file1.txt", "r");//open file in read mode
3. while(!feof($fp)) {
4. echo fgetc($fp);
5. }
6. fclose($fp);
7. ?>

Output

this is first line this is another line this is third line

PHP Write File


PHP fwrite() and fputs() functions are used to write data into file. To write data into file,
you need to use w, r+, w+, x, x+, c or c+ mode.

PHP Write File - fwrite()


The PHP fwrite() function is used to write content of the string into file.

Syntax

1. int fwrite ( resource $handle , string $string [, int $length ] )

Example
1. <?php
2. $fp = fopen('data.txt', 'w');//opens file in write-only mode
3. fwrite($fp, 'welcome ');
4. fwrite($fp, 'to php file write');
5. fclose($fp);
6.
7. echo "File written successfully";
8. ?>

Output: data.txt

welcome to php file write

PHP Overwriting File


If you run the above code again, it will erase the previous data of the file and writes
the new data. Let's see the code that writes only new data into data.txt file.

1. <?php
2. $fp = fopen('data.txt', 'w');//opens file in write-only mode
3. fwrite($fp, 'hello');
4. fclose($fp);
5.
6. echo "File written successfully";
7. ?>

Output: data.txt

hello

PHP Append to File


If you use a mode, it will not erase the data of the file. It will write the data at the end
of the file. Visit the next page to see the example of appending data into file.

You can append data into file by using a or a+ mode in fopen() function. Let's see a
simple example that appends data into data.txt file.
Let's see the data of file first.

data.txt

welcome to php file write

PHP Append to File - fwrite()


The PHP fwrite() function is used to write and append data into file.

Example

1. <?php
2. $fp = fopen('data.txt', 'a');//opens file in append mode
3. fwrite($fp, ' this is additional text ');
4. fwrite($fp, 'appending data');
5. fclose($fp);
6.
7. echo "File appended successfully";
8. ?>

Output: data.txt

welcome to php file write this is additional text appending data

PHP Delete File


In PHP, we can delete any file using unlink() function. The unlink() function accepts one
argument only: file name. It is similar to UNIX C unlink() function.

PHP unlink() generates E_WARNING level error if file is not deleted. It returns TRUE if
file is deleted successfully otherwise FALSE.

Syntax

1. bool unlink ( string $filename [, resource $context ] )

$filename represents the name of the file to be deleted.


PHP Delete File Example
1. <?php
2. $status=unlink('data.txt');
3. if($status){
4. echo "File deleted successfully";
5. }else{
6. echo "Sorry!";
7. }
8. ?>

Output

File deleted successfully

PHP File Upload


PHP allows you to upload single and multiple files through few lines of code only.

PHP file upload features allows you to upload binary and text files both. Moreover, you
can have the full control over the file to be uploaded through PHP authentication and
file operation functions.

PHP $_FILES
The PHP global $_FILES contains all the information of file. By the help of $_FILES
global, we can get file name, file type, file size, temp file name and errors associated
with file.

Here, we are assuming that file name is filename.

$_FILES['filename']['name']
returns file name.

$_FILES['filename']['type']
returns MIME type of the file.
$_FILES['filename']['size']
returns size of the file (in bytes).

$_FILES['filename']['tmp_name']
returns temporary file name of the file which was stored on the server.

$_FILES['filename']['error']
returns error code associated with this file.

move_uploaded_file() function
The move_uploaded_file() function moves the uploaded file to a new location. The
move_uploaded_file() function checks internally if the file is uploaded thorough the
POST request. It moves the file if it is uploaded through the POST request.

Syntax

1. bool move_uploaded_file ( string $filename , string $destination )

PHP File Upload Example


File: uploadform.html

1. <form action="uploader.php" method="post" enctype="multipart/form-


data">
2. Select File:
3. <input type="file" name="fileToUpload"/>
4. <input type="submit" value="Upload Image" name="submit"/>
5. </form>
File: uploader.php

1. <?php
2. $target_path = "e:/";
3. $target_path = $target_path.basename( $_FILES['fileToUpload']['name']);
4.
5. if(move_uploaded_file($_FILES['fileToUpload']['tmp_name'], $target_path)) {
6. echo "File uploaded successfully!";
7. } else{
8. echo "Sorry, file not uploaded, please try again!";
9. }

PHP Download File


PHP enables you to download file easily using built-in readfile() function. The readfile()
function reads a file and writes it to the output buffer.

PHP readfile() function


Syntax

1. int readfile ( string $filename [, bool $use_include_path = false [, resource $con


text ]] )

$filename: represents the file name

$use_include_path: it is the optional parameter. It is by default false. You can set it to


true to the search the file in the included_path.

$context: represents the context stream resource.

int: it returns the number of bytes read from the file.

PHP Download File Example: Text File

1. <?php
2. $file_url = 'http://www.javatpoint.com/f.txt';
3. header('Content-Type: application/octet-stream');
4. header("Content-Transfer-Encoding: utf-8");
5. header("Content-
disposition: attachment; filename=\"" . basename($file_url) . "\"");
6. readfile($file_url);
7. ?>
PHP Download File Example: Binary File
File: download2.php
1. <?php
2. $file_url = 'http://www.myremoteserver.com/file.exe';
3. header('Content-Type: application/octet-stream');
4. header("Content-Transfer-Encoding: Binary");
5. header("Content-
disposition: attachment; filename=\"" . basename($file_url) . "\"");
6. readfile($file_url);
7. ?>

PHP Directory Functions


The directory functions allow you to retrieve information about directories and their contents.

S.no Function Description


1 chdir() Changes the current directory

2 chroot() Changes the root directory

3 closedir() Closes a directory handle

4 dir() Returns an instance of the Directory class

5 getcwd() Returns the current working directory

6 opendir() Opens a directory handle

7 rewinddir() Resets a directory handle

8 readdir() Returns an entry from a directory handle

9 scandir() Returns an array of files and directories of a specified directory

You might also like