PHP File Handling
Complete Guide in Hindi
PHP File Handling की पूरी जानकारी — fopen/fclose, fread/fwrite, file_get_contents, file_put_contents, directory functions, CSV handling, और file upload। Real examples के साथ।
📋 इस Article में क्या-क्या है
- File Handling Overview
- file_get/put_contents — Easy Way
- fopen / fclose — Low Level
- File Modes
- fread / fwrite / fgets
- File Info Functions
- Directory Functions
- CSV File Handling
- File Upload
- Real World Examples
PHP में files को read, write, create, delete, और rename कर सकते हो। Logs save करना, CSV generate करना, config files read करना, user uploads handle करना — सब file handling है।
✅ Easy Way — file_get/put_contents
$content = file_get_contents("data.txt");
// एक line में write
file_put_contents("data.txt", "Hello");
ℹ️ Low Level — fopen/fclose
$fh = fopen("data.txt", "r");
$line = fgets($fh);
fclose($fh);
// READ — पूरी file एक string में
$content = file_get_contents("notes.txt");
echo $content;
// File exist check — always!
if (file_exists("notes.txt")) {
$content = file_get_contents("notes.txt");
}
// URL से read (allow_url_fopen = On)
$json = file_get_contents("https://api.example.com/data");
$data = json_decode($json, true);
// WRITE — file create/overwrite
file_put_contents("output.txt", "Hello World\n");
// APPEND — file_put_contents + FILE_APPEND flag
file_put_contents("log.txt", "New log entry\n", FILE_APPEND);
// LOCK — concurrent writes से बचाओ
file_put_contents("data.txt", "data", LOCK_EX);
// दोनों flags एक साथ
file_put_contents("log.txt", $logEntry, FILE_APPEND | LOCK_EX);
// file() — array of lines
$lines = file("data.txt", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
foreach ($lines as $line) {
echo $line . "\n";
}
?>
// Open → Use → Close (always!)
$fh = fopen("data.txt", "r");
if ($fh === false) {
die("File open नहीं हो सकी");
}
// ... file operations ...
fclose($fh); // हमेशा close करो!
// try-finally — exception होने पर भी close होगा
$fh = fopen("data.txt", "r");
try {
// file operations
$content = fread($fh, filesize("data.txt"));
} finally {
fclose($fh); // Exception होने पर भी!
}
?>
| Mode | मतलब | File exist नहीं? | Pointer |
|---|---|---|---|
| "r" | Read only | Error | Start |
| "r+" | Read + Write | Error | Start |
| "w" | Write only (truncate) | Create करे | Start |
| "w+" | Read + Write (truncate) | Create करे | Start |
| "a" | Append only | Create करे | End |
| "a+" | Read + Append | Create करे | End |
| "x" | Create only (fail if exists) | Create करे | Start |
| "x+" | Read + Create only | Create करे | Start |
| "c" | Write (no truncate) | Create करे | Start |
| "b" | Binary mode (suffix) | — | — |
// fread() — N bytes read करो
$fh = fopen("data.txt", "r");
$content = fread($fh, filesize("data.txt")); // whole file
fclose($fh);
// fgets() — एक line read करो
$fh = fopen("data.txt", "r");
while (!feof($fh)) {
$line = fgets($fh); // one line at a time
if ($line !== false) {
echo trim($line) . "\n";
}
}
fclose($fh);
// fgetc() — एक character
$fh = fopen("data.txt", "r");
while (($char = fgetc($fh)) !== false) {
echo $char;
}
fclose($fh);
?>
// fwrite() / fputs() — write करो
$fh = fopen("output.txt", "w");
fwrite($fh, "Line 1\n");
fwrite($fh, "Line 2\n");
fwrite($fh, "Line 3\n");
fclose($fh);
// Append mode — existing content रखो
$fh = fopen("log.txt", "a");
fwrite($fh, date("Y-m-d H:i:s") . " — User logged in\n");
fclose($fh);
// fseek() — cursor move करो
$fh = fopen("data.txt", "r");
fseek($fh, 100); // 100 bytes skip करो
$data = fread($fh, 50); // 50 bytes read
echo ftell($fh); // current position: 150
rewind($fh); // beginning पर वापस
fclose($fh);
?>
$file = "document.pdf";
// Existence checks
file_exists($file); // exists? (file या dir)
is_file($file); // regular file है?
is_dir($file); // directory है?
is_readable($file); // read किया जा सकता है?
is_writable($file); // write किया जा सकता है?
// File info
echo filesize($file); // bytes में size
echo filemtime($file); // last modified timestamp
echo date("Y-m-d", filemtime($file)); // readable date
echo filetype($file); // file, dir, link...
// Path info
$info = pathinfo("/var/www/uploads/photo.jpg");
echo $info["dirname"]; // /var/www/uploads
echo $info["basename"]; // photo.jpg
echo $info["filename"]; // photo
echo $info["extension"]; // jpg
// File operations
copy("src.txt", "dst.txt"); // copy
rename("old.txt", "new.txt"); // rename/move
unlink("delete.txt"); // delete
?>
| Function | काम | Returns |
|---|---|---|
| file_exists() | File/dir exist करता है? | bool |
| is_file() | Regular file है? | bool |
| is_dir() | Directory है? | bool |
| is_readable() | Read permission है? | bool |
| is_writable() | Write permission है? | bool |
| filesize() | Size in bytes | int |
| filemtime() | Last modified timestamp | int |
| pathinfo() | Path components | array |
| basename() | Filename from path | string |
| dirname() | Directory from path | string |
| realpath() | Absolute path | string|false |
| copy() | File copy करना | bool |
| rename() | Rename/move करना | bool |
| unlink() | File delete करना | bool |
| touch() | File create/timestamp update | bool |
// Directory बनाना
mkdir("uploads"); // single dir
mkdir("uploads/2025/05", 0755, true); // nested + permissions
// Directory list — scandir()
$items = scandir("uploads");
foreach ($items as $item) {
if ($item !== "." && $item !== "..") {
echo $item . "\n";
}
}
// glob() — pattern matching
$phpFiles = glob("*.php"); // all .php files
$imgFiles = glob("uploads/*.{jpg,png,gif}", GLOB_BRACE);
// opendir / readdir — traditional way
$dh = opendir("uploads");
while (($file = readdir($dh)) !== false) {
if (is_file("uploads/" . $file)) {
echo $file . "\n";
}
}
closedir($dh);
// Directory delete
rmdir("empty_dir"); // सिर्फ empty directory
// Recursive delete function
function deleteDir(string $dir): void {
foreach (scandir($dir) as $item) {
if ($item === "." || $item === "..") continue;
$path = $dir . "/" . $item;
is_dir($path) ? deleteDir($path) : unlink($path);
}
rmdir($dir);
}
?>
// students.csv:
// Name,Marks,Grade
// Rahul,95,A+
// Priya,88,A
$fh = fopen("students.csv", "r");
$headers = fgetcsv($fh); // First row = headers
$students = [];
while (($row = fgetcsv($fh)) !== false) {
$students[] = array_combine($headers, $row);
}
fclose($fh);
foreach ($students as $s) {
echo "{$s['Name']}: {$s['Marks']} ({$s['Grade']})\n";
}
// Rahul: 95 (A+)
// Priya: 88 (A)
?>
// File में write
$fh = fopen("report.csv", "w");
fputcsv($fh, ["Name", "Email", "Score"]); // headers
$data = [
["Rahul", "r@g.com", 95],
["Priya", "p@g.com", 88],
];
foreach ($data as $row) {
fputcsv($fh, $row);
}
fclose($fh);
// Browser से download करवाना
function downloadCSV(array $rows, string $filename = "export.csv"): void {
header("Content-Type: text/csv");
header("Content-Disposition: attachment; filename=\"$filename\"");
$out = fopen("php://output", "w");
foreach ($rows as $row) {
fputcsv($out, $row);
}
fclose($out);
}
downloadCSV([
["Name", "Score"],
["Rahul", 95],
], "students.csv");
?>
<input type="file" name="photo">
<button type="submit">Upload</button>
</form>
// $_FILES["photo"] structure:
// [name] => "photo.jpg" (original filename)
// [type] => "image/jpeg" (MIME type — user-provided, unsafe!)
// [tmp_name] => "/tmp/phpXXXX" (server temp location)
// [error] => 0 (0 = no error)
// [size] => 102400 (bytes)
function handleUpload(array $file, string $uploadDir = "uploads/"): array {
// Step 1: Error check
if ($file["error"] !== UPLOAD_ERR_OK) {
return ["success" => false, "error" => "Upload error: " . $file["error"]];
}
// Step 2: Size check (5MB max)
$maxSize = 5 * 1024 * 1024;
if ($file["size"] > $maxSize) {
return ["success" => false, "error" => "File 5MB से बड़ी है"];
}
// Step 3: Extension check (MIME type नहीं — unsafe!)
$allowed = ["jpg", "jpeg", "png", "gif", "webp"];
$ext = strtolower(pathinfo($file["name"], PATHINFO_EXTENSION));
if (!in_array($ext, $allowed)) {
return ["success" => false, "error" => "Invalid file type"];
}
// Step 4: MIME type verify (finfo — server side)
$finfo = new finfo(FILEINFO_MIME_TYPE);
$mimeType = $finfo->file($file["tmp_name"]);
$allowedMime = ["image/jpeg", "image/png", "image/gif", "image/webp"];
if (!in_array($mimeType, $allowedMime)) {
return ["success" => false, "error" => "Invalid MIME type"];
}
// Step 5: Unique filename बनाओ
$newName = uniqid("img_", true) . "." . $ext;
$dest = $uploadDir . $newName;
// Step 6: Directory बनाओ अगर नहीं है
if (!is_dir($uploadDir)) {
mkdir($uploadDir, 0755, true);
}
// Step 7: move_uploaded_file() — safe move
if (!move_uploaded_file($file["tmp_name"], $dest)) {
return ["success" => false, "error" => "Move failed"];
}
return ["success" => true, "filename" => $newName];
}
// Usage
if ($_SERVER["REQUEST_METHOD"] === "POST") {
$result = handleUpload($_FILES["photo"]);
if ($result["success"]) {
echo "✅ Uploaded: " . $result["filename"];
} else {
echo "❌ Error: " . $result["error"];
}
}
?>
1. $_FILES["type"] trust मत करो — user-controlled है। finfo से server-side MIME check करो।
2. Extension whitelist — blacklist नहीं। "php", "phtml" explicitly block करो।
3. Unique filename — original name use मत करो — path traversal attack।
4. Upload folder outside webroot या .htaccess से PHP execution block करो।
5. move_uploaded_file() use करो — copy/rename नहीं।
class Logger {
private string $logDir;
public function __construct(string $dir = "logs/") {
$this->logDir = $dir;
if (!is_dir($dir)) mkdir($dir, 0755, true);
}
public function log(string $level, string $message): void {
$file = $this->logDir . date("Y-m-d") . ".log";
$entry = sprintf("[%s] [%s] %s\n", date("H:i:s"), strtoupper($level), $message);
file_put_contents($file, $entry, FILE_APPEND | LOCK_EX);
}
public function getLogs(string $date = ""): array {
$file = $this->logDir . ($date ?: date("Y-m-d")) . ".log";
if (!file_exists($file)) return [];
return file($file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
}
}
$logger = new Logger();
$logger->log("info", "User Rahul logged in");
$logger->log("error", "DB connection failed");
$logs = $logger->getLogs(); // Today's logs
?>
PHP File Handling powerful है। Logs, configs, CSV exports, uploads — सब इन्हीं functions से होता है। Security पर ध्यान दो — especially uploads में।
file_get/put_contents — Small files के लिए prefer करो। Simple और fast।
fopen + try-finally — Large files। fclose() ज़रूर करो।
FILE_APPEND | LOCK_EX — Log files के लिए। Concurrent safe।
fgetcsv / fputcsv — CSV के लिए। php://output से browser download।
Upload Security — finfo MIME check, whitelist, unique name, move_uploaded_file।
glob() — Pattern से files ढूँढना। scandir() से directory list।