files, directories, permissions tran anh tuan edit from telerik software academy [email protected]

33
Files, Resources and Processes Files, Directories, Permissions Tran Anh Tuan Edit from Telerik Software Academy [email protected] http://www.math.hcmus.edu.vn/~tatuan

Upload: maud-dawson

Post on 17-Dec-2015

222 views

Category:

Documents


0 download

TRANSCRIPT

Files, Resources and Processes

Files, Directories, Permissions

Tran Anh Tuan

Edit from Telerik Software Academy

[email protected]

http://www.math.hcmus.edu.vn/~tatuan

Contents Working with files

Opening, reading, writing

Directories and file system Permissions Access external process

Opening fileReading and

writing

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

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");// example – open file test.txt for reading$fp = fopen ("test.txt", "r");

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);

// example – open file test.txt for reading// read 10 chars from it$fp = fopen ("test.txt", "r");if ($fp !== false)

echo fread ($fp, 10);

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);

// print file content:$fp = fopen ("test.txt", "r");while (!feof($fp)) echo fread ($fp, 32);

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!");$fp = fopen ("test.txt", "w");fwrite ($fp, "Hello world!");

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);

$fp = fopen ("test.txt", "w");fwrite ($fp, "Hello world!");fclose ($fp);

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 errorecho file_get_contents("test.txt");echo file_get_contents("test.txt");

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;?>

<?php$fp = fopen ("http://abv.bg/", "r");$content = '';while (!feof($fp)) {

$content .= fread ($fp, 512);}fclose ($fp);echo $content;?>

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 errorfile_put_contents("test.txt", "text data");file_put_contents("test.txt", "text data");

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

File System and

Directories

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 errorforeach (glob("*.txt") as $file)echo $file.": ".filesize($file);

foreach (glob("*.txt") as $file)echo $file.": ".filesize($file);

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)

opendir/readdir/closedir is safer than glob in terms of security

glob may allow shell injection

$dh = opendir("/etc/");while (false !== ($file = readdir($dh)))

echo $file."\n";closedir($dh);

$dh = opendir("/etc/");while (false !== ($file = readdir($dh)))

echo $file."\n";closedir($dh);

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

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

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

echo basename("/home/avatar/temp.txt");echo dirname ("/home/avatar/temp.txt");// outputs// /home/avatar// temp.txt

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

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

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)

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 it's rights, but not always

These functions check if the user that executes the script has access to the file

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

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);

exec ("whoami");$list = array();exec ("ls –l /", $list, $return);

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];}

$lines = shell_exec("set");foreach ($lines as $line) { if (preg_match("/BASH=(.*)/",$line,$chunk)) echo $chunk[1];}

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

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

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

Open process Open process example

Pipes are read and written like ordinary files

Process is closed with proc_close

$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);

$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);

форум програмиране, форум уеб дизайнкурсове и уроци по програмиране, уеб дизайн – безплатно

програмиране за деца – безплатни курсове и уроцибезплатен SEO курс - оптимизация за търсачки

уроци по уеб дизайн, HTML, CSS, JavaScript, Photoshop

уроци по програмиране и уеб дизайн за ученициASP.NET MVC курс – HTML, SQL, C#, .NET, ASP.NET MVC

безплатен курс "Разработка на софтуер в cloud среда"

BG Coder - онлайн състезателна система - online judge

курсове и уроци по програмиране, книги – безплатно от Наков

безплатен курс "Качествен програмен код"

алго академия – състезателно програмиране, състезания

ASP.NET курс - уеб програмиране, бази данни, C#, .NET, ASP.NETкурсове и уроци по програмиране – Телерик академия

курс мобилни приложения с iPhone, Android, WP7, PhoneGap

free C# book, безплатна книга C#, книга Java, книга C#Дончо Минков - сайт за програмиранеНиколай Костов - блог за програмиранеC# курс, програмиране, безплатно

?

? ? ??

?? ?

?

?

?

??

?

?

? ?

Questions?

?

Files, Resources and Processes

Exercises1. Create a PHP application that allows browsing given folder's subfolders and files and displaying file's contents

Exercises (2)2. Create a PHP application that allows interactive execution of shell commands