320 likes | 432 Views
PHP Working with Files: Sample Applications. Examples. Web counter can counts the no. of time the page has been visited . Simple discussion board . Simple blog Simple file gallery. Algorithm: Break problem into steps of coding.
E N D
Examples • Web counter can counts the no. of time the page has been visited. • Simple discussion board. • Simple blog • Simple file gallery
Algorithm: Break problem into steps of coding • Before starts writing, we should break the problem (web counter) into steps: • When visited, load the global counter first • Increment that counter, show it • Store the counter • That’s it! • But how to store the counter?
How to store and access files? • We must first open a file • Assume we have a file called counter.txt in the same directory • We can use fopen() to open a file • $fp=fopen(“counter.txt”, “r+”); • A filepointer ($fp) is return as the beginning of the file.
How to get the value? • We can use fgets() to get a line from a file • $string1=fgets($fp, 4096); • 4096 is a length (of course it won’t be so long!!) • But we’ve get a number in String type, how to convert to Integer?
String – Integer Conversion • Use intval() • It converts any time of variable with integer value to Integer type; • E.g. $stringnum=“12345”; //String! echo intval($stringnum)+1; • The output will be 12346!!
OK, how to store it? • We should remove all the content first rewind($fp); //rewind the file pointer ftruncate($fp,0); //set size to 0 • Then store the incremented value to it fwrite($fp,strval($num)); //strval() converts to integer • Then close the file stream fclose($fp);
counter.php <? $fp=fopen("counter.txt", "r+"); $num=intval(fgets($fp, 4096)); echo ++$num; rewind($fp); ftruncate($fp,0); fwrite($fp,strval($num)); fclose($fp); ?> http://oj311.aisites.com/counter.php
Evaluation • Use a file to store the counter • The set of file operations functions: • fopen(), fgets(), rewind(), ftruncate(), fwrite(), fclose() • The next application – Discussion board also requires file operation functions
Discussion Board • It’s a simple board – no thread • Just let user to post message by message • You can view the demo board @ http://oj311.aisites.com/board.php
How to write? • It’s a little bit more complicated than the counter • Broken into several parts: • A form to enter data • Load the posts stored and display them • Once received post action, store the new post
The Form • Very simple, just “name”, “email” and “message” <form action="<?echo $PHP_SELF;?>" method="post"> Name: <input type="text" name="name"><br> Email: <input type="text" name="email"><br> Message:<br> <textarea name="message" COLS="60" ROWS="10"></textarea><br> <input type="submit" name="submit" value="Post!"> <input type="reset"> </form>
So How to load the post? • Let us make a specification of storage file first • In the file, 4 columns make a record of a post • 1stcolumn: Name • 2ndcolumn: Email • 3rdcolumn: Message • 4thcolumn: Date & Time of post
Load the posts • Open the file: $fp=fopen(“message.txt”, “r+”); • We use fgets() to read the line one by one • When to end? Use feof($fp) to test. while(!feof($fp)){ $name=fgets($fp, 4096); $email=fgets($fp, 4096); $message=fgets($fp, 4096); $datetime=fgets($fp, 4096); if (feof($fp)) break; //Then print out the data… }
How to store? • Loaded the content • To store, we only need to open the file, store name, email, message, datetime line by line • But a potential problem - the message may have several lines! • How to solve?
Convert to <br/> • Actually we can convert newline character to <br/> and then store it • We can use nl2br() to do it • It add a “<br>” before each newline characters • But how to remove the newline char?
Remove newline character • We can replace the newline character by a whitespace • $message=str_replace(chr(10),” “, “$message”); • chr(10) is newline for UNIX/LINUX • (optional)We also need to do chr(13) as it’s newline for Windows environment • $message=str_replace(chr(13),” “, “$message”); • Afterwards, the message will be stored as a single line only!
Solved? • Not yet, PHP will automatically add escaped character -- \ • E.g., I’m -> I\’m • It’s redundant, how to remove? • Use stripslashes() • $message=stripslashes($message); • Also, how to get the date and time? • Use date() • $datetime=date(“Y-m-d H:i:s”);
Store data entered by user • Open the file first • $fp=fopen(“message.txt”,”a”); • Then write name, email, message, datetime with a newline character in between: fwrite($fp,$name); fwrite($fp,chr(10)); fwrite($fp,$email); fwrite($fp,chr(10)); …
Reload to see new data • You’ve saved all the data • Then you should divert the user back to the interface part • Use JavaScript to bring it back <script language=“Javascript”> location.href=“<?echo $PHP_SELF;?>”; </script>
Complete code for board application • Full source code @ http://oj311.aisites.com/board.phps (do ‘file->save’ as and save the file as ‘board.php’ make sure type is set to all files.) • Remember to create/save message.txt • (Optional) chmod644“board.php” • In the same directory, make a file called “message.txt” with permission 666
Blog • Write a blog • Simple form to collect posts • Save posts to file • Page to display header, navigation and footer files along with posts saved in text file • Approach • Use files or use a database. Using a database would be better but you could use files. • Outline using files • Outline using a database
Blog – File scenario • Form to collect entry information • Entry information stored in file – each entry saved as a line in the text file. • Misc • Add on edit functionality • Could add more styling information • Check to make sure any email address entered is in a valid email address format • Limit number of posts shown out of total posts • Add in a link to other page(s) that would show the next set posts out of total posts.
Blog – File scenario • Test and download code: • View :: http://oj311.aisites.com/blog/blog.php • Source :: http://oj311.aisites.com/blog/blog_source.zip
Blog • Write a blog • Post new articles • Edit articles • Delete articles • Approach • MySQL – table for blog entries • Password protect admin functions • Use session to remember visitor is an admin • PHP to display HTML and process additions/deletions/edits.
Blog – Database scenario • Database • Create a table with columns • id (int not null auto_increment), title (tinytext), body (text) • Page to list blog entries: mysql_query(“SELECT * FROM blogs”); While ($row = mysql_fetch_array()) { echo “<h2>{$row[‘title’]</h2>”; echo “<p>{$row[‘body’]}</p>”; }
Blog – Database scenario • Page to add new blog entries • Create page with form and <textarea> field for entering blog text. Submits to a PHP file. • PHP file: $title = $_POST[‘title’]; $body = $_POST[‘body’]; mysql_query(“INSERT INTO blogs (title, body) VALUES (‘{$title}’, ‘{$body}’)”);
Blog – Database scenario • Editing entries • Link above each blog post called edit, that passes the blog ID by get, e.g. link to: • edit.php?id=3 • Edit.php generates a form and fills in the <textarea> with the current body text. • Hidden field to pass blog entry id. • Submits to another PHP file which performs an SQL UPDATE query like the INSERT on the last slide.
Blog – Database scenario • Deleting entries • Link above each entry, which passes blog entry ID via GET: e.g. link to: • delete.php?id=3 • Perform SQL DELETE query to remove row, e.g. • DELETE FROM blogs WHERE id = XXX • Misc • Could add datetime field, and set current time and date on posting/updating.
Image Gallery • PHP program that displays a photo gallery of images found in a directory. • Misc • Program should make sure the files in the directory it displays, are image files. • http://oj311.aisites.com/file_gallery.php • http://oj311.aisites.com/file_gallery.phps (do ‘file->save’ as and save the file as ‘file_gallery.php’ make sure type is set to all files.)
Resources • Creating and deleting directories • Working with directories • Creating text files with PHP • Reading data from text files with PHP • Editing text files with PHP • Deleting a file • Using fgetscsv function