Presentation is loading. Please wait.

Presentation is loading. Please wait.

Creating Databases Uploading Files. Reading & writing files. Homework: Starting planning ‘original’ project.

Similar presentations


Presentation on theme: "Creating Databases Uploading Files. Reading & writing files. Homework: Starting planning ‘original’ project."— Presentation transcript:

1 Creating Databases Uploading Files. Reading & writing files. Homework: Starting planning ‘original’ project.

2 Uploading files using php What if you have an application, such as origami store, video portal, etc., and you want to provide a way for users to upload files to the server? – Users may be other people in same organization. – Now, users are not that trustworthy OR skilled, so need to put in checks!!! – Some php installations may not allow this at all. CTS was reluctant. Why?

3 Example http://socialsoftware.purchase.edu/jeanine.m eyer/fileupload1.html http://socialsoftware.purchase.edu/jeanine.m eyer/fileupload1.html – HTML does much of the work for us: a special type of input plus special attributes in the form tag. This invokes fileupload2.php and stores image files under a certain size in the subfolder uploads

4 fileupload1.html Get file name Upload image file: <form action="fileupload2.php" method="post" enctype="multipart/form-data"> Filename:

5 fileupload2.php My code displays more information that you would want in a production system!!! You would want the checking. Information on the uploaded files are in a php variable calls $_FILES. The uploaded files are in a temporary directory. My code moves it into a subfolder of the folder of the current script. CTS may have made special permissions for this to work.

6 <?php echo "Script path is $basename "; echo "File type is ". $_FILES["ufile"]["type"]. " "; echo "File size is ". $_FILES["ufile"]["size"]. " " ; if ((($_FILES["ufile"]["type"] == "image/gif") || ($_FILES["ufile"]["type"] == "image/jpeg") || ($_FILES["ufile"]["type"] == "image/pjpeg")) && ($_FILES["ufile"]["size"] < 20000000)) {

7 if ($_FILES["ufile"]["error"] > 0) { echo "Return Code: ". $_FILES["ufile"]["error"]. " "; } else { echo "Upload: ". $_FILES["ufile"]["name"]. " "; echo "Type: ". $_FILES["ufile"]["type"]. " "; echo "Size: ". ($_FILES["ufile"]["size"] / 1024). " Kb "; echo "Temp file: ". $_FILES["ufile"]["tmp_name"]. " "; if (file_exists($_FILES["ufile"]["name"])) { echo $_FILES["ufile"]["name"]. " already exists. "; } else { $target = "uploads/". $_FILES["ufile"]["name"] ; echo "The length of $target is ". strlen($target). " "; move_uploaded_file($_FILES["ufile"]["tmp_name"],$target); echo "Stored as: ". $target; } } } else { echo "Invalid file"; } ?>

8 Files Before there were databases, there were simple files. What about using a file for data? Example application: top best scores. Only keep top 5 scores. My demonstration application: http://socialsoftware.purchase.edu/jeanine.meyer/bestsco res.html http://socialsoftware.purchase.edu/jeanine.meyer/bestsco res.html [Simply] requests a player name and a score. Adds to file if big enough. Uses @fclose to mask error. Note: closes file and may or may not re-open. Script displays more than appropriate for production version.

9 bestscores.html Input new scores Player Score

10 Note The score input is a piece of text. Some browsers may check that that text represents a number, but it is still text. My script will create a scores.txt file if one does not already exist in the subfolder uploads. My script has debugging messages that should be removed for a production system.

11 strategy Open [connection to] file for reading. Read in the whole file (5 records) into an array variable $data. Close the connection to the file. Each record is name,score – Use explode to get the two different things. – Convert the score to a number – Produce an array $scores of numbers. Compare intval($newscore) to elements in $scores. – Find the first one smaller than the proposed new score. Manipulate $data by inserting a record holding “$newname,$newscore\n” Open [connection to] file for writing. For php, writing means erasing whole file and then re-writing it. Write out $data items as records.

