SlideShare una empresa de Scribd logo
1 de 31
1 PHP include file 
CS380
PHP Include File 
 Insert the content of one PHP file into another 
PHP file before the server executes it 
 Use the 
 include() generates a warning, but the script 
will continue execution 
 require() generates a fatal error, and the 
script will stop 
CS380 
2
include() example 
3 
<a href="/default.php">Home</a> 
<a href="/tutorials.php">Tutorials</a> 
<a href="/references.php">References</a> 
<a href="/examples.php">Examples</a> 
<a href="/contact.php">Contact Us</a> PHP 
<html> 
<body> 
<div class="leftmenu"> 
<?php include("menu.php"); ?> 
</div> 
<h1>Welcome to my home page.</h1> 
<p>I have a great menu here.</p> 
</body> 
</html> PHP
4 PHP File Input/Output 
CS380
PHP file I/O functions 
function name(s) category 
file, file_get_contents, 
file_put_contents 
reading/writing entire files 
basename, file_exists, 
filesize, 
fileperms, filemtime, is_dir, 
is_readable, is_writable, 
disk_free_space 
asking for information 
copy, rename, unlink, 
chmod, chgrp, chown, 
mkdir, rmdir 
manipulating files and 
directories 
glob, scandir reading directories 
CS380 
5
Reading/writing files 
contents of 
foo.txt 
file("foo.txt") 
file_get_contents 
("foo.txt") 
Hello 
how are 
you? 
I'm fine 
array( 
"Hellon", #0 
"how aren", #1 
"you?n", #2 
"n", #3 
"I'm finen" #4 
) 
"Hellon 
how aren 
you?n 
n 
I'm finen" 
CS380 
6 
 file returns lines of a file as an array 
 file_get_contents returns entire contents of a file 
as a string
Reading/writing an entire file 
 file_get_contents returns entire contents of a file 
as a string 
 file_put_contents writes a string into a file, 
replacing any prior contents 
CS380 
7 
# reverse a file 
$text = file_get_contents("poem.txt"); 
$text = strrev($text); 
file_put_contents("poem.txt", $text); PHP
Appending to a file 
CS380 
8 
# add a line to a file 
$new_text = "P.S. ILY, GTG TTYL!~"; 
file_put_contents("poem.txt", $new_text, 
FILE_APPEND); PHP 
old contents new contents 
Roses are red, 
Violets are blue. 
All my base, 
Are belong to you. 
Roses are red, 
Violets are blue. 
All my base, 
Are belong to you. 
P.S. ILY, GTG TTYL!~
The file function 
9 
# display lines of file as a bulleted list 
$lines = file("todolist.txt"); 
foreach ($lines as $line) { 
?> 
<li> <?= $line ?> </li> 
<?php 
} 
?> PHP 
 file returns the lines of a file as an array of strings 
 each string ends with n 
 to strip the n off each line, use optional second parameter: 
$lines = file("todolist.txt",FILE_IGNORE_NEW_LINES); 
PHP
Unpacking an array: list 
10 
list($var1, ..., $varN) = array; PHP 
$values = array(“mundruid", "18", “f", "96"); 
... 
list($username, $age, $gender, $iq) = $values; 
 the list function accepts a comma-separated list of 
variable names as parameters 
 use this to quickly "unpack" an array's contents into 
several variables 
PHP 
CS380
Fixed-length files, file and 
list 
11 
Xenia Mountrouidou 
(919)685-2181 
570-86-7326 contents of file personal.txt 
list($name, $phone, $ssn) = file("personal.txt"); 
 reads the file into an array of lines and unpacks the lines 
into variables 
 Need to know a file's exact length/format 
PHP 
CS380
Splitting/joining strings 
12 
$array = explode(delimiter, string); 
$string = implode(delimiter, array); 
PHP 
$class = "CS 380 01"; 
$class1 = explode(" ", $s); # ("CS", “380", “01") 
$class2 = implode("...", $a); # "CSE...380...01" 
 explode and implode convert between strings and 
