The following post provides 10+ File Handling Problems in PHP. Also, their solutions are available on respective links.
- To begin with, write a PHP script to read the contents of a file and display them on the screen.
<?php
$filename = "file.txt";
$file = fopen($filename, "r");
echo fread($file, filesize($filename));
fclose($file);
?>
- After that, write a PHP script to write a string to a file.
<?php
$filename = "file.txt";
$file = fopen($filename, "w");
fwrite($file, "Hello World!");
fclose($file);
?>
- Then, write a PHP script to append a string to a file.
<?php
$filename = "file.txt";
$file = fopen($filename, "a");
fwrite($file, "Hello World Again!");
fclose($file);
?>
- Next, write a PHP script to check if a file exists.
<?php
$filename = "file.txt";
if(file_exists($filename)){
echo "File exists!";
} else {
echo "File does not exist!";
}
?>
- Also, write a PHP script to check if a file is readable.
<?php
$filename = "file.txt";
if(is_readable($filename)){
echo "File is readable!";
} else {
echo "File is not readable!";
}
?>
- Similarly, write a PHP script to check if a file is writable.
<?php
$filename = "file.txt";
if(is_writable($filename)){
echo "File is writable!";
} else {
echo "File is not writable!";
}
?>
- Also, write a PHP script to delete a file.
<?php
$filename = "file.txt";
if(file_exists($filename)){
unlink($filename);
echo "File deleted!";
} else {
echo "File does not exist!";
}
?>
- Write a PHP script to copy a file.
<?php
$filename = "file.txt";
$newfilename = "file_copy.txt";
if(file_exists($filename)){
copy($filename, $newfilename);
echo "File copied!";
} else {
echo "File does not exist!";
}
?>
- Further, write a PHP script to rename a file.
<?php
$filename = "file.txt";
$newfilename = "new_file.txt";
if(file_exists($filename)){
rename($filename, $newfilename);
echo "File renamed!";
} else {
echo "File does not exist!";
}
?>
- Likewise, write a PHP script to get the file size.
<?php
$filename = "file.txt";
if(file_exists($filename)){
echo "File size: " . filesize($filename) . " bytes.";
} else {
echo "File does not exist!";
}
?>
- Write a PHP script to get the file extension.
<?php
$filename = "file.txt";
if(file_exists($filename)){
echo "File extension: " . pathinfo($filename, PATHINFO_EXTENSION);
} else {
echo "File does not exist!";
}
?>
- Also, write a PHP script to get the file name.
<?php
$filename = "file.txt";
if(file_exists($filename)){
echo "File name: " . basename($filename);
} else {
echo "File does not exist!";
}
?>
- Lastly, write a PHP script to get the file path.
<?php
$filename = "file.txt";
if(file_exists($filename)){
echo "File path: " . realpath($filename);
} else {
echo "File does not exist!";
}
?>
Further Reading
Examples of Array Functions in PHP
Pattern Display Problems in PHP
How to Create a Login Application in PHP?
How to Implement the Change Password Function in PHP?