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

unit 4 php

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views

unit 4 php

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

UNIT-IV

PHP Advanced Concepts-Reading and Writing Files – Reading Data from a


File.
PHP File Handling
File handling is an important part of any web application. You often need to open and process a file
for different tasks.
PHP has several functions for creating, reading, uploading, and editing files.
PHP reading file
PHP read file () Function
There ad file () function reads a file and writes it to the output buffer.
As somehow have a text file called "webdictionary.txt", stored on the server, that looks like this:
The PHP code to read the file and write it to the output buffer is as follows (thereadfile() function returns
the number of bytes read on success):
Example
<?php
Echo read file("webdictionary.txt");
?>
There ad file() function is useful if all you want to do is open up a file and read its contents. Output:
AJAX=AsynchronousJavaScriptandXMLCSS=CascadingStyleSheetsHTML=HyperText Markup Language
PHP = PHP Hypertext Preprocessor SQL = Structured Query Language SVG
=Scalable Vector Graphics XML=EXtensibleMarkupLanguage236 PHP
File Open/Read/Close
PHP Open File –f open ()
A better method to open files is with the f open() function. This function
gives you more options than the read file () function.
We will use the text file, "web dictionary. txt", during the lessons:
Example
<?php
$myfile=fopen("webdictionary.txt","r")ordie("Unabletoopenfile!"); echo f read ($my
file, file size("webdictionary.txt"));
F close ($my file);
?>
The file may be opened in one of the following modes:
Modes Description
r Open a file for read only. File pointer starts at the beginning of the file.
w Open a file for write only.Erases the content soft he file or creates a new file if it doesn't
exist. File pointer starts at the beginning of the file.
a Open a file for write only. The existing data in file is preserved. File pointer starts at the
end of the file. Creates a new file if the file doesn't exist
x Creates a new file for write only. Returns FALSE and an error if file already exists.
r+ Open a file for read/write. File pointer starts at the beginning of the file
w+ Open a file for read/write. Erases the content soft he file or creates a new file if it doesn't
exist. File pointer starts at the beginning of the file.
a+ Open a file for read/write. The existing data in file is preserved. File pointer starts at the
end of the file. Creates a new file if the file doesn't exist.
x+ Creates a new file for read/write.Returns FALSE and an error if file already exists.
PHP Read File-f read ()
The f read () function reads from an open file.
The first parameter off read () contains the name of the file to read from and these cond parameter specifies
the maximum number of bytes to read.
The followingvPHP code reads the "web dictionary. txt "file to the end:
fread($myfile,filesize("webdictionary.txt"));
PHP Close File-fclose()
The f close () function is used to close an open file.
It's a good programming practice to close all files after you have finished with them. You don't
want an open file running around on your server taking up resources!
The f close() requires then a me of the file (or avariable that holds the file name) we want to close:
<?php
$myfile=f open ("web dictionary.txt","r");
//some code to be executed.... f close ($myfile);>
PHP Read SingleLinefgets()
The f gets() function is used to read a single line froma file.
The example below outputs the first line of the"web dictionary. txt"file:
Example
<?php
$myfile=fopen("web dictionary.txt","r")or die("Unable to open file!"); echo
fgets($myfile);
fclose($myfile);
?>
Note:
After a call to the fgets() function, the file pointer has moved to the next line.
PHP Check End-Of-File-feof()
The feof() function checks if the "end-of-file" (EOF) has been reached. The
feof() function is useful for looping through data of unknown length.
The example below reads the "web dictionary. txt "file line by line,until end-of-file is reached:
Example
<?php
$myfile=f open("web dictionary.txt","r")or die("Unable to open file!");
//Output one line until end-of-file

