This chapter will explain following functions related to files:
Files modes can be specified as one of the six options in this table.
If an attempt to open a file fails then fopen returns a value of false otherwise it returns a file pointer which is used for further reading or writing to that file.
After making a changes to the opened file it is important to close it with the fclose() function. The fclose() function requires a file pointer as its argument and then returns true when the closure succeeds or false if it fails.
The files's length can be found using the filesize() function which takes the file name as its argument and returns the size of the file expressed in bytes.
So here are the steps required to read a file with PHP.
The following example creates a new text file then writes a short text heading insite it. After closing this file its existence is confirmed using file_exist() function which takes file name as an argument
We have covered all the function related to file input and out in PHP File System Function chapter.
PHP functions are similar to other programming languages. A function is a piece of code which takes one more input in the form of parameter and does some processing and returns a value.
You already have seen many functions like fopen() and fread() etc. They are built-in functions but PHP gives you option to create your own functions as well.
There are two parts which should be clear to you:
Please refer to PHP Function Reference for a complete set of useful functions.
Note that while creating a function its name should start with keyword function and all the PHP code should be put inside { and } braces as shown in the following example below:
This will display following result:
This will display following result:
Any changes made to an argument in these cases will change the value of the original variable. You can pass an argument by reference by adding an ampersand to the variable name in either the function call or the function definition.
Following example depicts both the cases.
This will display following result:
You can return more than one value from a function using return array(1,2,3,4).
Following example takes two integer parameters and add them together and then returns their sum to the calling program. Note that return keyword is used to return a value from a function.
This will display following result:
Following function prints NULL in case use does not pass any value to this function.
This will produce following result:
This will display following result:
- Opening a file
- Reading a file
- Writing a file
- Closing a file
Opening and Closing Files
The PHP fopen() function is used to open a file. It requires two arguments stating first the file name and then mode in which to operate.Files modes can be specified as one of the six options in this table.
Mode | Purpose |
---|---|
r | Opens the file for reading only. Places the file pointer at the beginning of the file. |
r+ | Opens the file for reading and writing. Places the file pointer at the beginning of the file. |
w | Opens the file for writing only. Places the file pointer at the beginning of the file. and truncates the file to zero length. If files does not exist then it attemts to create a file. |
w+ | Opens the file for reading and writing only. Places the file pointer at the beginning of the file. and truncates the file to zero length. If files does not exist then it attemts to create a file. |
a | Opens the file for writing only. Places the file pointer at the end of the file. If files does not exist then it attemts to create a file. |
a+ | Opens the file for reading and writing only. Places the file pointer at the end of the file. If files does not exist then it attemts to create a file. |
After making a changes to the opened file it is important to close it with the fclose() function. The fclose() function requires a file pointer as its argument and then returns true when the closure succeeds or false if it fails.
Reading a file
Once a file is opened using fopen() function it can be read with a function called fread(). This function requires two arguments. These must be the file pointer and the length of the file expressed in bytes.The files's length can be found using the filesize() function which takes the file name as its argument and returns the size of the file expressed in bytes.
So here are the steps required to read a file with PHP.
- Open a file using fopen() function.
- Get the file's length using filesize() function.
- Read the file's content using fread() function.
- Close the file with fclose() function.
<html> <head> <title>Reading a file using PHP</title> </head> <body> <?php $filename = "/home/user/guest/tmp.txt"; $file = fopen( $filename, "r" ); if( $file == false ) { echo ( "Error in opening file" ); exit(); } $filesize = filesize( $filename ); $filetext = fread( $file, $filesize ); fclose( $file ); echo ( "File size : $filesize bytes" ); echo ( "<pre>$filetext</pre>" ); ?> </body> </html> |
Writing a file
A new file can be written or text can be appended to an existing file using the PHP fwrite() function. This function requires two arguments specifying a file pointer and the string of data that is to be written. Optionally a third integer argument can be included to specify the length of the data to write. If the third argument is included, writing would will stop after the specified length has been reached.The following example creates a new text file then writes a short text heading insite it. After closing this file its existence is confirmed using file_exist() function which takes file name as an argument
<?php $filename = "/home/user/guest/newfile.txt"; $file = fopen( $filename, "w" ); if( $file == false ) { echo ( "Error in opening new file" ); exit(); } fwrite( $file, "This is a simple test\n" ); fclose( $file ); ?> <html> <head> <title>Writing a file using PHP</title> </head> <body> <?php if( file_exist( $filename ) ) { $filesize = filesize( $filename ); $msg = "File created with name $filename "; $msg .= "containing $filesize bytes"; echo ($msg ); } else { echo ("File $filename does not exit" ); } ?> </body> </html> |
PHP functions are similar to other programming languages. A function is a piece of code which takes one more input in the form of parameter and does some processing and returns a value.
You already have seen many functions like fopen() and fread() etc. They are built-in functions but PHP gives you option to create your own functions as well.
There are two parts which should be clear to you:
- Creating a PHP Function
- Calling a PHP Function
Please refer to PHP Function Reference for a complete set of useful functions.
Creating PHP Function:
Its very easy to create your own PHP function. Suppose you want to create a PHP function which will simply write a simple message on your browser when you will call it. Following example creates a function called writeMessage() and then calls it just after creating it.Note that while creating a function its name should start with keyword function and all the PHP code should be put inside { and } braces as shown in the following example below:
<html> <head> <title>Writing PHP Function</title> </head> <body> <?php /* Defining a PHP Function */ function writeMessage() { echo "You are really a nice person, Have a nice time!"; } /* Calling a PHP Function */ writeMessage(); ?> </body> </html> |
You are really a nice person, Have a nice time! |
PHP Functions with Parameters:
PHP gives you option to pass your parameters inside a function. You can pass as many as parameters your like. These parameters work like variables inside your function. Following example takes two integer parameters and add them together and then print them.<html> <head> <title>Writing PHP Function with Parameters</title> </head> <body> <?php function addFunction($num1, $num2) { $sum = $num1 + $num2; echo "Sum of the two numbers is : $sum"; } addFunction(10, 20); ?> </body> </html> |
Sum of the two numbers is : 30 |
Passing Arguments by Reference:
It is possible to pass arguments to functions by reference. This means that a reference to the variable is manipulated by the function rather than a copy of the variable's value.Any changes made to an argument in these cases will change the value of the original variable. You can pass an argument by reference by adding an ampersand to the variable name in either the function call or the function definition.
Following example depicts both the cases.
<html> <head> <title>Passing Argument by Reference</title> </head> <body> <?php function addFive($num) { $num += 5; } function addSix(&$num) { $num += 6; } $orignum = 10; addFive( &$orignum ); echo "Original Value is $orignum<br />"; addSix( $orignum ); echo "Original Value is $orignum<br />"; ?> </body> </html> |
Original Value is 15 Original Value is 21 |
PHP Functions retruning value:
A function can return a value using the return statement in conjunction with a value or object. return stops the execution of the function and sends the value back to the calling code.You can return more than one value from a function using return array(1,2,3,4).
Following example takes two integer parameters and add them together and then returns their sum to the calling program. Note that return keyword is used to return a value from a function.
<html> <head> <title>Writing PHP Function which returns value</title> </head> <body> <?php function addFunction($num1, $num2) { $sum = $num1 + $num2; return $sum; } $return_value = addFunction(10, 20); echo "Returned value from the function : $return_value"; ?> </body> </html> |
Returned value from the function : 30 |
Setting Default Values for Function Parameters:
You can set a parameter to have a default value if the function's caller doesn't pass it.Following function prints NULL in case use does not pass any value to this function.
<html> <head> <title>Writing PHP Function which returns value</title> </head> <body> <?php function printMe($param = NULL) { print $param; } printMe("This is test"); printMe(); ?> </body> </html> |
This is test |
Dynamic Function Calls:
It is possible to assign function names as strings to variables and then treat these variables exactly as you would the function name itself. Following example depicts this behaviour.<html> <head> <title>Dynamic Function Calls</title> </head> <body> <?php function sayHello() { echo "Hello<br />"; } $function_holder = "sayHello"; $function_holder(); ?> </body> </html> |
Hello
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
No comments:
Post a Comment