PHP Basics · Chapter 13 · File Handling

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 के साथ।

📂 fopen/fclose 📖 fread/fwrite ⚡ file_get/put_contents 📁 Directories ⬆️ File Upload
fopenFile खोलना
r w aFile modes
2MBDefault upload limit
SPLSplFileObject — OOP

📋 इस Article में क्या-क्या है

  1. File Handling Overview
  2. file_get/put_contents — Easy Way
  3. fopen / fclose — Low Level
  4. File Modes
  5. fread / fwrite / fgets
  6. File Info Functions
  7. Directory Functions
  8. CSV File Handling
  9. File Upload
  10. Real World Examples
1
File Handling Overview

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

// एक line में read
$content = file_get_contents("data.txt");

// एक line में write
file_put_contents("data.txt", "Hello");

ℹ️ Low Level — fopen/fclose

// Large files, streaming
$fh = fopen("data.txt", "r");
$line = fgets($fh);
fclose($fh);
Small files → file_get/put_contents। Large files / streaming → fopen/fread/fwrite।

2
file_get_contents & file_put_contents — Easy Way
fgc
fpc

file_get_contents() / file_put_contents()

सबसे simple file functions। file_get_contents() — पूरी file एक string में। file_put_contents() — string को file में write। URLs से भी read कर सकते हो।

PHP 4.3+ One-liner URL support
file_get_contents() & file_put_contents()
<?php
// 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";
}
?>

3
fopen() और fclose() — Low Level Control
fopn
fclse

fopen() / fclose()

File को open करके file handle (resource) return करता है। Large files line-by-line read, streaming, precise seek control के लिए। हमेशा fclose() करो।

PHP 4+ Returns: resource fclose() ज़रूरी!
resource|false fopen( string $filename, string $mode )
fopen() — BASIC PATTERN
<?php
// 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 होने पर भी!
}
?>

4
File Modes — r, w, a, x, c
ModeमतलबFile exist नहीं?Pointer
"r"Read onlyErrorStart
"r+"Read + WriteErrorStart
"w"Write only (truncate)Create करेStart
"w+"Read + Write (truncate)Create करेStart
"a"Append onlyCreate करेEnd
"a+"Read + AppendCreate करेEnd
"x"Create only (fail if exists)Create करेStart
"x+"Read + Create onlyCreate करेStart
"c"Write (no truncate)Create करेStart
"b"Binary mode (suffix)
💡 Most Used: "r" — read, "w" — write/create, "a" — append, "rb"/"wb" — binary files (images, PDFs)। Windows पर binary files के लिए "b" ज़रूरी है।

5
fread · fwrite · fgets · fputs
READING FUNCTIONS
<?php
// 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);
?>
WRITING FUNCTIONS
<?php
// 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);
?>

6
File Info Functions — Check & Stats
FILE INFO — COMMON FUNCTIONS
<?php
$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 bytesint
filemtime()Last modified timestampint
pathinfo()Path componentsarray
basename()Filename from pathstring
dirname()Directory from pathstring
realpath()Absolute pathstring|false
copy()File copy करनाbool
rename()Rename/move करनाbool
unlink()File delete करनाbool
touch()File create/timestamp updatebool

7
Directory Functions — Folders के साथ काम
DIRECTORY — CREATE, LIST, DELETE
<?php
// 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);
}
?>

8
CSV File Handling — Data Import/Export
CSV
data

fgetcsv() / fputcsv()

PHP में CSV files को directly parse और write करने के functions। Excel data import, reports export — सबसे common file operation।

PHP 4+ Auto parse Excel compatible
CSV READ — fgetcsv()
<?php
// 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)
?>
CSV WRITE — fputcsv() & Browser Download
<?php
// 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");
?>
💡 php://output: Browser को directly output stream में write करने के लिए। File save किए बिना user को download करवाना।

9
File Upload — $_FILES Handle करना
⬆️
upload

File Upload Processing

HTML form से upload हुई file $_FILES superglobal में आती है। Validate करो — type, size, errors। फिर safe location पर move करो।

Always validate! $_FILES superglobal move_uploaded_file()
HTML FORM — Enctype ज़रूरी
<form method="POST" enctype="multipart/form-data">
  <input type="file" name="photo">
  <button type="submit">Upload</button>
</form>
PHP — $_FILES STRUCTURE & PROCESSING
<?php
// $_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"];
  }
}
?>
⚠️ Security Rules — File Upload:
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 नहीं।

10
Real World — Log System & Config Cache
REAL WORLD — Logger Class
<?php
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
?>
Pattern: file_exists → fopen (try-finally) → fread/fwrite → fclose। Upload: validate → unique name → move_uploaded_file।

निष्कर्ष

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।

🚀 अगला Chapter: Chapter 14: PHP MySQL & PDO — Database connect करना, CRUD operations, Prepared Statements, Transactions। PHP का सबसे important topic।