ITM 352 © Port,KazmanFile I/O - 1 File I/O in PHP Persistent Data.

Slides:



Advertisements
Similar presentations
PHP Form and File Handling
Advertisements

JQuery MessageBoard. Lets use jQuery and AJAX in combination with a database to update and retrieve information without refreshing the page. Here we will.
UFCE8V-20-3 Information Systems Development 3 (SHAPE HK)
Files in C Rohit Khokher. Files in C Real life situations involve large volume of data and in such cases, the console oriented I/O operations pose two.
1 PHP Storing and Retrieving Data. string fgets(resource handle [, int length]) Reads and returns one line from a file; moves file pointer to next line.
More on PHP Coding Lab no. 6 Advance Database Management System.
FILES Files types and operations. Files Files are used to store data Data can be Text (ASCII only: 0  127) Binary (Full range: 0  256) Each file resides.
Website Development Tutorial 3. Outline Getting data from the user using forms Sending data from a form to a PHP program Writing the data to a file for.
IS 1181 IS 118 Introduction to Development Tools Week 2.
Chapter 9 Above: An early computer input/output device on the IBM 7030 (STRETCH)
PHP Tutorials 02 Olarik Surinta Management Information System Faculty of Informatics.
(c) Manzur Ashraf, Short course, KFUPM PHP & MySQL 1 Basic PHP Class 2.
Lecture 6 – Form processing (Part 1) SFDV3011 – Advanced Web Development 1.
CHAPTER 12 COOKIES AND SESSIONS. INTRO HTTP is a stateless technology Each page rendered by a browser is unrelated to other pages – even if they are from.
PHP and MySQL for Client-Server Database Interaction Chapter 10.
NMED 3850 A Advanced Online Design January 26, 2010 V. Mahadevan.
Files COP3275 – PROGRAMMING USING C DIEGO J. RIVERA-GUTIERREZ.
Chapter 8 Cookies And Security JavaScript, Third Edition.
Creating Dynamic Web Pages Using PHP and MySQL CS 320.
PHP - Part 2. More operators... Arithmetic and Assignment Operators e.g., using + and =  $IntA=5; $intB=8; $intC=$intA+$intB; //intC is 13  // Same.
18. PHP File Operations Opening a File
PHP1-1 PHP Lecture 2 Xingquan (Hill) Zhu
Lecture 8 – Cookies & Sessions SFDV3011 – Advanced Web Development 1.
Website Development with PHP and MySQL Saving Data.
PHP2. PHP Form Handling The PHP $_GET and $_POST variables are used to retrieve information from forms, like user input. Name: Age:
1 Chapter 4 – Breaking It Up: Functions spring into PHP 5 by Steven Holzner Slides were developed by Jack Davis College of Information Science and Technology.
Introduction to Programming Using C Files. 2 Contents Files Working with files Sequential files Records.
1 Chapter 7 – Object-Oriented Programming and File Handling spring into PHP 5 by Steven Holzner Slides were developed by Jack Davis College of Information.
Storing and Retrieving Data
Outline Overview Opening a file How to create a file ? Closing a File Check End-of-file Reading a File Line by Line Reading a File Character by Character.
1 File Handling. 2 Storage seen so far All variables stored in memory Problem: the contents of memory are wiped out when the computer is powered off Example:
Open Source Server Side Scripting ECA 236 Open Source Server Side Scripting Files & Directories.
8 th Semester, Batch 2008 Department Of Computer Science SSUET.
ITM © Port, Kazman1 ITM 352 More on Forms Processing.
Advanced Web 2012 Lecture 6 Sean Costain Files Sean Costain 2012 Php allows for the : Creation Reading Appending Deleting Uploading And Closing.
COMP 116: Introduction to Scientific Programming Lecture 29: File I/O.
Chapter 7 : File Processing1 File-Oriented Input & Output CHAPTER 7.
1 CHAPTER6 CHAPTER 6. Objectives: You’ll learn about;  Introduction  Files and streams  Creating a sequential access file  Reading data from a sequential.
8 Chapter Eight Server-side Scripts. 8 Chapter Objectives Create dynamic Web pages that retrieve and display database data using Active Server Pages Process.
ICS3U_FileIO.ppt File Input/Output (I/O)‏ ICS3U_FileIO.ppt File I/O Declare a file object File myFile = new File("billy.txt"); a file object whose name.
SESSIONS 27/2/12 Lecture 8. ? Operator Similar to the if statement but returns a value derived from one of two expressions by a colon. Syntax: (expression)
ITM © Port,Kazman 1 ITM 352 Cookies. ITM © Port,Kazman 2 Problem… r How do you identify a particular user when they visit your site (or any.
1 CSC103: Introduction to Computer and Programming Lecture No 28.
CS162 External Data Files 1 Today in CS162 External Files What is an external file? How do we save data in a file?
Files A collection of related data treated as a unit. Two types Text
Connecting to Files In order to read or write to a file, we need to make a connection to it. There are several functions for doing this. fopen() – makes.
C Programming Day 2. 2 Copyright © 2005, Infosys Technologies Ltd ER/CORP/CRS/LA07/003 Version No. 1.0 Union –mechanism to create user defined data types.
Programming for the Web Data Structure Writing to a file Dónal Mulligan BSc MA
FILES AND EXCEPTIONS Topics Introduction to File Input and Output Using Loops to Process Files Processing Records Exceptions.
FILE I/O: Low-level 1. The Big Picture 2 Low-Level, cont. Some files are mixed format that are not readable by high- level functions such as xlsread()
ITM 352 © Port,KazmanFile I/O - 1 File I/O in PHP Persistent Data.
Silberschatz and Galvin  C Programming Language Kingdom of Saudi Arabia Ministry of Higher Education Al-Majma’ah University College of Education.
Lesson 08: Files Class Participation: Class Chat: Attendance Code 
CGS 3066: Web Programming and Design Spring 2016
ITM 352 Cookies.
Plan for the Day: I/O (beyond scanf and printf)
CS111 Computer Programming
Files I/O, Streams, I/O Redirection, Reading with fscanf
Conditions and Ifs BIS1523 – Lecture 8.
<?php require("header.htm"); ?>
Lesson 08: Files Topic: Introduction to Programming, Zybook Ch 7, P4E Ch 7. Slides on website.
File I/O in C Lecture 7 Narrator: Lecture 7: File I/O in C.
Introduction to TouchDevelop
File Input and Output.
Lesson 08: Files Class Chat: Attendance: Participation
Files.
File I/O in PHP Persistent Data.
Professor Jodi Neely-Ritz University of Florida
Presentation transcript:

ITM 352 © Port,KazmanFile I/O - 1 File I/O in PHP Persistent Data

ITM 352 © Port,KazmanFile I/O - 2 Persistent Data Storage  Problem in mini-assignments:  Information gathered in forms and variables is only temporary– this info will disappear as soon as the page is reloaded or when the user navigates to another page.  Sometimes you need a way to keep data around between program executions (e.g. page loads)  Sometimes you need a way to share data between programs (e.g. between pages)  Three ways of more permanent (or persistent) data storage exist:  Files  Databases (we won't discuss these until ITM354)  Cookies/Sessions (we will discuss these shortly)

ITM 352 © Port,KazmanFile I/O - 3 Persistent Data Storage: Products  Let's say you have product data: Small Gumball; 0.02; Medium Gumball; 0.05; Large Gumball; 0.1;  This could be saved in a text file such as "product_data.dat"  How to use this data for our e-store?

ITM 352 © Port,KazmanFile I/O - 4 File Basics Files are controlled with "file pointers", which must be created before files are used. To open a file: $fp = fopen("name", ) This creates a handle or file pointer, called $fp The name can be in UNIX style (../../file.txt), Windows style (..\..\file.txt), a URL ( or some other data stream (e.g. ftp). will be discussed next slide…

ITM 352 © Port,KazmanFile I/O - 5 File Opening Types  'r' - Open for reading only; place the file pointer at the beginning of the file.  'w' - Open for writing only; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it.  'a' - Open for writing only; place the file pointer at the end of the file. If the file does not exist, attempt to create it.

ITM 352 © Port,KazmanFile I/O - 6 More File Opening Types  'r+' - Open for reading and writing; place the file pointer at the beginning of the file.  'w+' - Open for reading and writing; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it.  'a+' - Open for reading and writing; place the file pointer at the end of the file. If the file does not exist, attempt to create it.  These are generally less useful and more confusing, so I advise not using them.

ITM 352 © Port,KazmanFile I/O - 7 or die…  You can have PHP generate a specific error message if there is an error upon opening the file (permissions, disk space, etc.): $filename = "product_data.dat"; $h = fopen("$filename","r") or die("cannot open $filename"); Note the use of 'or', rather than '||'.

ITM 352 © Port,KazmanFile I/O - 8 Closing Files Always close a file when you're done with it– if you don't something can easily go wrong and corrupt your file. fclose($fp); (fclose returns TRUE on success or FALSE on failure. ) Why is this needed? Do Exercise #1

ITM 352 © Port,KazmanFile I/O - 9 File existence, Size of a file To check that a file exists, use: $filename = 'product_data.dat'; if( !file_exists($filename) ) echo "$filename does not exist!"; Often you will want the size of a file: echo "$filename is ". filesize($filename); Do Exercise #2

ITM 352 © Port,KazmanFile I/O - 10 Basic File I/O Example: Opening a File for Reading  To open a file or a URL we use fopen(). $filename = 'c:\file.txt'; $fp = fopen($filename, "r");

ITM 352 © Port,KazmanFile I/O - 11 Basic File I/O Example: Reading Info from a File  After we have opened the file, we will probably want to do something with it. To read the contents of a file into a variable we use fread(). $contents = fread($fp,filesize($filename)); fclose($fp);  Let us assume C:file.txt contains: 1: Hi there 2: Hello  So now $contents would be a string like: $contents = "1: Hi there\n 2: Hello\n"; Do Exercise #3

ITM 352 © Port,KazmanFile I/O - 12 Basic File I/O Example: Writing To a File  We can also write data into a file once we have opened it. To do this we use the fputs() function.  $filename = 'c:\file.txt'; $fp = fopen($filename, "a"); $string = "3: G'day\n"; $write = fputs($fp, $string); fclose($fp);  So now what will the file contain? 1: Hi there 2: Hello 3: G'day Do Exercise #4

ITM 352 © Port,KazmanFile I/O - 13 Basic File I/O Example: Reading Formatted Data  We can also read data from a file once we have opened it. To do this we use the fscanf() function. $filename = './file.txt'; $fp = fopen($filename, 'r'); while(fscanf($fp, '%d: %s\n', $number, $text)) { print "the text: $text is on line number: $number "; }; fclose($fp);  Prints the text: Hi is on line number: 1 the text: Hello is on line number: 2 the text: G'day is on line number: 3

ITM 352 © Port,KazmanFile I/O - 14 Warning: reading using fscanf can be tricky.  It's easier to read a line at a time, using fgets() or fgetss()... and then use strtok(), split(), or explode() to grab individual parts of the line. More on Reading Formatted Data

ITM 352 © Port,KazmanFile I/O - 15 <?php $fname = "test_file.txt"; // test_file.txt contains: $fp = fopen($fname, "r");// Dan Port;dport;portpass $size = filesize($fname);// Rick Kazman;kazman;kazpass // ITM352TA;itm352;password while($line_in = fgetss($fp, $size)) { echo "Got line: $line_in "; // $fields = explode (';', $line_in); $first = strtok($line_in, ";"); $second = strtok(";"); $third = strtok(","); echo "Tokens: $first / $second / $third "; } fclose($fp); ?> Reading Formatted Data: Example Code Do Exercise #5

ITM 352 © Port,KazmanFile I/O - 16 File Permissions To read from and write to files, certain permissions are necessary. Since the web interacts with our pages as the group (www), you may need to add group read, write and/or execute permissions. Permissions are changed with the folder properties in Windows, and the chmod command in UNIX

ITM 352 © Port,KazmanFile I/O - 17 PHP File Functions  PHP has many useful functions for manipulating files, such as:  fileread()  Reads a file into a string  file()  Reads a file into an array  unset()  Deletes a file  fileperms()  Provides statistics on a file  fscanf()  Reads a file in a particular format

ITM 352 © Port,KazmanFile I/O - 18 Why Use Files?  Often data needs to be stored for later use  Programs aren't always running (especially true of web applications which run only when a page is loaded) and data needs to be shared between different executions  Data needs to be shared between different programs  Keep data in a known location  Keeping the code separate from the data is a good programming practice.  Can make files work like an array, except they will persist.  Can do fancy stuff like binary encoding (for efficiency) or encryption (for security)

ITM 352 © Port,KazmanFile I/O - 19 Why NOT Use Files?  Typically users want simultaneous access to the data  Can't handle large amounts of data  No support for data analysis  No support for queries, reports, …  These ARE supported by relational DBs

ITM 352 © Port,KazmanFile I/O - 20 Things you can do with files...  User registration data  Products and services information  Real time inventory  Message board (the registration signup)  Shopping cart  Anything that requires persistent data.....

ITM 352 © Port,KazmanFile I/O - 21 Example: Project Registration Board (register_asst1.php: user registration input form) Please register your assignment #1 information. Be sure to verify that your description is different from any listed currently! Name: Describe your on-line store:

ITM 352 © Port,KazmanFile I/O - 22 ( messboard_ass1.php ) <?php $messFile = "./assignment1_regs.txt"; if(!empty($_POST['name'])) { echo "YOUR REGISTRATIONS FOR ASSIGNMENT #1 HAS BEEN RECEIVED (SEE END OF LIST) "; $fp = fopen($messFile, "a"); $data = 'IP address:'. $_SERVER["REMOTE_ADDR"]. ' Name: '. $_POST['name']. ' '. 'Description: '. $_POST['description'].' '. " "; fwrite($fp, $data); fclose($fp); } Example: Writing Posted Data

ITM 352 © Port,KazmanFile I/O - 23 ( messboard_ass1.php cont ’ d ) if(file_exists($messFile)) { echo "CURRENT REGISTRATIONS FOR ASSIGNMENT #1 "; echo " "; $theFile = file($messFile); foreach($theFile as $value) { echo "$value\n"; echo " "; } } ?> Example: Reading Registrations

ITM 352 © Port,KazmanFile I/O - 24 Example: Persistent Arrays function arrayfile_to_array($filepath) { // This function reads the file at $filepath and returns an // array. It is assumed that the file being read is a // serialized array (created using array_to_arrayfile) $fsize if ($fsize > 0) { $fp = fopen($filepath, "r"); $encoded = fread($fp, $fsize); fclose($fp); return unserialize($encoded); } else echo "$filepath does not exist!"; }

ITM 352 © Port,KazmanFile I/O - 25 Example: Persistent Arrays (cont.) function array_to_arrayfile($theArray, $filepath) { // This function serializes an array in $theArray and saves it // in the file at $filepath. The file may then be converted // back into an array using the arrayfile_to_array() function) if($fp = fopen($filepath, "w+")) { $encoded = serialize($theArray); fwrite($fp, $encoded); fclose($fp); } else echo "Unable to write array to $filepath"; }