Streams and Network Programming
File and File Opening Modes
When working with files in PHP, it is important to understand the different file opening modes:
- r, w, a: ‘r’ represents read, ‘w’ represents write, and ‘a’ represents append.
- +: Adding + to the mode makes it both readable and writable.
- Append Mode: In append mode, the file pointer points to the end of the file, unlike other modes where it starts at the beginning.
- Truncating: ‘w’ mode additionally truncates the file size to 0 when opening the file.
- Create New File: ‘x’ mode creates a new file; it fails if the file already exists.
- fgetcsv() and fputcsv(): These functions simplify the task of reading from and writing to CSV files.
- file_get_contents() and file_put_contents(): These functions provide a simpler interface for reading from and writing to files.
if (!file_exists("filename.txt")) {
throw new Exception("The file does not exist.");
}
$file = fopen("filename.txt", "r");
while (!feof($file)) {
$txt .= fread($file, 1); // Last parameter specifies the number of bytes to read.
fwrite($file, $txt);
}
fseek($file, 10, SEEK_CUR); // Move file pointer by 10 bytes from the current position.
fclose($file);
Directory Operations
Working with directories in PHP involves various functions for directory manipulation:
chdir("path"):Changes the current working directory to the specified path.getcwd():Returns the current working directory path.mkdir("path", 0666, true):Creates a new directory. The second parameter specifies the access mode, and setting the third parameter to true creates any missing directories in the path.is_dir():Checks if a path is a directory.is_executable():Checks if a path is executable.is_file():Checks if a path exists and is a regular file.is_link():Checks if a path exists and is a symbolic link.is_readable():Checks if a path exists and is readable.is_writable():Checks if a path exists and is writable.is_uploaded_file():Checks if a path is an uploaded file (sent via HTTP POST).- File Permissions: On UNIX systems, file permissions can be managed using functions like chmod(), chgrp(), and chown() by providing the path and the desired access mode.
Network Programming
PHP provides capabilities for network programming, including:
- Simple Network Access: Basic network operations can be performed using PHP’s file functions.
- Socket Servers and Clients: PHP allows you to create socket servers and clients using functions like stream_socket_server() and stream_socket_client().
- Stream Filters: Stream filters enable data manipulation by passing data through a series of filters that can dynamically alter it, such as compression filters.
Additional Resources
For more in-depth information on PHP file handling and network programming, refer to the official PHP documentation and tutorials.
