Server-side Web Development (I3302) Semester: 1 Academic Year: 2017/2018 Credits: 5 (50 hours) Dr Antoun Yaacoub

Similar documents
Requirements Management tool makes traceability easy. See how!

FILE TYPES 1/2/12 CHAPTER 5 WORKING WITH FILES AND DIRECTORIES OBJECTIVES. Binary. Text PHP PROGRAMMING WITH MYSQL, 2ND EDITION

Lecture 6: More Arrays & HTML Forms. CS 383 Web Development II Monday, February 12, 2018

File handling is an important part of any web application. You often need to open and process a file for different tasks.

File I/O. Arash Rafiey. November 7, 2017

CLIL-4-PHP-4. Files - part 2. There are three functions that allow you to work more intimately with the contents

PHP with data handling

Introduction to file management

Files and Streams Opening and Closing a File Reading/Writing Text Reading/Writing Raw Data Random Access Files. C File Processing CS 2060

COMP284 Scripting Languages Lecture 11: PHP (Part 3) Handouts

PHP 5 if...else...elseif Statements

Course Topics. The Three-Tier Architecture. Example 1: Airline reservations. IT360: Applied Database Systems. Introduction to PHP

Princeton University COS 333: Advanced Programming Techniques A Subset of PHP

M.CS201 Programming language

Course Topics. IT360: Applied Database Systems. Introduction to PHP

Accessing Files in C. Professor Hugh C. Lauer CS-2303, System Programming Concepts

CLIL-3-PHP-3. Files - part 1. Once you master the art of working with files, a wider world of PHP web

A340 Laboratory Session #12

CS 418 Web Programming Spring 2013 IMAGES SCOTT G. AINSWORTH.

In a Linux/Unix operating system, it is expressed as:

Database Systems Fundamentals

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #47. File Handling

Darshan Institute of Engineering & Technology for Diploma Studies Unit 6

Standard File Pointers

Subject Name: Advanced Web Programming Subject Code: (13MCA43) 1. what is PHP? Discuss different control statements

Copyright 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley. Chapter 11 Introduction to PHP

Computer Programming Unit v

CITS1231 Web Technologies. PHP s, Cookies and Session Control

Mode Meaning r Opens the file for reading. If the file doesn't exist, fopen() returns NULL.

PHP INTERVIEW QUESTION-ANSWERS

Unit 6 Files. putchar(ch); ch = getc (fp); //Reads single character from file and advances position to next character

EM108 Software Development for Engineers

USQ/CSC2406 Web Publishing

C How to Program, 6/e by Pearson Education, Inc. All Rights Reserved.

PROGRAMMAZIONE I A.A. 2017/2018

fopen() fclose() fgetc() fputc() fread() fwrite()

Lecture 8. Dr M Kasim A Jalil. Faculty of Mechanical Engineering UTM (source: Deitel Associates & Pearson)

CSE 154 LECTURE 19: FORMS AND UPLOADING FILES

CSI 402 Systems Programming LECTURE 4 FILES AND FILE OPERATIONS

PHP Hypertext Preprocessor

CERTIFICATE IN WEB PROGRAMMING

NETB 329 Lecture 13 Python CGI Programming

Chapter 7 PHP Files & MySQL Databases

PHP Dynamic Web Pages, Without Knowing Beans

Introduction. Server-side Techniques. Introduction. 2 modes in the PHP processor:

Outline of Lecture 5. Course Content. Objectives of Lecture 6 CGI and HTML Forms

"Charting the Course... Intermediate PHP & MySQL Course Summary

Chapter 12. Files (reference: Deitel s chap 11) chap8

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING B.E SECOND SEMESTER CS 6202 PROGRAMMING AND DATA STRUCTURES I TWO MARKS UNIT I- 2 MARKS

Zend Zend Certified PHP Developer. Download Full Version :

13Holzner_index.qxd 3/23/05 1:51 PM Page 331. Index

Grapevine web hosting user manual. 12 August 2005

Content. Input Output Devices File access Function of File I/O Redirection Command-line arguments

The PHP language. Teaching you everything about PHP? Not exactly Goal: teach you how to interact with a database via web

Physical Files and Logical Files. Opening Files. Chap 2. Fundamental File Processing Operations. File Structures. Physical file.

UNIT-VI CREATING AND USING FORMS

BIL 104E Introduction to Scientific and Engineering Computing. Lecture 12

Arithmetic and Assignment Operators

ASPFileSaver - File Upload Component

