Download presentation
Presentation is loading. Please wait.
Published byAmi Barrett Modified over 6 years ago
1
PHP+SQL 3. Files, directories, images TWIG File-based "database"
File-based guestbook Exercises OE NIK 2013
2
PHP+SQL 3. Files, directories, images TWIG File-based "database"
File-based guestbook Exercises OE NIK 2013
3
Basic principles File paths: document_root (<a href=‘/path/to/file’>) vs php disk root ($path=‘/path/to/file’) In symfony, the document_root is the WEB directory, all PHP file access is relative to that directory 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
4
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
5
Usage of files (one row contents)
<?php $fp=fopen("welcome.txt","wb"); //file handle fwrite($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
6
File modes Modes 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
7
Perfect use <?php $handle "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
8
WRONG use $file = fopen("welcome.txt", "r"); while(!feof($file)) { //infinite loop!!!!!! echo fgets($file)."<br />"; } fclose($file); Alternative solution: $file = fopen("welcome.txt", "r") or die("Unable to open file!"); OE NIK 2013
9
Directory Functions getcwd() , chdir()
opendir(), readdir(), closedir(), rewinddir() scandir(), glob() realpath() OE NIK 2013
10
GD Functions image* , http://php.net/manual/en/book.image.php
$im=imagecreatefromjpeg($path) //png, gif, wbmp imagesy($im), imagesx($im) $index=imagecolorat($im, X, Y); $rgb=imagecolorsforindex($im, $index); $index=imagecolorallocate($im, R, G, B); imagesetpixel($im, X, Y, $index); OE NIK 2013
11
GD Example – pagetitle.php
OE NIK 2013
12
GD Example – getChannel.php
OE NIK 2013
13
PHP+SQL 3. Files, directories, images TWIG File-based "database"
File-based guestbook Exercises OE NIK 2013
14
TWIG Templating engine (Blade, smarty, native php)
{{ … }} = “says something” {{ }} = prints out the variable passed to the templating engine {{ user. }} = prints out the member of the user variable passed to the templating engine (intelligent member search!) {% … %} = “does something” {% for … %}, {% if … %}, {% set … %} {# … #} = “comments something” OE NIK 2013
15
Variables Global Local
app.user [logged in user’s data] app.request [request info] app.session [session data] app.environment [environment info] app.debug [true/false] Local When displaying from the controller, an array of variables can be passed from the controller to the view Variables can be arrays/object/scalars, member access is done with the . Operator (intelligent search) Everything is converted to strings! OE NIK 2013
16
Active elements Filters can be applied to template variables, can be chained if necessary: {{ someDateTime|date(‘Y.m.d. H:i:s’) }} {{ |lower }} {{ |default(‘nothing’)|upper }} Loops, functions: OE NIK 2013
17
Links / references <a href=‘{{ path(‘someRouteName’) }}’>LINK</a> <a href='{{ path('article_show', {'id': article.id }) }}'> {{ url(‘someRouteName’) }} = absolute url <img src=“{{ asset('images/logo.png') }}" /> OE NIK 2013
18
Fast, secure and “the right way”
Fast: effective caching (PHP classes are generated an then cached in var/cache/*/twig) Secure: automatic escaping of dangerous content (by default. Can be turned off with “autoescape off” or using {{ content|raw }} “The right way”: Complete separation of business logic and display MVC Instead of using PHP, we use an engine specifically built for templating cannot “hack” business logic into views! OE NIK 2013
19
Extensible {# base.twig #} {% block body} {% endblock}
{# sub.twig #} {% extends ‘base.twig’ %} {# app/Resources/views/* #} {% block body %} Hello, world! {% endblock %} {{ parent() }} append block from parent twig {{ include() }} includes another template OE NIK 2013
20
Extensible OE NIK 2013
21
Three-level inheritance
app/Resources/views/base.html.twig OE NIK 2013
22
PHP+SQL 3. Files, directories, images TWIG File-based "database"
File-based guestbook Exercises OE NIK 2013
23
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
24
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
25
HOMEWORK (NOT THIS SEMESTER)
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 OE NIK 2013
26
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, only list the questions and an example output! OE NIK 2013
27
HOMEWORK (FOR POINTS!!!) Deadline: 21st of March, 23:59!
**a link** to the filename and the text must contain your name and your neptun code The file must be a ZIP/ARJ/RAR/GZ/7Z/XZ file (fullname_neptuncode.zip) that contains: The full Symfony source The example TXT file with the 10 entities The full documentation in PDF form (use some nice formatting, header, footer, etc – must look pretty! ) OE NIK 2013
28
PHP+SQL 3. Files, directories, images TWIG File-based "database"
File-based guestbook Exercises OE NIK 2013
29
Guestbook structure Actions: guestbook index, add form, file modification Views: list of entries, data form Data: ../data/gb.txt After data modification/insertion, auto-redirect! Native PHP: header("location: some.php"); die(); Symfony: return $this->redirectToRoute('routeName'); OE NIK 2013
30
File format Data fields: name, email, multi-line text
To define data fields: we use prefix characters entry text 1 entry text 2 OE NIK 2013
31
Algorithm /gb/add /gb Entries + Link YES /gb/form Display form Save NO
ROUTING /gb/add /gb POST data? Entries + Link YES /gb/form Display form Save NO Error Redirect + flashbag OE NIK 2013
32
Sub-parts of the exercise
form.twig: an html form with two single-line textbox (name, ), one multiline textbox (textarea: entry text) and one submit button List.twig: an html list of guestbook entries Controller: according to the algorithm on the previous slide Write the difficult parts: listAction addAction OE NIK 2013
33
ListAction Open file If success, then LOOP, while (not EOF)
Read line, determine first character If '#', then start new entry, set name If then set address Otherwise, set content line without modification LOOP ends Instead of line-by-line operations, we could use file(), but we usually need FILE_IGNORE_NEW_LINES, and look out for memory limits (this time: we don’t care)! OE NIK 2013
34
Save entry Check Name, , Entry in $_POST Open file for append Append "#" + name + newline Append + + newline Append entry + newline Close file Redirect! ??? What if the entry's first character is # ??? ??? XSS: htmlspecialchars/strip_tags ??? OE NIK 2013
35
LET'S CODE! OE NIK 2013
36
PHP+SQL 3. Files, directories, images TWIG File-based "database"
File-based guestbook Exercises OE NIK 2013
37
Recipe book Create an application to manage a recipe book
The script should have actions to manage the ingredients.txt file: the file contains one ingredient per line; create actions to list them or add a new ingredient The script should have actions to manage the recipes.txt file: the file should have the entries in the format of: RECIPE_NAME|ingredient1,ingredient2,ingredient3 There should be an action to list all recipes (and the ingredients of the recipes) in a nice-looking table There should be an action to add a new recipe: first ask the recipe name and the number of ingredients; then input the ingredients (using selects), then save into the file OE NIK 2013
38
OE NIK 2013
39
OE NIK 2013
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.