100 likes | 267 Vues
PHP. Working with Files. File Modes. Opening a File. fopen (path_to_file, file_mode). Reading from a File. Fgets() is used to read a file one line at a time. <?php $MyFile = fopen(“daftar.txt", 'r'); if (!$MyFile) { echo '<p>Cannot open file.'; } else {
E N D
PHP Working with Files
File Modes Perancangan dan Pemrograman Web: PHP (wcw) Opening a File • fopen (path_to_file, file_mode)
Perancangan dan Pemrograman Web: PHP (wcw) Reading from a File • Fgets() • is used to read a file one line at a time <?php $MyFile = fopen(“daftar.txt", 'r'); if (!$MyFile) { echo '<p>Cannot open file.'; } else { while (!feof($MyFile)) { $Employee = fgets($MyFile, 999); echo $Employee.'<br />'; } fclose($MyFile); } ?>
Perancangan dan Pemrograman Web: PHP (wcw) Writing to a File • fwrite() • fwrite(file_pointer,output_string) <? $OutputString=‘Menulis teks ke dalam file'; $MyFile = fopen(‘daftar.txt', 'a'); fwrite($MyFile, $OutputString); fclose($MyFile); ?>
Perancangan dan Pemrograman Web: PHP (wcw) Session • Session Functions
Perancangan dan Pemrograman Web: PHP (wcw) Using Session <? //Begin a session and create a session variable in //the $_SESSION array. session_start(); $_SESSION[‘user'] = ‘Susilo'; echo $_SESSION[‘user']; ?>
Perancangan dan Pemrograman Web: PHP (wcw) Using Session <? session_start(); if (isset($_SESSION[‘user'])) { echo “You are Authorized as” . $_SESSION[‘user’] ; unset($_SESSION[‘user’]) ; } ?>
Perancangan dan Pemrograman Web: PHP (wcw) Killing Session <? session_unset(); session_destroy() ; ?>
Perancangan dan Pemrograman Web: PHP (wcw) Directories • File_exists • Check if a directory or a file exists $dirpath = "/home/wibowo/ppw” ; if (! file_exists($dirpath)) { mkdir($dirpath, 0777); echo “Directory is created now!” }
Perancangan dan Pemrograman Web: PHP (wcw) Directories • readdir • Reading contents of a directory $dirpath = "/home/wibowo/ppw” ; $dir_handle=@opendir($dirpath) or die("Unable to open $dirpath"); $flist = array() ; while ($file = readdir($dir_handle)) { if (! ($file == "." || $file=="..")) { $flist[] = $file ; } } sort ($flist) ; foreach ($flist as $file) echo $file . “<br />” ; closedir($dir_handle);