Lecture6 File Processing

Ch 11. C File Processing (review)

UNIT IV-2. The I/O library functions can be classified into two broad categories:

C Programming Language

BEGINNER PHP Table of Contents

File System User API

B. V. Patel Institute of BMC & IT 2014

COMP1917: 15 File IO

CS Homework 6. Deadline. Purpose. How to submit. Important notes. Problem 1. Spring CS Homework 6 p. 1

John Valance JValance Consulting

Introduction to Computer and Program Design. Lesson 6. File I/O. James C.C. Cheng Department of Computer Science National Chiao Tung University

CS246 Spring14 Programming Paradigm Files, Pipes and Redirection

Standard C Library Functions

HTML Forms. By Jaroslav Mohapl

Organization of a file

COMS 469: Interactive Media II

CSI 402 Lecture 2 Working with Files (Text and Binary)

Input / Output Functions

CMPE-013/L. File I/O. File Processing. Gabriel Hugh Elkaim Winter File Processing. Files and Streams. Outline.

HTML forms and the dynamic web

C mini reference. 5 Binary numbers 12

Chapter 11 File Processing

CSCI 171 Chapter Outlines

Chapter 7:- PHP. Compiled By:- Sanjay Patel Assistant Professor, SVBIT.

25.2 Opening and Closing a File

System Software Experiment 1 Lecture 7

Databases HTML and PHP I. (GF Royle, N Spadaccini ) HTML/PHP I 1 / 28

CSE 154 LECTURE 9: SUBMITTING DATA (POST)

Lecture 9 Server Browser Interactions

Computer programming

Outline. Introducing Form. Introducing Forms 2/21/2013 INTRODUCTION TO WEB DEVELOPMENT AND HTML

C Basics And Concepts Input And Output

CSC209H Lecture 3. Dan Zingaro. January 21, 2015

What is PHP? [1] Figure 1 [1]

Engineering program development 7. Edited by Péter Vass

Lecture 10: Working with Files. CS 383 Web Development II Monday, March 12, 2018

Programming for the Web with PHP

Networking and Internet

Creating HTML files using Notepad

Fundamentals of Programming & Procedural Programming

Homework #1 From C to Binary

Transcription:

Lebanese University Faculty of Science Computer Science BS Degree Server-side Web Development (I3302) Semester: 1 Academic Year: 2017/2018 Credits: 5 (50 hours) Dr Antoun Yaacoub

2 PHP forms

This lecture covers Getting data from forms html form + php action on the same page $_SERVER['PHP_SELF'] maintain form status page redirection - the header() function Upload files Files creation and deletion opening and closing reading print_r function 3

This lecture covers Getting data from forms html form + php action on the same page $_SERVER['PHP_SELF'] maintain form status page redirection - the header() function Upload files Files creation and deletion opening and closing reading print_r function 4

Getting data from forms what happens when the user clicks the submit button? an HTTP request is sent to the server to the script named by the action attribute of the <form> request contains all associations between field names and their values in the body of the HTTP request if the POST method is used in the URL if it is the GET method 5

Typical form 6

Unique values are from the form fields in which the user can only enter a value, such as a text, or can only make one choice (radio button, select list) since PHP 4.1 values superglobal associative arrays : $_POST or $_GET array keys = names associated with fields by the name attribute 7

Getting values to simplify get value in scalar variable, then reuse $name= $_POST["name"]; $level=$_post["level"]; W3C (World Wide Web Consortium) consider removing the get value for the method attribute of forms in HTML or xhtml 8

Multiple Values some fields allow the entry of several values under the same name group of checkboxes with the same name attribute (check one or more) selection list with multiple attribute = "multiple" give the same name to different text entry elements, less interest table that is retrieved on the server side must follow the name of the component of brackets, as to create a variable of type array example Blue :<input type="checkbox" name="choice[]" value="blue" /> White :<input type="checkbox" name="choice[]" value="white" /> Getting the values $_POST["choice"][0] contains the value "blue" $_POST["choice"][1] contains the value "white" 9

This lecture covers Getting data from forms html form + php action on the same page $_SERVER['PHP_SELF'] maintain form status page redirection - the header() function Upload files Files creation and deletion opening and closing reading print_r function 10

The combination of the HTML form and the PHP action on the same page <form action="<?php print $_SERVER['PHP_SELF']?>" method="post"> $_SERVER['PHP_SELF'] the action of this script is $_SERVER ['PHP_SELF'] this variable is equivalent to the name of the current script the action indicates that the script is reloading itself 11