arrays 
PHP 
CS380
Example explode 
13 
Harry Potter, J.K. Rowling 
The Lord of the Rings, J.R.R. Tolkien 
Dune, Frank Herbert 
contents of input file books.txt 
<?php foreach (file(“books.txt") as $book) { 
list($title, $author) = explode(“,", $book); 
?> 
<p> Book title: <?= $title ?>, Author: <?= 
$author ?> </p> 
<?php 
} 
?> PHP 
CS380
Reading directories 
function description 
scandir 
returns an array of all file 
names in a given directory 
(returns just the file names, 
such as "myfile.txt") 
glob 
returns an array of all file 
names that match a given 
pattern 
(returns a file path and 
name, such as 
"foo/bar/myfile.txt") 
CS380 
14
Example for glob 
15 
# reverse all poems in the poetry directory 
$poems = glob("poetry/poem*.dat"); 
foreach ($poems as $poemfile) { 
$text = file_get_contents($poemfile); 
file_put_contents($poemfile, strrev($text)); 
print "I just reversed " . 
basename($poemfile); 
} PHP 
 glob can match a "wildcard" path with the * character 
 the basename function strips any leading directory from 
a file path 
CS380
Example for glob 
16 
# reverse all poems in the poetry directory 
$poems = glob("poetry/poem*.dat"); 
foreach ($poems as $poemfile) { 
$text = file_get_contents($poemfile); 
file_put_contents($poemfile, strrev($text)); 
print "I just reversed " . 
basename($poemfile); 
} PHP 
 glob can match a "wildcard" path with the * character 
 the basename function strips any leading directory from 
a file path 
CS380
Example for scandir 
17 
<ul> 
<?php 
$folder = "taxes/old"; 
foreach (scandir($folder) as $filename) { 
?> 
<li> <?= $filename ?> </li> 
<?php 
} 
?> 
</ul> PHP 
• . 
• .. 
• 2009_w2.pdf 
• 2007_1099.doc output
18 PHP Exceptions 
CS380
Exceptions 
 Used to change the normal flow of the code 
execution if a specified error (exceptional) 
condition occurs. 
 What normally happens when an exception is 
triggered: 
 current code state is saved 
 code execution will switch to a predefined 
(custom) exception handler function 
 the handler may then 
 resume the execution from the saved code state, 
 terminate the script execution or 
 continue the script from a different location in the code 
19
Exception example 
20 
<?php 
//create function with an exception 
function checkStr($str) 
{ 
if(strcmp($str, “correct”)!= 0) 
{ 
throw new Exception(“String is not correct!"); 
} 
return true; 
} 
//trigger exception 
checkStr(“wrong”); 
?> PHP 
CS380
Exception example (cont.) 
21 
<?php 
//create function with an exception 
function checkStr($str) 
{ 
… 
} 
//trigger exception in a "try" block 
try 
{ 
checkStr(“wrong”); 
//If the exception is thrown, this text will not be shown 
echo 'If you see this, the string is correct'; 
} 
//catch exception 
catch(Exception $e) 
{ 
echo 'Message: ' .$e->getMessage(); 
} 
?> PHP
PHP larger example 
 Display a random quote of the day: 
 I don't know half of you half as well as I should like; and I like less 
than half of you half as well as you deserve. 
J. R. R. Tolkien (1892 - 1973), The Fellowship of the Ring 
 I have not failed. I've just found 10,000 ways that won't work. 
Thomas A. Edison (1847 - 1931), (attributed) 
 I am among those who think that science has great beauty. A 
scientist in his laboratory is not only a technician: he is also a child 
placed before natural phenomena which impress him like a fairy 
tale. 
Marie Curie (1867 - 1934) 
 I love deadlines. I like the whooshing sound they make as they fly 
by. Douglas Adams 
 Statistics: The only science that enables different experts using the 
same figures to draw different conclusions. 
22
23 PHP cookies and sessions 
CS380
Cookies 
 Problem: HTTP is stateless 
 What is a cookie? 
 tiny bits of information that a web site could store 
on the client's machine 
 they are sent back to the web site each time a 
new page is requested by this client. 
CS380 
24
Bad Cookies? 
 Urban myth: tracking, violate privacy 
 Reality: 
 cookies are relatively harmless 
 can only store a small amount of information 
CS380 
25
Sessions 
 What is a session? 
 a combination of a server-side cookie and a 
client-side cookie, 
 the client-side cookie contains only a reference to 
the correct data on the server. 
 when the user visits the site: 
 their browser sends the reference code to the 
server 
 the server loads the corresponding data. 
CS380 
26
Cookies vs Sessions 
 Cookies can be set to a long lifespan 
 Cookies work smoothly when you have a 
cluster of web servers 
 Sessions are stored on the server, i.e. clients 
do not have access to the information you 
store about 
 Session data does not need to be transmitted 
with each page; clients just need to send an ID 
and the data is loaded from the local file. 
 Sessions can be any size you want because 
they are held on your server, 
27
Create a cookie 
28 
setcookie(name, value, expire, path, domain); 
PHP 
<?php 
setcookie("user", “Harry Poter", time()+3600); 
?> 
<html> 
..... 
CS380 
PHP
Retrieve a Cookie Value 
29 
<?php 
// Print a cookie 
echo $_COOKIE["user"]; 
// A way to view all cookies 
print_r($_COOKIE); 
?> 
CS380 
PHP
Delete a Cookie 
30 
<?php 
// set the expiration date to one hour ago 
setcookie("user", "", time()+3600); 
?> 
CS380 
PHP
Start/end a session 
31 
bool session_start ( void ) 
bool session_destroy ( void ) PHP 
 All your session data is stored in the session 
superglobal array, $_SESSION 
$_SESSION['var'] = $val; 
$_SESSION['FirstName'] = "Jim"; PHP 
CS380

Más contenido relacionado

La actualidad más candente

Teaching Your Machine To Find Fraudsters
Teaching Your Machine To Find FraudstersTeaching Your Machine To Find Fraudsters
Teaching Your Machine To Find FraudstersIan Barber
 
Créer une base NoSQL en 1 heure
Créer une base NoSQL en 1 heureCréer une base NoSQL en 1 heure
Créer une base NoSQL en 1 heureAmaury Bouchard
 
How to stand on the shoulders of giants
How to stand on the shoulders of giantsHow to stand on the shoulders of giants
How to stand on the shoulders of giantsIan Barber
 
Redis for the Everyday Developer
Redis for the Everyday DeveloperRedis for the Everyday Developer
Redis for the Everyday DeveloperRoss Tuck
 
ZeroMQ Is The Answer
ZeroMQ Is The AnswerZeroMQ Is The Answer
ZeroMQ Is The AnswerIan Barber
 
PHP7 - Scalar Type Hints & Return Types
PHP7 - Scalar Type Hints & Return TypesPHP7 - Scalar Type Hints & Return Types
PHP7 - Scalar Type Hints & Return TypesEric Poe
 
Character_Device_drvier_pc
Character_Device_drvier_pcCharacter_Device_drvier_pc
Character_Device_drvier_pcRashila Rr
 
ZeroMQ Is The Answer: DPC 11 Version
ZeroMQ Is The Answer: DPC 11 VersionZeroMQ Is The Answer: DPC 11 Version
ZeroMQ Is The Answer: DPC 11 VersionIan Barber
 
PSR-7 and PSR-15, why can't you ignore them
PSR-7 and PSR-15, why can't you ignore themPSR-7 and PSR-15, why can't you ignore them
PSR-7 and PSR-15, why can't you ignore themSérgio Rafael Siqueira
 
Mengembalikan data yang terhapus atau rusak pada hardisk menggunakan ubuntu
Mengembalikan data yang terhapus atau rusak pada hardisk menggunakan ubuntuMengembalikan data yang terhapus atau rusak pada hardisk menggunakan ubuntu
Mengembalikan data yang terhapus atau rusak pada hardisk menggunakan ubuntuAlferizhy Chalter
 
ZeroMQ: Messaging Made Simple
ZeroMQ: Messaging Made SimpleZeroMQ: Messaging Made Simple
ZeroMQ: Messaging Made SimpleIan Barber
 
Introdução ao Perl 6
Introdução ao Perl 6Introdução ao Perl 6
Introdução ao Perl 6garux
 
Meet up symfony 16 juin 2017 - Les PSR
Meet up symfony 16 juin 2017 -  Les PSRMeet up symfony 16 juin 2017 -  Les PSR
Meet up symfony 16 juin 2017 - Les PSRJulien Vinber
 

La actualidad más candente (18)

Cod
CodCod
Cod
 
Teaching Your Machine To Find Fraudsters
Teaching Your Machine To Find FraudstersTeaching Your Machine To Find Fraudsters
Teaching Your Machine To Find Fraudsters
 
File system
File systemFile system
File system
 
Créer une base NoSQL en 1 heure
Créer une base NoSQL en 1 heureCréer une base NoSQL en 1 heure
Créer une base NoSQL en 1 heure
 
How to stand on the shoulders of giants
How to stand on the shoulders of giantsHow to stand on the shoulders of giants
How to stand on the shoulders of giants
 
Redis for the Everyday Developer
Redis for the Everyday DeveloperRedis for the Everyday Developer
Redis for the Everyday Developer
 
ZeroMQ Is The Answer
ZeroMQ Is The AnswerZeroMQ Is The Answer
ZeroMQ Is The Answer
 
PHP7 - Scalar Type Hints & Return Types
PHP7 - Scalar Type Hints & Return TypesPHP7 - Scalar Type Hints & Return Types
PHP7 - Scalar Type Hints & Return Types
 
Character_Device_drvier_pc
Character_Device_drvier_pcCharacter_Device_drvier_pc
Character_Device_drvier_pc
 
ZeroMQ Is The Answer: DPC 11 Version
ZeroMQ Is The Answer: DPC 11 VersionZeroMQ Is The Answer: DPC 11 Version
ZeroMQ Is The Answer: DPC 11 Version
 
Vcs28
Vcs28Vcs28
Vcs28
 
PSR-7 and PSR-15, why can't you ignore them
PSR-7 and PSR-15, why can't you ignore themPSR-7 and PSR-15, why can't you ignore them
PSR-7 and PSR-15, why can't you ignore them
 
Mengembalikan data yang terhapus atau rusak pada hardisk menggunakan ubuntu
Mengembalikan data yang terhapus atau rusak pada hardisk menggunakan ubuntuMengembalikan data yang terhapus atau rusak pada hardisk menggunakan ubuntu
Mengembalikan data yang terhapus atau rusak pada hardisk menggunakan ubuntu
 
ZeroMQ: Messaging Made Simple
ZeroMQ: Messaging Made SimpleZeroMQ: Messaging Made Simple
ZeroMQ: Messaging Made Simple
 
Introdução ao Perl 6
Introdução ao Perl 6Introdução ao Perl 6
Introdução ao Perl 6
 
My First Ruby
My First RubyMy First Ruby
My First Ruby
 
Meet up symfony 16 juin 2017 - Les PSR
Meet up symfony 16 juin 2017 -  Les PSRMeet up symfony 16 juin 2017 -  Les PSR
Meet up symfony 16 juin 2017 - Les PSR
 
Basics of Unix Adminisration
Basics  of Unix AdminisrationBasics  of Unix Adminisration
Basics of Unix Adminisration
 

Destacado

Cánones de belleza: la alienación femenina
Cánones de belleza: la alienación femeninaCánones de belleza: la alienación femenina
Cánones de belleza: la alienación femeninaUniversidad del Quindío
 
El segundo sexo: alcances, logros y fracasos sobre la condición de la mujer e...
El segundo sexo: alcances, logros y fracasos sobre la condición de la mujer e...El segundo sexo: alcances, logros y fracasos sobre la condición de la mujer e...
El segundo sexo: alcances, logros y fracasos sobre la condición de la mujer e...Universidad del Quindío
 
Come to the confidential & anonymous side of Internet
Come to the confidential & anonymous side of InternetCome to the confidential & anonymous side of Internet
Come to the confidential & anonymous side of InternetWith_it_app
 
La náusea como captación no posicional de la propia existencia
La náusea como  captación no posicional de la propia existenciaLa náusea como  captación no posicional de la propia existencia
La náusea como captación no posicional de la propia existenciaUniversidad del Quindío
 
¿Por qué la gente se suicida? La otra versión
¿Por qué la gente se suicida? La otra versión¿Por qué la gente se suicida? La otra versión
¿Por qué la gente se suicida? La otra versiónUniversidad del Quindío
 
EL SENTIDO DE LA EXISTENCIA: DOS PERSPECTIVAS
EL SENTIDO DE LA EXISTENCIA: DOS PERSPECTIVASEL SENTIDO DE LA EXISTENCIA: DOS PERSPECTIVAS
EL SENTIDO DE LA EXISTENCIA: DOS PERSPECTIVASUniversidad del Quindío
 
Legitimación de la violencia como principio de equilibrio social
Legitimación de la violencia como principio de equilibrio socialLegitimación de la violencia como principio de equilibrio social
Legitimación de la violencia como principio de equilibrio socialUniversidad del Quindío
 
Презентація проекту TOUA
Презентація проекту TOUAПрезентація проекту TOUA
Презентація проекту TOUAKatya Yuschenko
 
Immobilized enzyme
Immobilized enzymeImmobilized enzyme
Immobilized enzymebansalaman80
 
ms excel presentation...
ms excel presentation...ms excel presentation...
ms excel presentation...alok1994
 
El suicidio como recuperacion de la subjetividad
El suicidio como recuperacion de la subjetividadEl suicidio como recuperacion de la subjetividad
El suicidio como recuperacion de la subjetividadUniversidad del Quindío
 

Destacado (16)

Cánones de belleza: la alienación femenina
Cánones de belleza: la alienación femeninaCánones de belleza: la alienación femenina
Cánones de belleza: la alienación femenina
 
Selfie: el olvido del ser-para-otro
Selfie: el olvido del ser-para-otroSelfie: el olvido del ser-para-otro
Selfie: el olvido del ser-para-otro
 
Tecnología y ciberexistencia
Tecnología y ciberexistenciaTecnología y ciberexistencia
Tecnología y ciberexistencia
 
El segundo sexo: alcances, logros y fracasos sobre la condición de la mujer e...
El segundo sexo: alcances, logros y fracasos sobre la condición de la mujer e...El segundo sexo: alcances, logros y fracasos sobre la condición de la mujer e...
El segundo sexo: alcances, logros y fracasos sobre la condición de la mujer e...
 
Het Watergateschandaal
Het WatergateschandaalHet Watergateschandaal
Het Watergateschandaal
 
Come to the confidential & anonymous side of Internet
Come to the confidential & anonymous side of InternetCome to the confidential & anonymous side of Internet
Come to the confidential & anonymous side of Internet
 
La náusea como captación no posicional de la propia existencia
La náusea como  captación no posicional de la propia existenciaLa náusea como  captación no posicional de la propia existencia
La náusea como captación no posicional de la propia existencia
 
¿Por qué la gente se suicida? La otra versión
¿Por qué la gente se suicida? La otra versión¿Por qué la gente se suicida? La otra versión
¿Por qué la gente se suicida? La otra versión
 
EL SENTIDO DE LA EXISTENCIA: DOS PERSPECTIVAS
EL SENTIDO DE LA EXISTENCIA: DOS PERSPECTIVASEL SENTIDO DE LA EXISTENCIA: DOS PERSPECTIVAS
EL SENTIDO DE LA EXISTENCIA: DOS PERSPECTIVAS
 
El suicidio como derecho humano
El suicidio como derecho humanoEl suicidio como derecho humano
El suicidio como derecho humano
 
Legitimación de la violencia como principio de equilibrio social
Legitimación de la violencia como principio de equilibrio socialLegitimación de la violencia como principio de equilibrio social
Legitimación de la violencia como principio de equilibrio social
 
Презентація проекту TOUA
Презентація проекту TOUAПрезентація проекту TOUA
Презентація проекту TOUA
 
Immobilized enzyme
Immobilized enzymeImmobilized enzyme
Immobilized enzyme
 
ms excel presentation...
ms excel presentation...ms excel presentation...
ms excel presentation...
 
El suicidio como recuperacion de la subjetividad
El suicidio como recuperacion de la subjetividadEl suicidio como recuperacion de la subjetividad
El suicidio como recuperacion de la subjetividad
 
The advocates act, 1961
The advocates act, 1961The advocates act, 1961
The advocates act, 1961
 

Similar a 08 php-files

Php interview-questions and answers
Php interview-questions and answersPhp interview-questions and answers
Php interview-questions and answerssheibansari
 
Web2py Code Lab
Web2py Code LabWeb2py Code Lab
Web2py Code LabColin Su
 
Learn PHP Lacture2
Learn PHP Lacture2Learn PHP Lacture2
Learn PHP Lacture2ADARSH BHATT
 
PHP Arrays - indexed and associative array.
PHP Arrays - indexed and associative array. PHP Arrays - indexed and associative array.
PHP Arrays - indexed and associative array. wahidullah mudaser
 
&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />tutorialsruby
 
PHP and MySQL with snapshots
 PHP and MySQL with snapshots PHP and MySQL with snapshots
PHP and MySQL with snapshotsrichambra
 
php-mysql-tutorial-part-3
php-mysql-tutorial-part-3php-mysql-tutorial-part-3
php-mysql-tutorial-part-3tutorialsruby
 
&lt;b>PHP&lt;/b>/MySQL &lt;b>Tutorial&lt;/b> webmonkey/programming/
&lt;b>PHP&lt;/b>/MySQL &lt;b>Tutorial&lt;/b> webmonkey/programming/&lt;b>PHP&lt;/b>/MySQL &lt;b>Tutorial&lt;/b> webmonkey/programming/
&lt;b>PHP&lt;/b>/MySQL &lt;b>Tutorial&lt;/b> webmonkey/programming/tutorialsruby
 
php-mysql-tutorial-part-3
php-mysql-tutorial-part-3php-mysql-tutorial-part-3
php-mysql-tutorial-part-3tutorialsruby
 
4 - Files and Directories - Pemrograman Internet Lanjut.pptx
4 - Files and Directories - Pemrograman Internet Lanjut.pptx4 - Files and Directories - Pemrograman Internet Lanjut.pptx
4 - Files and Directories - Pemrograman Internet Lanjut.pptxMasSam13
 
Introduction to source{d} Engine and source{d} Lookout
Introduction to source{d} Engine and source{d} Lookout Introduction to source{d} Engine and source{d} Lookout
Introduction to source{d} Engine and source{d} Lookout source{d}
 
The Ring programming language version 1.8 book - Part 50 of 202
The Ring programming language version 1.8 book - Part 50 of 202The Ring programming language version 1.8 book - Part 50 of 202
The Ring programming language version 1.8 book - Part 50 of 202Mahmoud Samir Fayed
 

Similar a 08 php-files (20)

Synapse india basic php development part 1
Synapse india basic php development part 1Synapse india basic php development part 1
Synapse india basic php development part 1
 
PHP code examples
PHP code examplesPHP code examples
PHP code examples
 
Php interview-questions and answers
Php interview-questions and answersPhp interview-questions and answers
Php interview-questions and answers
 
php part 2
php part 2php part 2
php part 2
 
Web2py Code Lab
Web2py Code LabWeb2py Code Lab
Web2py Code Lab
 
Learn PHP Lacture2
Learn PHP Lacture2Learn PHP Lacture2
Learn PHP Lacture2
 
Day1
Day1Day1
Day1
 
PHP Arrays - indexed and associative array.
PHP Arrays - indexed and associative array. PHP Arrays - indexed and associative array.
PHP Arrays - indexed and associative array.
 
&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />
 
PHP and MySQL with snapshots
 PHP and MySQL with snapshots PHP and MySQL with snapshots
PHP and MySQL with snapshots
 
php-mysql-tutorial-part-3
php-mysql-tutorial-part-3php-mysql-tutorial-part-3
php-mysql-tutorial-part-3
 
&lt;b>PHP&lt;/b>/MySQL &lt;b>Tutorial&lt;/b> webmonkey/programming/
&lt;b>PHP&lt;/b>/MySQL &lt;b>Tutorial&lt;/b> webmonkey/programming/&lt;b>PHP&lt;/b>/MySQL &lt;b>Tutorial&lt;/b> webmonkey/programming/
&lt;b>PHP&lt;/b>/MySQL &lt;b>Tutorial&lt;/b> webmonkey/programming/
 
php-mysql-tutorial-part-3
php-mysql-tutorial-part-3php-mysql-tutorial-part-3
php-mysql-tutorial-part-3
 
Presentaion
PresentaionPresentaion
Presentaion
 
07 php
07 php07 php
07 php
 
4 - Files and Directories - Pemrograman Internet Lanjut.pptx
4 - Files and Directories - Pemrograman Internet Lanjut.pptx4 - Files and Directories - Pemrograman Internet Lanjut.pptx
4 - Files and Directories - Pemrograman Internet Lanjut.pptx
 
Introduction to source{d} Engine and source{d} Lookout
Introduction to source{d} Engine and source{d} Lookout Introduction to source{d} Engine and source{d} Lookout
Introduction to source{d} Engine and source{d} Lookout
 
The Ring programming language version 1.8 book - Part 50 of 202
The Ring programming language version 1.8 book - Part 50 of 202The Ring programming language version 1.8 book - Part 50 of 202
The Ring programming language version 1.8 book - Part 50 of 202
 
Php session
Php sessionPhp session
Php session
 
lab4_php
lab4_phplab4_php
lab4_php
 

08 php-files

  • 1. 1 PHP include file CS380
  • 2. PHP Include File  Insert the content of one PHP file into another PHP file before the server executes it  Use the  include() generates a warning, but the script will continue execution  require() generates a fatal error, and the script will stop CS380 2
  • 3. include() example 3 <a href="/default.php">Home</a> <a href="/tutorials.php">Tutorials</a> <a href="/references.php">References</a> <a href="/examples.php">Examples</a> <a href="/contact.php">Contact Us</a> PHP <html> <body> <div class="leftmenu"> <?php include("menu.php"); ?> </div> <h1>Welcome to my home page.</h1> <p>I have a great menu here.</p> </body> </html> PHP
  • 4. 4 PHP File Input/Output CS380
  • 5. PHP file I/O functions function name(s) category file, file_get_contents, file_put_contents reading/writing entire files basename, file_exists, filesize, fileperms, filemtime, is_dir, is_readable, is_writable, disk_free_space asking for information copy, rename, unlink, chmod, chgrp, chown, mkdir, rmdir manipulating files and directories glob, scandir reading directories CS380 5
  • 6. Reading/writing files contents of foo.txt file("foo.txt") file_get_contents ("foo.txt") Hello how are you? I'm fine array( "Hellon", #0 "how aren", #1 "you?n", #2 "n", #3 "I'm finen" #4 ) "Hellon how aren you?n n I'm finen" CS380 6  file returns lines of a file as an array  file_get_contents returns entire contents of a file as a string
  • 7. Reading/writing an entire file  file_get_contents returns entire contents of a file as a string  file_put_contents writes a string into a file, replacing any prior contents CS380 7 # reverse a file $text = file_get_contents("poem.txt"); $text = strrev($text); file_put_contents("poem.txt", $text); PHP
  • 8. Appending to a file CS380 8 # add a line to a file $new_text = "P.S. ILY, GTG TTYL!~"; file_put_contents("poem.txt", $new_text, FILE_APPEND); PHP old contents new contents Roses are red, Violets are blue. All my base, Are belong to you. Roses are red, Violets are blue. All my base, Are belong to you. P.S. ILY, GTG TTYL!~
  • 9. The file function 9 # display lines of file as a bulleted list $lines = file("todolist.txt"); foreach ($lines as $line) { ?> <li> <?= $line ?> </li> <?php } ?> PHP  file returns the lines of a file as an array of strings  each string ends with n  to strip the n off each line, use optional second parameter: $lines = file("todolist.txt",FILE_IGNORE_NEW_LINES); PHP
  • 10. Unpacking an array: list 10 list($var1, ..., $varN) = array; PHP $values = array(“mundruid", "18", “f", "96"); ... list($username, $age, $gender, $iq) = $values;  the list function accepts a comma-separated list of variable names as parameters  use this to quickly "unpack" an array's contents into several variables PHP CS380
  • 11. Fixed-length files, file and list 11 Xenia Mountrouidou (919)685-2181 570-86-7326 contents of file personal.txt list($name, $phone, $ssn) = file("personal.txt");  reads the file into an array of lines and unpacks the lines into variables  Need to know a file's exact length/format PHP CS380
  • 12. Splitting/joining strings 12 $array = explode(delimiter, string); $string = implode(delimiter, array); PHP $class = "CS 380 01"; $class1 = explode(" ", $s); # ("CS", “380", “01") $class2 = implode("...", $a); # "CSE...380...01"  explode and implode convert between strings and arrays PHP CS380
  • 13. Example explode 13 Harry Potter, J.K. Rowling The Lord of the Rings, J.R.R. Tolkien Dune, Frank Herbert contents of input file books.txt <?php foreach (file(“books.txt") as $book) { list($title, $author) = explode(“,", $book); ?> <p> Book title: <?= $title ?>, Author: <?= $author ?> </p> <?php } ?> PHP CS380
  • 14. Reading directories function description scandir returns an array of all file names in a given directory (returns just the file names, such as "myfile.txt") glob returns an array of all file names that match a given pattern (returns a file path and name, such as "foo/bar/myfile.txt") CS380 14
  • 15. Example for glob 15 # reverse all poems in the poetry directory $poems = glob("poetry/poem*.dat"); foreach ($poems as $poemfile) { $text = file_get_contents($poemfile); file_put_contents($poemfile, strrev($text)); print "I just reversed " . basename($poemfile); } PHP  glob can match a "wildcard" path with the * character  the basename function strips any leading directory from a file path CS380
  • 16. Example for glob 16 # reverse all poems in the poetry directory $poems = glob("poetry/poem*.dat"); foreach ($poems as $poemfile) { $text = file_get_contents($poemfile); file_put_contents($poemfile, strrev($text)); print "I just reversed " . basename($poemfile); } PHP  glob can match a "wildcard" path with the * character  the basename function strips any leading directory from a file path CS380
  • 17. Example for scandir 17 <ul> <?php $folder = "taxes/old"; foreach (scandir($folder) as $filename) { ?> <li> <?= $filename ?> </li> <?php } ?> </ul> PHP • . • .. • 2009_w2.pdf • 2007_1099.doc output
  • 19. Exceptions  Used to change the normal flow of the code execution if a specified error (exceptional) condition occurs.  What normally happens when an exception is triggered:  current code state is saved  code execution will switch to a predefined (custom) exception handler function  the handler may then  resume the execution from the saved code state,  terminate the script execution or  continue the script from a different location in the code 19
  • 20. Exception example 20 <?php //create function with an exception function checkStr($str) { if(strcmp($str, “correct”)!= 0) { throw new Exception(“String is not correct!"); } return true; } //trigger exception checkStr(“wrong”); ?> PHP CS380
  • 21. Exception example (cont.) 21 <?php //create function with an exception function checkStr($str) { … } //trigger exception in a "try" block try { checkStr(“wrong”); //If the exception is thrown, this text will not be shown echo 'If you see this, the string is correct'; } //catch exception catch(Exception $e) { echo 'Message: ' .$e->getMessage(); } ?> PHP
  • 22. PHP larger example  Display a random quote of the day:  I don't know half of you half as well as I should like; and I like less than half of you half as well as you deserve. J. R. R. Tolkien (1892 - 1973), The Fellowship of the Ring  I have not failed. I've just found 10,000 ways that won't work. Thomas A. Edison (1847 - 1931), (attributed)  I am among those who think that science has great beauty. A scientist in his laboratory is not only a technician: he is also a child placed before natural phenomena which impress him like a fairy tale. Marie Curie (1867 - 1934)  I love deadlines. I like the whooshing sound they make as they fly by. Douglas Adams  Statistics: The only science that enables different experts using the same figures to draw different conclusions. 22
  • 23. 23 PHP cookies and sessions CS380
  • 24. Cookies  Problem: HTTP is stateless  What is a cookie?  tiny bits of information that a web site could store on the client's machine  they are sent back to the web site each time a new page is requested by this client. CS380 24
  • 25. Bad Cookies?  Urban myth: tracking, violate privacy  Reality:  cookies are relatively harmless  can only store a small amount of information CS380 25
  • 26. Sessions  What is a session?  a combination of a server-side cookie and a client-side cookie,  the client-side cookie contains only a reference to the correct data on the server.  when the user visits the site:  their browser sends the reference code to the server  the server loads the corresponding data. CS380 26
  • 27. Cookies vs Sessions  Cookies can be set to a long lifespan  Cookies work smoothly when you have a cluster of web servers  Sessions are stored on the server, i.e. clients do not have access to the information you store about  Session data does not need to be transmitted with each page; clients just need to send an ID and the data is loaded from the local file.  Sessions can be any size you want because they are held on your server, 27
  • 28. Create a cookie 28 setcookie(name, value, expire, path, domain); PHP <?php setcookie("user", “Harry Poter", time()+3600); ?> <html> ..... CS380 PHP
  • 29. Retrieve a Cookie Value 29 <?php // Print a cookie echo $_COOKIE["user"]; // A way to view all cookies print_r($_COOKIE); ?> CS380 PHP
  • 30. Delete a Cookie 30 <?php // set the expiration date to one hour ago setcookie("user", "", time()+3600); ?> CS380 PHP
  • 31. Start/end a session 31 bool session_start ( void ) bool session_destroy ( void ) PHP  All your session data is stored in the session superglobal array, $_SESSION $_SESSION['var'] = $val; $_SESSION['FirstName'] = "Jim"; PHP CS380

Notas del editor

  1. Server side includes saves a lot of work. This means that you can create a standard header, footer, or menu file for all your web pages. When the header needs to be updated, you can only update the include file, or when you add a new page to your site, you can simply change the menu file (instead of updating the links on all your web pages).
  2. file_put_contents can be called with an optional third parameter appends (adds to the end) rather than replacing previous contents
  3. a convenience, so you can refer to $username instead of $values[0], etc.
  4. a convenience, so you can refer to $username instead of $values[0], etc.
  5. for more complex string splitting, you can use regular expressions
  6. glob can filter by accepting wildcard paths with the * character
  7. glob("foo/bar/*.doc") returns all .doc files in the foo/bar subdirectory glob("food*") returns all files whose names begin with "food" glob("lecture*/slides*.ppt") examines all directories whose names begin with lecture and grabs all files whose names begin with "slides" and end with ".ppt“ basename("foo/bar/baz.txt") returns "baz.txt"
  8. annoyingly, the current directory (".") and parent directory ("..") are included in the array don't need basename with scandir because it returns the file's names only
  9. , whereas sessions are stored on the server, meaning in one of your web servers handles the first request, the other web servers in your cluster will not have the stored information. whereas many web browsers have a limit on how big cookies can be to stop rogue web sites chewing up gigabytes of data with meaningless cookie information. More long term: cookies More flexibility, security: sessions
  10. The setcookie() function must appear BEFORE the <html> tag.
  11. The PHP $_COOKIE variable is used to retrieve a cookie value.
  12. When deleting a cookie you should assure that the expiration date is in the past.
  13. How do you remove data?