7. Files, Resources and Processes - PHP & MySQL Web Development


Published on

Basic concepts about working with files, resources and processes in PHP
Telerik Software Academy: http://academy.telerik.com/school-academy/meetings/details/2011/10/11/php-school-academy-meeting
The website and all video materials are in Bulgarian.

This lecture discusses the following topics:

Working with files: Opening, reading, writing
Directories and file system
Access external process

Published in: Education, Technology
1 Like
  • Be the first to comment

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

7. Files, Resources and Processes - PHP & MySQL Web Development

  1. 1. Files, Resources and Processes Files, Directories, PermissionsNikolay KostovTechnical Trainerhttp://nikolay.itTelerik Software Academyacademy.telerik.com
  2. 2. Contents Working with files  Opening, reading, writing Directories and file system Permissions Access external process
  3. 3. Opening fileReading and writing
  4. 4. Opening file fopen ($name, $mode, $use_include_path, $context) – open a file and return associated resource  $name specifies the file to open  $mode sets the mode of file opening:  "w" – open for writing, clear all content  "r" – open for reading  "a" – open for writing, keep content, append  "x" – open new file for writing, if file exists – fail
  5. 5. Opening file All four modes can be used with"+" – open for both reading and writing ("r+", "w+", "a+", "x+") All four modes can be used with "b" flag – safe binary access (i.e.: "rb", "wb")  used only on Windows-like systems that make difference between byte and text files $use_include_path – optional, if true the file will be searched in the PPH include path $context – optional, additional settings for handling streams fopen returns file pointer resource or false on error // example – open file test.txt for reading $fp = fopen ("test.txt", "r");
  6. 6. Reading from file fread ($resource, $length) – read from file pointer resource $resource up to number of character $length  Reading stops when $length chars have been read or file ends or 8192 bytes are read  Returns string or false in case of error  Moves the internal file pointer // example – open file test.txt for reading // read 10 chars from it $fp = fopen ("test.txt", "r"); if ($fp !== false) echo fread ($fp, 10);
  7. 7. Determining file end feof ($file_pointer) – returns true if the internal file pointer has reached the file end filesize ($filename) – returns the size of the file in bytes  Returns false on error  Results of this functions are cached! // print file content: $fp = fopen ("test.txt", "r"); while (!feof($fp)) echo fread ($fp, 32);
  8. 8. Writing to a file fwrite($resource, $string, $length)  $resource is file pointer resource  $string is the data to be written  $length is optional parameter – maximum bytes to be written  Returns false on error or number of bytes written on success$fp = fopen ("test.txt", "w");fwrite ($fp, "Hello world!");
  9. 9. Closing file fclose ($resource) – closes file, stream or socket connection  $resource is file pointer  Returns true on success, false on error  Changes, made to a file may not be saved unless file is closed  Clears locks to the file$fp = fopen ("test.txt", "w");fwrite ($fp, "Hello world!");fclose ($fp);
  10. 10. Reading entire file at once stream_get_contents($handle) file_get_contents ($filename, $use_include_path, $context, $offset, $max_length) – returns string, containing the data from a file  $use_include_path, $context are similar to fopen parameters  $offset and $max_length specify the start and maximum length of the data read  Returns string or false on error echo file_get_contents("test.txt");
  11. 11. Accessing URL Resources We can download files from URL location with the same file I/O functions: <?php $fp = fopen ("http://abv.bg/", "r"); $content = ; while (!feof($fp)) { $content .= fread ($fp, 512); } fclose ($fp); echo $content; ?>
  12. 12. Writing all data at once file_put_contents ($filename, $data, $flags, $context) – open file, write the data and close it  $filename is the file name to open  $data is the string to write  $flags is boolean combination of:  FILE_USE_INCLUDE_PATH  FILE_APPEND  LOCK_EX  Returns number of bytes written or false on error file_put_contents("test.txt", "text data");
  13. 13. More reading and writing PHP also has the C-style functions:  fscanf, fprintf – reads/writes data from file, parsing it according to format  fgets, fputs – read/write entire line from file  fgetc, fputc – read/write single character form file  fseek, ftell – set/get position of internal file pointer  rewind – sets file pointer in the beginning
  14. 14. File System and Directories
  15. 15. Listing files in directory glob($pattern, $flags) – list items in directory according pattern  Pattern is specified in an OS-dependant way  Flags – some of the flags that apply are:  GLOB_ONLYDIR – list only directories  GLOB_NOSORT – return without sorting  GLOB_NOESCAPE – backslashes in pattern are not considered escaping  Returns array or false on error foreach (glob("*.txt") as $file) echo $file.": ".filesize($file);
  16. 16. Listing files in directory opendir ($path, $context) – opens directory handle to be used in subsequent readdir calls readdir ($dir_handle) – read next item in the directory closedir ($dir_handle) $dh = opendir("/etc/"); while (false !== ($file = readdir($dh))) echo $file."n"; closedir($dh); opendir/readdir/closedir is safer than glob in terms of security  glob may allow shell injection
  17. 17. Creating directory mkdir($path, $mode, $recursive, $context) – create new directory  $path is the new directory path and name  $mode is optional parameter to specify the permissions  By default is assumed 0777  Ignored on Windows  $recursive – boolean, create all subdirectories too, if not found
  18. 18. File system functions file_exists ($name) – checks if file or directory exists copy ($source, $destination) – copy file/directory rename ($oldname, $newname) – rename file/directory  Also used for moving file or directory unlink ($filename) – delete file rmdir ($dirname) – delete directory
  19. 19. Names handling basename ($filename) – given full filename returns only the file name portion (removes directory parts) dirname ($filename) – like basename but returns the directory name, removes file nameecho basename("/home/avatar/temp.txt");echo dirname ("/home/avatar/temp.txt");// outputs// /home/avatar// temp.txt
  20. 20. Permissions Linux permissions are defined in three levels – owner, group and others  Each folder/file has owner and group IDs  Read, write and execute rights are assigned for owner, group and other users separately  In binary the rights are presented as 3 by 3 bits  Usual decimal representation is set of 3 numbers from 0 to 7 (octal representation)  Example: 777 means full rights for everyone  Example: 760 means full rights for owner, read and write for group members, no access for the rest
  21. 21. Read permissions filegroup($filename), fileowner($filename) – return the group/owner ID of the file/directory fileperms($filename) – returns integer with all the permissions of the file/directory  Including system file type – socket, link, directory, pipe, etc
  22. 22. Modify permissions chgrp ($filename, $group), chown ($filename, $user) – change group/owner of a file/directory  Group and owner can be specified as name or numerical ID chmod ($filename, $mode) – change the mode (permissions) of a file/directory  $mode is specified as integer  To ensure proper work, $mode should be given in octal mode (e.g.: 0755)
  23. 23. Simple permissions checks is_readable ($filename), is_writeable ($filename) – check if PHP can access given file for reading/writing  PHP scripts usually are executed with the apache user and inherit its rights, but not always  These functions check if the user that executes the script has access to the file
  24. 24. External processes PHP can start and communicate with other processes  Can start process, send to its input stream and read output/error data  The process inherits the permissions of the PHP/Apache process, unless specified different  Common use is sending email or processing uploaded files
  25. 25. Execute program exec ($command, $output, $return)  Starts process and waits for it to finish  Returns last line of output  $output and $return are optional – array that will get all output data and the return codeexec ("whoami");$list = array();exec ("ls –l /", $list, $return);
  26. 26. Execute program trough shell shell_exec ($command)  Similar to exec but executes the program trough shell  Returns the entire output  Also waits for the program to finish$lines = shell_exec("set");foreach ($lines as $line) { if (preg_match("/BASH=(.*)/",$line,$chunk)) echo $chunk[1];}
  27. 27. Starting process and attaching pipes Pipes are streams – one program writes on one end, another reads at the other  FIFO (First in, first out)  Each process has at least three pipes – input, output and error  Process reads from input, writes at output and error  PHP can start process and define handlers for its pipes  Can define more pipes if needed
  28. 28. Open process proc_open ($command, $descriptors, $pipes, $dir, $environment, $other)  Starts process with given pipe descriptors, working directory and other details  $descriptors is array, describing the pipes that PHP will handle  $dir is optional - sets current working directory for the process  $environment is optional parameter – array, containing the environmental variables to be passed  $other is optional array with additional options, primary for Windows
  29. 29. Open process $descriptors is indexed array of arrays  0 is input (stdin), 1 is output (stdout), 2 is error (stderr)  For each must be specified indexed array  First element is either "file" or "pipe"  In case of "pipe", second element is "r" for reading pipe or "w" for writing pipe  In case of "file" second element is the file, third is "r", "w" or "a" for read, write or append  For each of the items in $descriptors in $pipes array is created element with same index  The items in $pipes are used to read/write data
  30. 30. Open process Open process example$spec = array ( 0 => array ("pipe", "r"), 1 => array ("pipe", "w"), 2 => array ("file", "/var/log/mylog.log", "a"));$env = array ("PATH" => "/bin/bash");$p = proc_open("/bin/bash", $spec, $pipes, "/", $env);$procstdin = $pipes[0];$procstdout = $pipes[1];fwrite ($procstdin, "date");echo fread ($procstdout, 128);fclose($procstdin);fclose($procstdout);proc_close($p);  Pipes are read and written like ordinary files  Process is closed with proc_close
  31. 31. Files, Resources and Processes курсове и уроци по програмиране, уеб дизайн – безплатно BG Coder - онлайн състезателна система - online judge курсове и уроци по програмиране – Телерик академия форум програмиране, форум уеб дизайн уроци по програмиране и уеб дизайн за ученици ASP.NET курс - уеб програмиране, бази данни, C#, .NET, ASP.NET http://academy.telerik.com програмиране за деца – безплатни курсове и уроци ASP.NET MVC курс – HTML, SQL, C#, .NET, ASP.NET MVC безплатен SEO курс - оптимизация за търсачки алго академия – състезателно програмиране, състезаниякурсове и уроци по програмиране, книги – безплатно от Наков курс мобилни приложения с iPhone, Android, WP7, PhoneGap уроци по уеб дизайн, HTML, CSS, JavaScript, Photoshop Дончо Минков - сайт за програмиране free C# book, безплатна книга C#, книга Java, книга C# Николай Костов - блог за програмиране безплатен курс "Качествен програмен код" безплатен курс "Разработка на софтуер в cloud среда" C# курс, програмиране, безплатно
  32. 32. Exercises1. Create a PHP application that allows browsing given folders subfolders and files and displaying files contents
  33. 33. Exercises (2)2. Create a PHP application that allows interactive execution of shell commands
  34. 34. Free Trainings @ Telerik Academy “PHP & MySQL Web Design" course academy.telerik.com/.../php-school- academy-meeting Telerik Software Academy  academy.telerik.com Telerik Academy @ Facebook  facebook.com/TelerikAcademy Telerik Software Academy Forums  forums.academy.telerik.com