open and read a file Flashcards

1
Q

Specify the File Path
How do you specify the file path in PHP?

A

// Specify the file path
$filename = “example.txt”; // Ensure this file exists

The variable $filename holds the name of the file you want to read.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Check if the File Exists
How do you check if a file exists in PHP?

A

// Check if the file exists
if (file_exists($filename)) {
** // Proceed to open the file**
} else {
echo “Error: The file does not exist.”;
}

Always check if the file exists using file_exists().

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Open the File
How do you open a file in read mode in PHP?

A

// Open the file in read mode
$file = fopen($filename, “r”); // “r” mode is for reading

// Check if the file was opened successfully
if ($file) {
** // Proceed to read the file**
} else {
echo “Error: Unable to open the file.”;
}

Use fopen() with “r” mode to read.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Read the File Line by Line
How do you read a file line by line in PHP?

A

// Read the file line by line
while (($line = fgets($file)) !== false) {
** // Output the line**
echo $line . “<br></br>”; // Adding <br></br> for line breaks in HTML
}

Use fgets() to read each line.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Close the File
How do you close a file in PHP after reading?

A

// Close the file after reading
fclose($file);

Always close the file with fclose()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Steps of Open and Read a file.

A
  1. Specify the File Path
  2. Check if the File Exists
  3. Open the File
  4. Read the File Line by Line
  5. Close the File
How well did you know this?
1
Not at all
2
3
4
5
Perfectly