File I/O
## Learning Objectives
- Read and write files
- Work with file paths
- Handle file operations safely
- Use directory functions
## Reading Files
### file_get_contents()
```php
```
### file() - Read into Array
```php
```
### fopen(), fread(), fclose()
```php
```
### Reading Modes
| Mode | Description |
|------|-------------|
| r | Read only, start at beginning |
| r+ | Read and write, start at beginning |
| w | Write only, truncate/creates |
| w+ | Read and write, truncate/creates |
| a | Write only, append to end |
| a+ | Read and write, append to end |
| x | Create and write only (fails if exists) |
| x+ | Create and read/write (fails if exists) |
### fgets() - Read Line
```php
```
### fgetc() - Read Character
```php
```
### feof() - Check End of File
```php
```
## Writing Files
### file_put_contents()
```php
```
### fwrite() with fopen()
```php
```
### flock() - File Locking
```php
```
## CSV Files
### Reading CSV
```php
```
### Writing CSV
```php
```
### Reading CSV with Headers
```php
```
## File Information
### file_exists()
```php
```
### is_file() vs is_dir()
```php
```
### File Stats
```php
```
### pathinfo()
```php
/var/www/html/images
// [basename] => photo.jpg
// [extension] => jpg
// [filename] => photo
// Individual parts
pathinfo($path, PATHINFO_DIRNAME); // /var/www/html/images
pathinfo($path, PATHINFO_BASENAME); // photo.jpg
pathinfo($path, PATHINFO_EXTENSION); // jpg
pathinfo($path, PATHINFO_FILENAME); // photo
?>
```
### realpath()
```php
```
## Directory Operations
### Creating Directories
```php
```
### Reading Directories
```php
```
### Directory Functions
```php
```
### Directory Iterator (Modern Approach)
```php
isFile()) {
echo $file->getFilename() . "\n";
}
}
// Recursive directory iterator
$iterator = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator("src")
);
foreach ($iterator as $file) {
if ($file->isFile()) {
echo $file->getPathname() . "\n";
}
}
?>
```
## File Copy, Move, Delete
### Copy
```php
```
### Rename/Move
```php
```
### Delete
```php
```
## Temporary Files
### tempnam()
```php
```
### tmpfile()
```php
```
## Serialization
### serialize()
```php
"Alice",
"age" => 25,
"skills" => ["PHP", "MySQL"]
];
$serialized = serialize($data);
// a:3:{s:4:"name";s:5:"Alice";s:3:"age";i:25;s:6:"skills";a:2:{i:0;s:3:"PHP";i:1;s:5:"MySQL";}}
file_put_contents("data.txt", $serialized);
?>
```
### unserialize()
```php
Alice [age] => 25 [skills] => Array ( [0] => PHP [1] => MySQL ) )
// Warning: Never unserialize untrusted data!
?>
```
### JSON as Alternative
```php
"Alice", "age" => 25];
$json = json_encode($data);
file_put_contents("data.json", $json);
$loaded = json_decode(file_get_contents("data.json"), true);
?>
```
## Error Handling
### File Errors
```php
```
### Custom Error Handler
```php
```
## Summary
- `file_get_contents()` reads entire file; `file()` reads into array
- `fopen()`, `fgets()`, `fread()`, `fwrite()`, `fclose()` for detailed control
- `file_put_contents()` writes to file; `fwrite()` with `fopen()`
- Modes: `r`, `r+`, `w`, `w+`, `a`, `a+`, `x`, `x+`
- Use `flock()` for file locking
- `fgetcsv()` and `fputcsv()` for CSV files
- `file_exists()`, `is_file()`, `filesize()`, `filemtime()` for file info
- `mkdir()`, `rmdir()`, `scandir()`, `glob()` for directories
- `copy()`, `rename()`, `unlink()` for file operations
- `tempnam()` and `tmpfile()` for temporary files
- `serialize()`/`unserialize()` for PHP-specific data storage
- `json_encode()`/`json_decode()` for cross-language data
Comments
Comments powered by Giscus
To enable comments, add your Giscus embed code here.
Learn more about Giscus →