WikiGalaxy

Personalize

PHP File Handling

Reading a File:

PHP provides several functions to read files. The simplest way is using the file_get_contents() function which reads the entire file into a string.


<?php
$content = file_get_contents("example.txt");
echo $content;
?>
    

Opening a File:

To open a file, use the fopen() function, which returns a file pointer resource on success.


<?php
$file = fopen("example.txt", "r");
if ($file) {
    echo "File opened successfully.";
}
?>
    

Reading a File Line by Line:

The fgets() function is used to read a file line by line.


<?php
$file = fopen("example.txt", "r");
while (($line = fgets($file)) !== false) {
    echo $line;
}
fclose($file);
?>
    

Writing to a File:

The fwrite() function is used to write data to a file.


<?php
$file = fopen("example.txt", "w");
fwrite($file, "Hello, World!");
fclose($file);
?>
    

Appending to a File:

To append data to a file, open it in append mode using "a".


<?php
$file = fopen("example.txt", "a");
fwrite($file, "Appended text.");
fclose($file);
?>
    

Checking if a File Exists:

Use the file_exists() function to check if a file exists.


<?php
if (file_exists("example.txt")) {
    echo "File exists.";
} else {
    echo "File does not exist.";
}
?>
    

Deleting a File:

The unlink() function is used to delete a file.


<?php
if (unlink("example.txt")) {
    echo "File deleted.";
} else {
    echo "File could not be deleted.";
}
?>
    

Getting File Size:

Use the filesize() function to get the size of a file in bytes.


<?php
$size = filesize("example.txt");
echo "File size: " . $size . " bytes";
?>
    

Getting File Type:

The filetype() function returns the type of the file.


<?php
$type = filetype("example.txt");
echo "File type: " . $type;
?>
    

Copying a File:

To copy a file, use the copy() function.


<?php
if (copy("example.txt", "example_copy.txt")) {
    echo "File copied.";
} else {
    echo "File could not be copied.";
}
?>
    
logo of wikigalaxy

Newsletter

Subscribe to our newsletter for weekly updates and promotions.

Privacy Policy

 • 

Terms of Service

Copyright © WikiGalaxy 2025