while(!feof($myfile)) {
echo fgets($myfile) . "<br>";
}
fclose($myfile);
?>
PHP Read Single Character-fgetc()
The fgetc() function is used to read a single character from a file.
The example below reads the"web dictionary.txt "file character by character,until end-of-file is
reached.
Example
<?php
$myfile=fopen("web dictionary.txt","r") or die("Unable to open file!");
//Output one character untilend-of-file
while(!feof($myfile)) {
echo fgetc ($myfile);
}
fclose ($myfile);
?>
Note:
After a call to the fgetc() function, the file pointer moves to the next character.
PHP File Create/Write PHPCreateFile-fopen()
The fopen() function is also used to create a file.May be a little confusing, but in PHP, a file is
created using the same function used to open files.If you use fopen() on a file that does not exist,it
will create it,given that the file is opened for writing (w) or appending (a).
The example below creates a new file called "testfile.txt". The file will be created in the same
directory where the PHP code resides:
Example:
$myfile=fopen("testfile.txt","w")
PHP File Permissions
If you are having errors when trying to get this code to run, check that you have granted your PHP file
access to write information to the hard drive.
PHPWritetoFile-fwrite()
The fwrite() function is used to write to a file.
The first parameter off write() contain the name of the file to write to and these cond parameter is
the string to be written.
The example below writes a couple of names into a new file called "new file.txt":
Example
<?php
$myfile=fopen("newfile.txt","w") or die("Unable to open file!");
$txt = "John Doe\n";
fwrite($myfile,$txt);
$txt = "Jane Doe\n";
fwrite($myfile,$txt);
fclose($myfile);
?>
Notice that we wrote to the file "newfile.txt" twice. Each time we wrote to the file we sent the
string $txt that first contained "JohnDoe" and second contained "JaneDoe". After we finished writing,
we closed the file using the fclose() function.
If we open the "new file.txt "file it would look like this:
JohnDoe
JaneDoe
PHP Over writing
Now that "new file. txt" contains some data we can show what happens when we open an existing file for
writing. All the existing data will be ERASED and we start with an empty file.
In the example below we open our existing file"newfile.txt", and write some new data in to it.
Example
<?php
$myfile=fopen("newfile.txt","w")ordie("Unabletoopen file!");
$txt="MickeyMouse\n"; fwrite($myfile, $txt);
$txt="MinnieMouse\n"; fwrite($myfile, $txt); fclose($myfile);
?>
If we now open the "newfile.txt" file, both John and Jane have vanished, and only the data we just
wrote is present:
ickeyMouse
MinnieMouse
PHP Append Text
You can append data to a file by using the "a" mode. The "a" mode appends text to the end of the file,
while the "w" mode overrides (and erases) the old content of the file.
In the example below we open our existing file"new file.txt", and append some text to it:
Example
<?php
$myfile=fopen("newfile.txt","a")ordie("Unabletoopen file!");
$txt="DonaldDuck\n";
fwrite($myfile, $txt);
$txt="GoofyGoof\n";
fwrite($myfile, $txt);
fclose($myfile);
?>
If we new open the "newfile.txt" file, we will see that Donald Duck and Go of y Go of is appended to
the end of the file:
MickeyMouse
Minnie Mouse
Donald Duck
Goofy Goof
Reading Data from a File
To read data from a file using PHP,you typically use functions like fopen(), fread(), fgets(), or
file_get_contents().
Definitions
fopen(): Opens a file or URL. Returns a file pointer resource that can be used with other file
functions.
fread(): Reads a file from the file pointer upto a specified number of bytes.
fgets(): Reads a single line from the file pointer.
file_get_contents():Reads the entire file in to a string.
Examples and Output
1. Using fopen()and fread()
Definition: fopen() opens a file and fread() reads up to a give n number of bytes from the file pointer.
ExampleCode:
<?php
$filename ="example.txt"; //Filetoread
//Openthe file forreading
$file=fopen($filename,"r");
//Checkifthefilewasopenedsuccessfully if($file) {
//Read thecontentofthefile
$content=fread($file,filesize($filename));
//Closethefile
fclose($file);
//Output the content
echo"Filecontent:\n". $content;
}else {
echo"Unabletoopenthe file.";
}
?>
Output(as suming example. txt contains "Hello,World!"):
arduino
File content:
Hello,World!
2. Using fopen() and fgets()
Definition:fgets() reads a line from the file pointer. Example
Code:
<?php
$filename ="example.txt"; //Filetoread
//Open the file for reading
$file=fopen($filename,"r");
//Check if the file was opened successfully if
($file) {
//Read each line of the file
while(($line=fgets($file))!==false){ echo
"Line: " . $line;
}
//Close thefile fclose($file);
}else {
echo"Unable to open the file.";
}
?>
Output(as suming example. txt contains "Hello,World!"ononeline): Line:
Hello, World!
3. Using file_get_contents()
Definition:file_get_contents()reads the entire file in to a string. Example
Code:
<?php
$file name ="example.txt"; //File to read
//Read the entire file in to a string
$content=file_get_contents($filename);
//Check if the file was read successfully if
($content !== false) {
echo"Filecontent:\n". $content;
}else {
echo"Unable to read the file.";
}
?>
Output(as suming example.txt contains"Hello,World!"):
arduinoCopy
code Filecontent:
Hello,World!
Notes
Ensure the file exists and is readable.Handlepotential errors gracefully.
file_get_contents()is usually the simple stand most convenient method for reading the entire file, while
fgets() is useful for processing files line-by-line.
fopen() combined with fread() provides fine-grained control over reading a specific number of bytes.
PHP MCQ
1.Which PHP function is used to filter and validate user inputs?
A) htmlspecialchars() B) filter_var() C) str_replace() D) trim()
Answer: B) filter_var()
2. What is the purpose of the PDO extension in PHP?
A) To enable object-oriented file handling.
B) To provide a consistent interface for working with databases.
C) To encrypt data. D) To handle JSON data.
Answer: B) To provide a consistent interface for working with databases.
3. Which function is used to start a session in PHP?
A) session_start() B) session_begin() C) start_session() D) session()
Answer: A) session_start()
4. In PHP, which of the following methods is used to define a constant?
A) define_constant() B) set_constant() C) const D) define()
Answer: D) define()
5. Which of the following is true about final keyword in PHP?
A) It allows a method to be overridden. B) It allows a class to be inherited.
C) It prevents a class from being inherited. D) It makes a method private.
Answer: C) It prevents a class from being inherited.
6. What will __destruct() do in a PHP class?
A) It initializes the properties of a class. B) It is called automatically when an object is destroyed.
C) It forces garbage collection. D) It creates an object of a class.
Answer: B) It is called automatically when an object is destroyed.
7. Which function can be used to serialize an array in PHP?
A) json_encode() B) serialize() C) implode() D) serialize_array()
Answer: B) serialize()
8. Which PHP function is used to include files only once?
A) include() B) require() C) include_once() D) require_all()
Answer: C) include_once()
9. What does $this keyword represent in a PHP class?
A) The parent class object. B) The current class.
C) The current object instance. D) A static method in a class.
Answer: C) The current object instance.
10. In PHP, which keyword is used to inherit a class?
A) inherits B) extends C) implements D) inherit
Answer: B) extends
11. Which PHP function is used to filter and validate user inputs?
A) htmlspecialchars() B) filter_var() C) str_replace() D) trim()
Answer: B) filter_var()
12. What is the purpose of the PDO extension in PHP?
A) To enable object-oriented file handling.
B) To provide a consistent interface for working with databases.
C) To encrypt data. D) To handle JSON data.
Answer: B) To provide a consistent interface for working with databases.
13. Which function is used to start a session in PHP?
A) session_start() B) session_begin() C) start_session() D) session()
Answer: A) session_start()
14. In PHP, which of the following methods is used to define a constant?
A) define_constant() B) set_constant() C) const. D) define()
Answer: D) define()
15. Which of the following is true about final keyword in PHP?
A) It allows a method to be overridden. B) It allows a class to be inherited.
C) It prevents a class from being inherited. D) It makes a method private.
Answer: C) It prevents a class from being inherited.
16. What will __destruct() do in a PHP class?
A) It initializes the properties of a class. B) It is called automatically when an object is destroyed.
C) It forces garbage collection. D) It creates an object of a class.
Answer: B) It is called automatically when an object is destroyed.
17. Which function can be used to serialize an array in PHP?
A) json_encode() B) serialize() C) implode() D) serialize_array()
Answer: B) serialize()
18. Which PHP function is used to include files only once?
A) include() B) require() C) include_once() D) require_all()
Answer: C) include_once()
19. What does $this keyword represent in a PHP class?
A) The parent class object. B) The current class.
C) The current object instance. D) A static method in a class.
Answer: C) The current object instance.
20. In PHP, which keyword is used to inherit a class?
A) inherits B) extends C) implements D) inherit
Answer: B) extends
21. Which function reads the entire content of a file into a string in PHP?
A) fgets() B) file get contents() C) fread() D) readfile()
Answer: B) file_get_contents()
22. Which PHP function is used to read a single line from a file?
A) fopen() B) file() C) fgets() D) readline()
Answer: C) fgets()
23. What does the file() function return when reading a file?
A) A string with the entire file content. B) An array, with each element as a line from the file.
C) A boolean indicating file existence. D) The file size.
Answer: B) An array, with each element as a line from the file.
4. Which mode is used with fopen() to open a file for reading only?
A) r B) w C) a D) r+
Answer: A) r
25. What is the purpose of the fread() function in PHP?
A) It reads a file line by line. B) It reads a specified number of bytes from a file.
C) It reads the first line of a file. D) It checks if a file exists.
Answer: B) It reads a specified number of bytes from a file.
26. Which PHP function reads the entire content of a file and outputs it directly to the browser?
A) fgets() B) fread() C) file_get_contents() D) readfile()
Answer: D) readfile()
27. How can you move the file pointer to the beginning of a file in PHP?
A) rewind() B) reset_pointer() C) move_to_start() D) file_reset()
Answer: A) rewind()
28. Which function can be used to read each line of a file in a loop until reaching the end of the file?
A) file_get_contents() B) readfile() C) fgets() D) file_exists()
Answer: C) fgets()
29. What does the feof() function check in PHP?
A) If the file exists. B) If the end of the file has been reached.
C) If the file pointer is at the beginning. D) If the file is open.
Answer: B) If the end of the file has been reached.
30. Which PHP function reads an entire file into an array, with each line as a separate element?
A) fread() B) file() C) fgets() D) file_get_contents()
Answer: B) file()
31. What will the fgetc() function return?
A) The entire content of the file. B) The next line in the file.
C) The next character in the file. D) The size of the file.
Answer: C) The next character in the file.
32. Which function is used to get the current position of the file pointer?
A) fseek() B) ftell() C) rewind() D) file_get_position()
Answer: B) ftell()
33. Which function sets the file pointer to a specific location in the file?
A) fseek() B) rewind() C) file_seek() D) set_pointer()
Answer: A) fseek()
34. When reading a file with fgets(), which parameter is required to specify the maximum number of bytes to
read?
A) size B) length C) bytes D) limit
Answer: B) length

