MPSI - Fakultas Ilmu Komputer UI

Download Report

Transcript MPSI - Fakultas Ilmu Komputer UI

PHP
Working with Files
Opening a File
• fopen (path_to_file, file_mode)
File
Mode
Description
r
open for reading
w
open for writing (erases existing content); creates new file if one doesn't exist
a
open for appending to end of content; creates new file if one doesn't exist
x
create and open for writing (new in PHP 4.3.2)
r+
open for reading and writing (erases existing content when file is written to)
w+
open for writing and reading (erases existing content on opening or creates
new file if one doesn't exist
a+
open for appending and writing; creates new file if one doesn't exist
x+
create and open for writing and reading (new in PHP 4.3.2)
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
Function
Explanation
session_start()
Starts new session if one does not exist. Continues
current session if one exists.
session_unset()
Unsets all session variables.
session_destroy()
Kills session.
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);
Perancangan dan Pemrograman Web: PHP (wcw)