logo CBCE Skill INDIA

Welcome to CBCE Skill INDIA. An ISO 9001:2015 Certified Autonomous Body | Best Quality Computer and Skills Training Provider Organization. Established Under Indian Trust Act 1882, Govt. of India. Identity No. - IV-190200628, and registered under NITI Aayog Govt. of India. Identity No. - WB/2023/0344555. Also registered under Ministry of Micro, Small & Medium Enterprises - MSME (Govt. of India). Registration Number - UDYAM-WB-06-0031863

File Handling in PHP!


File Handling in PHP

File handling in PHP allows you to read from and write to files on the server or manipulate file-related operations. Here are some common file handling operations in PHP:

 

 

Reading from a File:

 

1. Using file_get_contents:

<?php
// Read the entire contents of a file into a string
$content = file_get_contents("example.txt");
echo $content;
?>

 

2. Using fopen, fread, and fclose:

<?php
// Open the file in read mode
$handle = fopen("example.txt", "r");

// Read the file line by line
while (!feof($handle)) {
    $line = fgets($handle);
    echo $line;
}

// Close the file handle
fclose($handle);
?>

 

 

Writing to a File:

 

1. Using file_put_contents:

<?php
// Write a string to a file
$data = "Hello, World!";
file_put_contents("example.txt", $data);
?>

 

2. Using fopen, fwrite, and fclose:

<?php
// Open the file in write mode
$handle = fopen("example.txt", "w");

// Write data to the file
fwrite($handle, "Hello, World!");

// Close the file handle
fclose($handle);
?>

 

 

Appending to a File:

 

1. Using file_put_contents with FILE_APPEND flag:

<?php
// Append a string to a file
$data = "New content to append";
file_put_contents("example.txt", $data, FILE_APPEND);
?>

2. Using fopen, fwrite, and fclose with "a" mode:

<?php
// Open the file in append mode
$handle = fopen("example.txt", "a");

// Write data to the end of the file
fwrite($handle, "New content to append");

// Close the file handle
fclose($handle);
?>

 

 

Checking File Existence:

 

<?php
$filename = "example.txt";

// Check if a file exists
if (file_exists($filename)) {
    echo "The file $filename exists.";
} else {
    echo "The file $filename does not exist.";
}
?>

 

 

Deleting a File:

 

<?php
$filename = "example.txt";

// Check if the file exists before attempting to delete
if (file_exists($filename)) {
    // Delete the file
    unlink($filename);
    echo "The file $filename has been deleted.";
} else {
    echo "The file $filename does not exist.";
}
?>

 

These are basic examples, and it's important to handle file operations carefully, especially when dealing with user input or dynamic file names. Additionally, consider file permissions and security measures to protect against unauthorized access or manipulation of files.

 

Thank you.

Popular Post:

Give us your feedback!

Your email address will not be published. Required fields are marked *
0 Comments Write Comment