35. What does file_exists() function do?


A) Opens a file for reading. B) Checks if a file exists on the server.
C) Reads the entire file into a string. D) Reads a file line by line.
Answer: B) Checks if a file exists on the server.
36. Which function reads an entire file and returns it as an array of lines, with each line ending in a newline
character?
A) fgets() B) file() C) file_get_contents() D) fread()
Answer: B) file()
37. In PHP, which function can be used to read a CSV file?
A) fopen() B) fgetcsv() C) file_get_contents() D) read_csv()
Answer: B) fgetcsv()
38. What is the difference between fread() and file_get_contents()?
A) fread() reads the entire file, while file_get_contents() reads only one line.
B) file_get_contents() reads the entire file at once, while fread() reads a specific number of bytes.
C) Both functions work the same way.
D) file_get_contents() is used for binary files, while fread() is not.
Answer: B) file_get_contents() reads the entire file at once, while fread() reads a specific number of bytes.
39. Which function reads the entire content of a file and allows specifying the number of bytes to read?
A) fread() B) file() C) file_get_contents() D) readfile()
Answer: A) fread()
40. When opening a file with fopen(), which mode is used to open it for reading and writing from the beginning
of the file?
A) w+ B) a+ C) r+ D) rw
Answer: C) r+
41.PHP scripts are executed on which side?
A) Client-side B) Server-side C) Both client-side and server-side D) Database-side
Answer: B) Server-side
42. What is the correct way to declare a PHP variable?
A) var $variable; B) $variable; C) declare $variable; D) variable $variable;
Answer: B) $variable;
43. Which of the following is the correct way to start a PHP block?
A) <php> B) <?php ?> C) <?> D) <?script>
Answer: B) <?php ?>
44. Which function is used to output content in PHP?
A) print() B) echo C) write() D) display()
Answer: B) echo
45. What does PHP stand for?
A) Personal Home Page. B) Private Home Page C) PHP: Hypertext Preprocessor
D) Public Hypertext Processor
Answer: C) PHP: Hypertext Preprocessor
46. Which of the following is NOT a data type in PHP?
A) Integer B) String C) Float D) Characte
Answer: D) Character
47. Which function is used to find the length of a string in PHP?
A) strlen() B) strlength() C) count() D) length()
Answer: A) strlen()
48. Which operator is used to concatenate two strings in PHP?
A) + B) * C) . (dot) D) &
Answer: C) . (dot)
49. What is the correct way to add a comment in PHP?
A) // Comment. B) /* Comment */ C) # Comment D) All of the above
Answer: D) All of the above
50. Which function is used to terminate the execution of a PHP script?
A) end() B) stop() C) exit() D) terminate()
Answer: C) exit()
5 & 10 mark:
1.Concepts of reading and writing files in PHP.
2. Code examples and explanations.
3. Theoretical questions on file handling techniques.
4. Write a php Advanced concepts?
5. Basic concept of PHP?

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy