Skip to content

Streams and Network Programming

IT Notes → PHP @ December 22, 2020

File and file opening modes:

  • r,w,a where r represents read, w represents write, a represents append.
  • + will make it both read and write.
  • In append mode file pointer points to the end which is otherwise at beginning.
  • w additionally truncates file size to 0.
  • x creates a new file.
  • fgetcsv() and fputcsv() vastly simplify the task of accessing CSV files.
  • file_get_contents() and file_put_contents() simply file writing.
  • if (!file_exist ("filename.txt"))
    {
    throw new Exception ("The file does not exist.");
    }
    
    $file = fopen("filename.txt", "r");
    while (!feof($file))
    {
    $txt .= fread($file, 1);            //Last parameter number of bytes. fgets() stops at newline character.
    fwrite($file, $txt);
    }
    
    fseek($file,10,SEEK_CUR);                  
    //This will move file pointer by itself. The second parameter is the number of bytes to be moved (negative or positive) and third is the location from where to move - SEEK_SET (start), SEEK_CUR (current) and SEEK_END (end).
    
    fclose($file);

     

Directory:

  • chdir(“path”) – Changes directory path.
  • getcwd() – Gets current working directory.
  • mkdir (“path”, 0666, true); – The second parameter gives access mode and last if set to true any missing directories in path will be created. Normally last directory is created.
  • is_dir() – Checks if the path is a directory.
  • is_executable() – Checks if the path is executable.
  • is_file() – Checks if the path exists and is a regular file.
  • is_link() – Checks if the path exists and is a symlink.
  • is_readable() – Checks if the path exists and is readable.
  • is_writable() – Checks if the path exists and is writable.
  • is_uploaded_file() – Checks if the path is an uploaded file (sent via HTTP POST).
  • File permissions on UNIX systems can be changed by using chmod(), chgrp() and chown() where path and access mode provided.

 

Network:

  • Simple Network Access can be done by using some of the file functions.
  • You can create socket servers and clients using the stream functions stream_socket_server() and stream_socket_client().
  • Stream filters allow you to pass data in and out of a stream through a series of filters that can alter it dynamically like say filter for compression.
0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x