v 1.0 oe nik 2013 php+sql 4. file handling basics file-based "database" file-based...
TRANSCRIPT
V 1.0 OE NIK 2013
PHP+SQL4.
File handling basicsFile-based "database"File-based guestbook
1
V 1.0 OE NIK 2013
PHP+SQL4.
File handling basicsFile-based "database"File-based guestbook
2
V 1.0
Basic principles• File paths:
document_root (<a href=‘/path/to/file’>) vsphp disk root ($path=‘/path/to/file’)
• File handle (file variable), file modes• Concurrent file access, race condition bug• Permissions (www-data/IUSR vs ftp-user)• EOL byte(s)?• EOF byte?
OE NIK 2013 3
V 1.0
Functions• file_exists($path), fopen($path, $mode), fclose($fp),
feof($fp)• fwrite($fp, $s)=fputs($fp, $s)=binary-safe write • fgetc($fp), fgets($fp), fread($fp, $len), rewind($fp)• file($path)• fpassthru($fp), readfile($path)• realpath($path), basename($path), unlink($path),
pathinfo($path), filesize($path)
$fname="path/to/file.txt";$cont=file_get_contents($fname);$cont.="hellobello";file_put_contents($fname, $cont);
OE NIK 2013 4
V 1.0
Usage of files (one row contents)<?php$fp=fopen("welcome.txt","wb"); //file handlefwrite($fp, "Hello world\n"); //same: fputs()fclose($fp); //close file
$fp=fopen("welcome.txt","r");$str=fgets($fp); //fread: not the same!echo $str;fclose($fp);?>
OE NIK 2013 5
V 1.0
File modesModes Description
r Read only. Starts at the beginning of the file
r+ Read/Write. Starts at the beginning of the file
w Write only. Opens and clears the contents of file; or creates a new file if it doesn't exist
w+ Read/Write. Opens and clears the contents of file; or creates a new file if it doesn't exist
a Append. Opens and writes to the end of the file or creates a new file if it doesn't exist
a+ Read/Append. Preserves file content by writing to the end of the file
x Write only. Creates a new file. Returns FALSE and an error if file already exists
x+ Read/Write. Creates a new file. Returns FALSE and an error if file already exists
OE NIK 2013 6
V 1.0
Perfect use<?php$handle = @fopen("/tmp/inputfile.txt", "r");if ($handle) { while (($buffer = fgets($handle, 4096)) !== false) { echo $buffer; } if (!feof($handle)) { echo "Error: unexpected fgets() fail\n"; } fclose($handle);}?>
OE NIK 2013 7
V 1.0
WRONG use$file = fopen("welcome.txt", "r");while(!feof($file)) { //Endless infinite loop!!!!!! echo fgets($file)."<br />";}fclose($file);
Alternative solution:$file = fopen("welcome.txt", "r") or die("Unable to open file!");
OE NIK 2013 8
V 1.0
Example: DOWNLOAD.PHP
OE NIK 2013 9
V 1.0 OE NIK 2013
PHP+SQL4.
File handling basicsFile-based "database"File-based guestbook
10
V 1.0
File format• The entities are typically in the separate rows of the file,
the data fields are usually separated by some special character ( \t ; , | )
• The only problem is that if a data field contains \n or \t we forbid these (we could substitute with special letters (weak solution), or we could properly use some special escaping (strong solution, but difficult) )
OE NIK 2013 11
V 1.0
File I/O• $path=‘database.txt’;
• $database=array();$rows_array=file($path, FILE_IGNORE_NEW_LINES);foreach ($rows_array as $key=>$row) {
$database[]=explode("\t", $row);} //we could use row-by-row operations
• $cont="";foreach ($database as $one_record) {
$cont.=implode("\t", $one_record)."\n";}file_put_contents($path, $cont); // we could use … …
OE NIK 2013 12
V 1.0
HOMEWORK (FOR POINTS!!!)
• Find out a topic, we need ONE entity with at least FIVE data fields that we want to store (e.g. topic: DVD rental; entity: movies; data fields: title, year, director, price, number_of_copies)
• Create a text file that stores 10 entities• Create a PHP script that reads the text file and
displays the entities in an HTML table• Find out and program 5 simple questions where you
can use simple programming theorems (e.g. What is the most expensive movie, how much movies do we have from 2001), the questions and answers must be displayed below the main table
13OE NIK 2013
V 1.0
HOMEWORK (FOR POINTS!!!)
• Using the original dataset as a source, randomly generate 20 other entities (e.g. 20 random movies) into another array, and display them below the simple questions & answers
• Find out and program 3 complex questions that require BOTH arrays (e.g. Generate the union/intersection, or use come complex programming theorems/tasks !)
• Create a PDF documentation describing the task you chose and the 8 questions you found out. Do not describe the algorithms step-by-step, but write down which programming theorems did you use in the different parts of the code
14OE NIK 2013
V 1.0
HOMEWORK (FOR POINTS!!!)
• Deadline: 17th of March, midnight!• Email to [email protected] , the subject
must contain the letters [PHP] , the email text must contain your name and your neptun code
• The email must contain a ZIP/ARJ/RAR/GZ/7Z/XZ file (fullname_neptuncode.zip) that contains:• The full PHP source
(HTML+CSS can be used, but not required)• The example TXT file with the 10 entities• The full documentation in PDF form (use some
nice formatting, header, footer, etc – must look pretty! )
15OE NIK 2013
V 1.0 OE NIK 2013
PHP+SQL4.
File handling basicsFile-based "database"File-based guestbook
16
V 1.0
Guestbook structure• Guestbook form gb_form.html• Guestbook entries gb_entries.txt• Guestbook program guestbook.php
• From now on, we ALWAYS open the PHP file, the other files are managed by the PHP script
• After data modification/insertion, auto-redirect:header("location: guestbook.php");die();
OE NIK 2013 17
V 1.0
File format• Data fields: name, email, multi-line text
• To define data fields: we use prefix characters
#name1@email1entrytext1#name2@email2entrytext2
OE NIK 2013 18
V 1.0
Algorithm
OE NIK 2013
$_GET['action']ADD
ANYTHING ELSE
ENTRIES + LINK(???)
HTML(file_get_contents)
FORM
POST data? YES
NO
ERROR(echo)
SAVE(???)
REDIRECT(header + exit)
19
V 1.0
Sub-parts of the exercise
1. gb_form.html: an html form with two single-line textbox (name, email), one multiline textbox (textarea: entry text) and one submit button
2. guestbook.php: according to the algorithm on the previous slide
3. Write the difficult parts:a) Display entriesb) Save entries
OE NIK 2013 20
V 1.0
Display entriesOpen fileIf success, then LOOP, while (not EOF)
Read line, determine first characterIf '#', then start new entry, echo nameIf '@', then echo email addressOtherwise, echo line without modification
LOOP endsDisplay html link towards the "New entry" action
(guestbook.php?action=FORM)
• Instead of line-by-line operations, we could use file(), but we usually need FILE_IGNORE_NEW_LINES
OE NIK 2013 21
V 1.0
Save entryCheck Name, Email, Entry in $_POST-banImport Name, Email, Entry from $_POSTOpen file for appendAppend "#" + name + newlineAppend "@" + email + newlineAppend entry + newlineClose file
??? What if the entry's first character is # or @ ?????? XSS: htmlspecialchars/strip_tags ???
OE NIK 2013 22
V 1.0 OE NIK 2013
LET'S CODE!
23
V 1.0 OE NIK 2013 24
OE NIK 2013 25