CS174
Chris Pollett
Sep 28, 2016
On Monday, we described how to declare functions in PHP, how to do string manipulation in PHP, and how to read and write from a file in PHP. Today, we start by looking at some more sophisticated file handling in PHP. To start, we consider file locking...
$fp = fopen("/tmp/my-data.txt", "w"); if (flock($fp, LOCK_EX)) { // do an exclusive/write lock. use LOCK_SH (for shared/read lock) fwrite($fp, "Write something here\n"); flock($fp, LOCK_UN); // release the lock } else { echo "Couldn't lock the file !"; } fclose($fp);Locks are released when fclose() is called.
rename($oldname, $newname); //like Unix mv command, renames/moves a file copy($source, $dest); //copies a file, like Unix cp unlink($filename); // delete a file mkdir($path); // make a directory rmdir($path); // delete a directory link($target, $name); // create a link chmod($filename, $mode); // change file permissions chown($filename, $user); // change owner of a file or dir or link chgrp($filename, $group); //change group of a file or dir or link stat($filename); //returns an array saying size, last access, last modified, etc. for a file touch($filename [, int $time = time() [, int $atime ]]); //sets modification/ access times of a file
if(file_exists('/path/to/folder')) { //file_exists check if a file or dir exists $h = opendir('/path/to/folder'); //can use is_dir to check is something is a directory while (($item = readdir($h)) !== false) { $type = is_dir($item) ? "directory" : (is_link($item) ? "link" : "file"); //there is also a is_file echo "$item is a $type\n"; } }
$text_files = glob("/some_path/*.txt"); foreach($text_files as $file_name) { //do something }
Set-Cookie: name=value;Expires=some date;Path=some path;Domain=some_domain;
Cookie: name=value
Cookie: name1=value1; name2=value2; ...to send back multiple cookies.
$_SESSION["test"]=37; /* sets the test session variable*/ echo $_SESSION["test"];
$_SESSION['time']
variable only if $_REQUEST['set_time']
is non-empty. In this case, it should also check if $_REQUEST['name']
is set and store that into $_SESSION['name']
.print_r
the $_SESSION
variable.phpinfo()
where the session file is stored on your machine. What are the contents of this file after your program stores info by the above process?session_start
. Make sure error reporting is on (error_reporting(-1);
ini_set('display_errors', 'On');
) For each of the following scenarios
say what error messages you get if any when you run your program.
some_file.php
does not existsome_file.php
consists of a single space.some_file.php
consists of the five characters: <?php