Example: Guessing game 12

Example: Guessing game 13

Example: Guessing game <?php?> <html> <head> </head> <body> </body> </html> $num_to_guess = 42; $message = ""; if (!isset($_post[guess])) { $message = "Welcome to the guessing machine!"; } elseif ($_POST[guess] > $num_to_guess) { $message = "$_POST[guess] is too big! Try a smaller number"; } elseif ($_POST[guess] < $num_to_guess) { $message = "$_POST[guess] is too small! Try a larger number"; } else { // must be equivalent $message = "Well done!"; } <title>a PHP number guessing script</title> <h1><?php print $message?></h1> <form action="<?php print $_SERVER[PHP_SELF]?>" method="post"> Type your guess here: <input type="text" name="guess"> </form> 14

15

Using Hidden Fields to Save State we want to count the number of attempts we use a variable $num_tries which is initialized for a first visit to zero this variable is passed in a field hidden in the form, to increment it after each test we want to keep the guessed value in the text field after reloading the form we give a default value to the text field "guess" it is the value of this same field already entered $_POST['guess'] 16

Example: Guessing game <?php $num_to_guess = 42; $num_tries = (isset($_post[num_tries]))? $_POST[num_tries] + 1 : 0; $message = ""; if (!isset($_post[guess])) { $message = "Welcome to the guessing machine!"; } elseif ($_POST[guess] > $num_to_guess) { $message = "$_POST[guess] is too big! Try a smaller number"; } elseif ($_POST[guess] < $num_to_guess) { $message = "$_POST[guess] is too small! Try a larger number"; } else { // must be equivalent $message = "Well done!"; } $guess = $_POST[guess];?> <html> <head><title>saving state with a hidden field</title> </head> <body> <h1><?php print $message?></h1> Guess number: <?php print $num_tries?> <form action="<?php print $_SERVER[PHP_SELF]?>" method="post"> Type your guess here: <input type="text" name="guess" value="<?php print $guess?>"> <input type="hidden" name="num_tries" value="<?php print $num_tries?>"> </form> </body> </html> 17

This lecture covers Getting data from forms html form + php action on the same page $_SERVER['PHP_SELF'] maintain form status page redirection - the header() function Upload files Files creation and deletion opening and closing reading print_r function 18

Redirecting the User previous script major disadvantage form is rewritten even if the user correctly guesses HTML is hard-coded difficult to avoid writing the entire page solution : redirect the user to another page congratulations 19

header() function when a server script communicates with a client, it must first send headers containing information about the upcoming document you can choose to send other header lines with the PHP function: header() to call the header() function, ensure that no line has been sent to the browser any display in document, even a line break or outside space to your script tags causes the headers to be sent to the client If you intend to use the header() function in a script ensure that nothing precedes the PHP code that contains the function call check used libraries 20

Using header() to Send Raw Headers assuming a page "congrats.html" edit the script to redirect the user if he guesses correctly 21

Example: Guessing game <?php?> $num_to_guess = 42; $num_tries = (isset($_post[num_tries]))? $_POST[num_tries] + 1 : 0; $message = ""; if (!isset($_post[guess])) { $message = "Welcome to the guessing machine!"; } elseif ($_POST[guess] > $num_to_guess) { $message = "$_POST[guess] is too big! Try a smaller number"; } elseif ($_POST[guess] < $num_to_guess) { $message = "$_POST[guess] is too small! Try a larger number"; } else { // must be equivalent header("location: congrats.html"); exit; } $guess = $_POST[guess]; 22

This lecture covers Getting data from forms html form + php action on the same page $_SERVER['PHP_SELF'] maintain form status page redirection - the header() function Upload files Files creation and deletion opening and closing reading print_r function 23

Upload files 24

Upload files <html> <head><title>a simple file upload form</title></head> <body> <form action="upload.php" enctype="multipart/form-data" method="post"> </form> </body> </html> <input type="hidden" name="max_file_size" value="51200"> File to Upload: <input type="file" name="fileupload"><br><br> <input type="submit" value="upload!"> 25

Upload form form attribute method: compulsory post attribute ENCTYPE : ENCTYPE="multipart/form-data" hidden field inserted before file field must be named MAX_FILE_SIZE maximum size in bytes accepted this size can not override the maximum upload_max_filesize size in the field in your default php.ini file of 2MB field to upload the file element INPUT of type="file" name="yourchoice" 26

PHP code for file Information about the uploaded file becomes available to you in the $_FILES superglobal, which is indexed by the name of the upload field (or fields) in the form. The corresponding value for each of these keys is an associative array. These fields are described below, using fileupload as the name of the form field used for the upload. Element Contains Example $_FILES['fileupload']['name'] Original name of uploaded file test.gif $_FILES['fileupload']['tmp_name'] Path to temporary file /tmp/phprdfzvn $_FILES['fileupload']['size'] Size (in bytes) of uploaded file 6835 $_FILES['fileupload']['type'] MIME type of uploaded file (where given by client) image/gif 27

A Simple File Upload Script 28

A Simple File Upload Script <html> <head><title>a file upload script</title></head> <body> <h1>file Upload Results</h1> <?php $file_dir = "D:\wamp\www\ch3"; copy"); </body> </html>?> foreach($_files as $file_name => $file_array) { print "path: ".$file_array['tmp_name']."<br>\n"; print "name: ".$file_array['name']."<br>\n"; print "type: ".$file_array['type']."<br>\n"; print "size: ".$file_array['size']."<br>\n"; } if (is_uploaded_file($file_array['tmp_name'])) { move_uploaded_file($file_array['tmp_name'], "$file_dir/$file_array[name]") or die ("Couldn't } print "file was moved!<br><br>"; 29

30

A File Upload Script <!DOCTYPE html> <html> <head><title>uploading...</title></head> <body> <h1>uploading File...</h1> <?php if ($_FILES['fileupload']['error'] > 0) { echo 'Problem: '; switch ($_FILES['fileupload']['error']) { case 1: echo 'File exceeded upload_max_filesize.'; break; case 2: echo 'File exceeded max_file_size.'; break; case 3: echo 'File only partially uploaded.'; break; case 4: echo 'No file uploaded.'; break; case 6: echo 'Cannot upload file: No temp directory specified.'; break; case 7: echo 'Upload failed: Cannot write to disk.'; break; case 8: echo 'A PHP extension blocked the file upload.'; break; } exit; } 31

A File Upload Script // Does the file have the right MIME type? if ($_FILES['fileupload']['type']!= 'image/png') { echo 'Problem: file is not a PNG image.'; exit; } // put the file where we'd like it $uploaded_file = "D:\\wamp\\www\\ch3\\uploads\\".$_FILES['fileupload']['name']; if (is_uploaded_file($_files['fileupload']['tmp_name'])) { if (!move_uploaded_file($_files['fileupload']['tmp_name'], $uploaded_file)) { echo 'Problem: Could not move file to destination directory.'; exit; } } else { echo 'Problem: Possible file upload attack. Filename: '; echo $_FILES['fileupload']['name']; exit; } echo 'File uploaded successfully.'; 32

A File Upload Script // show what was uploaded echo '<p>you uploaded the following image:<br/>'; echo '<img src="uploads/'.$_files['fileupload']['name'].'"/>';?> </body> </html> 33

Browse Directories 34

Browse Directories <html> <head><title>browse Directories</title></head> <body> <h1>browsing</h1> <?php $current_dir = "D:\\wamp\\www\\ch3"; $dir = opendir($current_dir); echo '<p>upload directory is '.$current_dir.'</p>'; echo '<p>directory Listing:</p><ul>'; while(false!== ($file = readdir($dir))) { //strip out the two entries of. and.. if($file!= "." && $file!= "..") { echo '<li>'.$file.'</li>'; } } echo '</ul>'; closedir($dir);?> 35

scandir() function to sort the filenames in alphabetical order The file names in the example above are not sorted in a particular order, so if you need a sorted list, you can use a function called scandir(). This function can be used to store file names in an array and sort them alphabetically, either ascending or descending, as in the following list. 36

37

scandir() function <html> <head><title>browse Directories</title></head> <body> <h1>browsing</h1> <?php $dir = "D:\\wamp\\www\\ch3"; $files1 = scandir($dir); $files2 = scandir($dir, 1); echo '<p>upload directory is '.$dir.'</p>'; echo '<p>directory Listing in alphabetical order, ascending:</p><ul>'; foreach($files1 as $file) { if ($file!= "." && $file!= "..") { echo '<li>'.$file.'</li>'; } } echo '</ul>'; 38

scandir() function echo '<p>upload directory is '.$dir.'</p>'; echo '<p>directory Listing in alphabetical, descending:</p><ul>'; foreach($files2 as $file) { if ($file!= "." && $file!= "..") { echo '<li>'.$file.'</li>'; } } echo '</ul>';?> </body> </html> 39

This lecture covers Getting data from forms html form + php action on the same page $_SERVER['PHP_SELF'] maintain form status page redirection - the header() function Upload files Files creation and deletion opening and closing reading print_r function 40

Open/Create and delete files function touch () argument: string representing url of the file if file did not already exist create empty file otherwise the old content is not changed but update date modified field example touch("myfile.txt"); unlink() function delete a file unlink("myfile.txt"); 41

Open/Create and delete files fopen() function 2 arguments: file name and opening mode mode: read (r), write (w), append (a) fopen() returns file resource or false if failed to open the file 42

Open/Create and delete files example $fp = fopen("test.txt", 'r'); better if ($fp = fopen("test.txt", "w")) { } ($fp = fopen("test.txt", "w")) or die (", sorry"); fclose() function closes the opened file with fopen() fclose($fp); 43

Read files line by line fgets() function ex: $line = fgets($fp, 1024); lreads 1024 or to the end of the line \ n feof() function return true if end of file ex: feof($fp); 44

Read files line by line <html> <head><title>opening and reading a file line by line</title></head> <body> <?php $filename = "test.txt"; $fp = fopen($filename, "r") or die("couldn't open $filename"); while (!feof($fp)) { $line = fgets($fp, 1024); print "$line<br>"; }?> </body> </html> 45

Reading Arbitrary Amounts of Data from a File with fread() <html> <head><title>reading a file with fread()</title></head> <body> <?php $filename = "test.txt"; $fp = fopen($filename, "r") or die("couldn't open $filename"); while (!feof($fp)) { $chunk = fread($fp, 16); print "$chunk<br>"; }?> </body> </html> 46

Moving Around a File with fgetc() <html> <head><title>moving Around a File with fseek()</title></head> <body> <?php $filename = "test.txt"; $fp = fopen($filename, "r") or die("couldn't open $filename"); while (!feof($fp)) { $char = fgetc($fp); print "$char<br>"; }?> </body> </html> 47

Writing and Appending to a File <html> <head><title>writing and appending to a file</title></head> <body> <?php $filename = "test.txt"; print "Writing to $filename<br>"; $fp = fopen($filename, "w") or die("couldn't open $filename"); fwrite($fp, "Hello world\n"); fclose($fp);?> </body> </html> print "Appending to $filename<br>"; $fp = fopen($filename, "a") or die("couldn't open $filename"); fputs($fp, "And another thing\n"); fclose($fp); 48

readfile() Function The readfile() function reads a file and writes it to the output buffer. Assume we have a text file called test.txt", stored on the server, that looks like this: The PHP code to read the file and write it to the output buffer is as follows (the readfile() function returns the number of bytes read on success): 49

readfile() Function Example <?php?> echo readfile("test.txt"); The readfile() function is useful if all you want to do is open up a file and read its contents. 50

file() function file() - Reads the file and returns the result in an array 51

Discover all by yourself fwrite() - Write a file in binary mode fread() - Read the file in binary mode fgets() - Retrieves the current line on which the file pointer is located fgetss() - Returns the current line of the file and removes the HTML tags fscanf() - Analyzes a file according to a format fprintf() file() - Reads the file and returns the result in a table fpassthru() - Show the rest of the file rewind() - Replace the file pointer at the beginning file_get_contents() - Get a whole file in a string fseek() flock() mkdir() rmdir() opendir() readfile() reads the filename file and sends it to the standard output 52

This lecture covers Getting data from forms html form + php action on the same page $_SERVER['PHP_SELF'] maintain form status page redirection - the header() function Upload files Files creation and deletion opening and closing reading print_r function 53

print_r function bool print_r( mixed expression [, bool return] ) displays information about a variable so that it is legible string, integer, double value itself displayed array values presented in a format that shows the keys and values print_r() places the array pointer at the end of the array reset() to bring it back to the beginning to get the result of print_r() in a string use the return parameter TRUE 54

Example withprint_r() <pre> <?php?> </pre> $a=array('a'=>'apple', 'b'=>'boat', 'c'=>array('can','clothes','cold')); print_r($a); 55

Example withprint_r() <pre> <?php?> </pre> $a=array('a'=>'apple', 'b'=>'boat', 'c'=>array('can','clothes','cold')); print_r($a); $result = print_r($a, true); 56

Attention print_r() will loop to infinity if An array or an object contains a reference on itself classic example print_r($globals) because $GLOBALS is itself a global variable therefore, contains a reference on itself 57