unit 4 php
unit 4 php
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