12 bestscores.php Best scores <?php $newname = $_GET['player']; $newscore = $_GET['score']; $filen = "uploads/scores.txt"; $open = fopen($filen,"r"); print (" Just tried to open file to add $newname and $newscore. "); print ("returned handler is $open "); if ($open) { $data = file($filen); fclose($open); //file closed for ($i=0;$i<count($data);$i++) { $item = explode(",",$data[$i]); $score = intval($item[1]); $scores[] = $score; print ("current score: $i ".$item[0]." ".$item[1]." "); }

13 for($i=0;$i<count($scores);$i++) { if (intval($newscore)>$scores[$i]) { $olddata = $data[$i]; $data[$i] = "$newname,$newscore\n"; for ($j=$i+1;$j<count($scores);$j++) { $nextone = $data[$j]; $data[$j] = $olddata; $olddata = $nextone; } // $j for break; //leave $i for loop } // if newscore better } // $i loop

14 print ("now will write out new data array. "); for($i=0;$i<count($scores);$i++) { print($data[$i]." "); } // now close the file which was open for reading @fclose($open); print (" Trying to open $filen for writing "); $open = fopen($filen,"w");

15 if ($open) { print("writing out to file "); for($i=0;$i<count($scores);$i++) { fwrite($open,$data[$i]); } fclose($open); } else { print (" Unable to write updated file. The returned handler value was $open. "); } } // file opened successfully for initial read

16 else { // need to create file @fclose($open); //may not be necessary since file wasn't opened. print ("scores file doesn't exist yet "); $open = fopen($filen,"w"); if ($open) { $setsize = 5; //keep 5 top scores fwrite($open,"$newname,$newscore\n"); for ($i=1;$i<$setsize;$i++) { fwrite($open,"X,0\n"); } @fclose($open); } else { print ("couldn't create scores file."); } } //needed to create scores file ?>

17 Application Store results of a "test" with one file / person file name based on "code" – Presented as input type=password, but more just identifier If person takes test more than once, add on to the file. – This can produce many files! http://socialsoftware.purchase.edu/jeanine.m eyer/testquiz.html http://socialsoftware.purchase.edu/jeanine.m eyer/testquiz.html

18 testquiz.html function check() { var oksofar = true; if (!((document.f.a1.value.length>0) && (document.f.a2.value.length>0) && (document.f.a3.value.length))){ alert("please submit answer for each question"); oksofar = false; } if (document.f.code.value.length<3){ alert ("The identifying code must be at least 3 characters long"); oksofar = false; } if (oksofar) { return true;} else { return false; } }

19 body of testquiz Sample quiz Identifying code: Answer 1: Answer 2: Answer 3:

20 from storeanswers.php <?php $code = $_POST['code']; $a1 = $_POST['a1']; $a2 = $_POST['a2']; $a3 = $_POST['a3']; $nowp= new DateTime(); $now = $nowp->format('Y-m-d H:i:s'); $answers = "$code $now answers are 1= $a1 2= $a1 3= $a3 ".PHP_EOL; $filen ="uploads/answers". $code. ".txt" ; $open=fopen($filen,"a"); if ($open) { fwrite($open,$answers); fclose($open); print "Answers stored "; } else { print "Problem with storing answers"; } ?>

21 sample output: done twice, producing 2 lines jmm 2013-04-06 19:54:54 answers are 1= 23 2= 23 3= 4 jmm 2013-04-06 19:55:09 answers are 1= 20 2= 20 3= 6

22 More on files Create a subfolder in the folder/directory where you php file is: call it uploads. Consult with CTS to confirm you can do this. – May need their help to set permissions

23 Why use files Very simple structure OR more complex or just different from tables – Perhaps with links (pointers) such as family or corporate tree – ?

24 Refrain on 3 tier Some divide the html tier into content versus style, with CSS holding the style. This is the interaction tier. – Note: Flash and other languages (Processing, Java, ??) also do more function Middle tier, php, do 'business logic', other function. Information tier, MySQL, holds information! – Serves multiple functions. Implemented (possibly) by different groups in an enterprise.

25 Another tier? or is the 3 tier terminology insufficient Organizations use code and content developed and maintained by others. – Web services – cloud computing – content such as Google maps – ??? Extra credit opportunity to report / comment.

26 php to php Alternative to cookies or data passed via query strings are Sessions. The sessions may be passed via the HTTP headers – Extra credit opportunity: research and do posting on php Sessions Access and set using $_SESSION. This, like $_COOKIE, etc. is an associative array: accessed using names not indices. – NOTE: the shopping cart in my store application is stored as a Session variable and is itself an associative array.

27 <?php session_start(); if (!isset($_SESSION["cart"])) { $_SESSION['cart']=array(); $_SESSION['items'] = 0; $_SESSION['totalprice']=0.00; $cart = array(); } else { //print ("cart already started "); $cart = $_SESSION['cart']; } ?>

28 Shopping Cart <? require("displaycartfunction.php"); ?> <?php require("opendbo.php"); ?> Shopping cart <? if (isset($_GET['productid'])) { $p_id = $_GET['productid']; $quantity=$_GET['quantity']; $cart[$p_id] = $quantity; $_SESSION['cart'] = $cart; }

29 displaycart(); ?> Checkout (submit order)! More shopping!

30 displaycart Function stored in file displaycartfunction. Assumes that connection has been made and session started. Makes use of the foreach construction for associative arrays. – Since associative arrays don't use index values 0 to length of array, what is the code to examine each element? Answer: foreach($aa as $key=>$qty) { } assuming $aa is the associative array and $key and $qty are variables used in the loop for the keys and values – Makes use of number_format($totalprice,2) to produce dollars and cents

31 <?php //assumes that opendbo called, and session started //when call is made. function displaycart() { global $cart, $DBname, $link, $totalprice; print (" "); print (" Product ID Product Name Quantity Total cost "); $items = 0; //note session variable items not used $totalprice = 0.00; $cart = $_SESSION['cart'];

32 foreach (@$cart as $pid => $qty) { $items += $qty; //print(" the pid is ".$pid. " and the qty is ". $qty); $query="Select * from catalog where id='$pid'"; //print("query is $query"); $result = mysql_db_query($DBname, $query, $link); $item_price = mysql_result($result,0,"cost"); $item_name = mysql_result($result,0,"p_name"); $item_total_price = $item_price * $qty; $totalprice += $item_total_price; $item_total_pricef = number_format($item_total_price,2); print (" $pid $item_name $qty $item_total_pricef "); }

33 $totalpricef = "$". number_format($totalprice,2); print(" TOTALS $items items $totalpricef "); $_SESSION['items']=$items; $_SESSION['totalprice']=$totalprice; } ?>

34 Project assignment Design and develop your own database php project – work individually and then gather team to determine general idea Make posting to moodle with idea and names of people on team YOU MAY WORK BY YOURSELF or in small group. From more, more is expected. – Develop database design (ER diagram) and Data flow diagram Presentations on 4/20 – Complete project Presentations on 5/11

35 Minimal requirements At least 2 tables and at least 2 SQL statements make use of at least one of – localStorage – file(s) – file uploading – sending email At least 2 types of agents. For example: setup and production use. Error handling (form input validation)

36 Classwork / homework More postings (mainly from those people who haven’t done it) on security, passwords, normalization, and other topics). Think about ‘original / from scratch’ project. Think about your teams. – Maybe smaller? – It is okay to ‘double-dip’; for example, build on project done for another class or you anticipate doing by adding a database. Make proposal to moodle forum – Topic, names of people on team

37 Planning presentation Tell what your project is Show ER diagram – Definition of the tables Show DFD – Definition of the tasks and the agents (aka users) and the data stores (database, maybe tables, maybe localStorage) If you have it, perhaps a form This is a presentation of plans!!!!!!


Download ppt "Creating Databases Uploading Files. Reading & writing files. Homework: Starting planning ‘original’ project."

Similar presentations


Ads by Google