Introduction to Web Programming with PHP Scripting Language for Applications in Agricultural Climatology Title.

Slides:



Advertisements
Similar presentations
PHP I.
Advertisements

UFCE8V-20-3 Information Systems Development 3 (SHAPE HK) Lecture 3 PHP (2) : Functions, User Defined Functions & Environment Variables.
Java Script Session1 INTRODUCTION.
Introduction to PHP MIS 3501, Fall 2014 Jeremy Shafer
Chapter 7: User-Defined Functions II
Working with JavaScript. 2 Objectives Introducing JavaScript Inserting JavaScript into a Web Page File Writing Output to the Web Page Working with Variables.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Introduction to Scripting.
CIS101 Introduction to Computing Week 05. Agenda Your questions Exam next week - Excel Introduction to the Internet & HTML Online HTML Resources Using.
CIS101 Introduction to Computing Week 05. Agenda Your questions CIS101 Survey Introduction to the Internet & HTML Online HTML Resources Using the HTML.
CIS101 Introduction to Computing
XP 1 Working with JavaScript Creating a Programmable Web Page for North Pole Novelties Tutorial 10.
Guide To UNIX Using Linux Third Edition
 2004 Prentice Hall, Inc. All rights reserved. Chapter 25 – Perl and CGI (Common Gateway Interface) Outline 25.1 Introduction 25.2 Perl 25.3 String Processing.
Creating a Web Page HTML, FrontPage, Word, Composer.
PHP: Hypertext Processor Fred Durao
CSC 318 WEB APPLICATION DEVELOPMENT.  Introduction to Server Scripting language  Client VS Server  Introduction to PHP  PHP Files and Syntax  Function.
PHP Tutorials 02 Olarik Surinta Management Information System Faculty of Informatics.
1 Introduction to PHP. 2 What is this “PHP” thing? Official description: “PHP, which stands for "PHP: Hypertext Preprocessor" is a widely-used Open Source.
Introduction to PHP and Server Side Technology. Slide 2 PHP History Created in 1995 PHP 5.0 is the current version It’s been around since 2004.
Reading Data in Web Pages tMyn1 Reading Data in Web Pages A very common application of PHP is to have an HTML form gather information from a website's.
JavaScript, Fifth Edition Chapter 1 Introduction to JavaScript.
INTERNET APPLICATION DEVELOPMENT For More visit:
1 PHP and MySQL. 2 Topics  Querying Data with PHP  User-Driven Querying  Writing Data with PHP and MySQL PHP and MySQL.
NMED 3850 A Advanced Online Design January 26, 2010 V. Mahadevan.
IST 210: PHP BASICS IST 210: Organization of Data IST210 1.
CMPS 211 JavaScript Topic 1 JavaScript Syntax. 2Outline Goals and Objectives Goals and Objectives Chapter Headlines Chapter Headlines Introduction Introduction.
XP Tutorial 10New Perspectives on Creating Web Pages with HTML, XHTML, and XML 1 Working with JavaScript Creating a Programmable Web Page for North Pole.
November 2003Bent Thomsen - FIT 6-11 IT – som værktøj Bent Thomsen Institut for Datalogi Aalborg Universitet.
Creating Dynamic Web Pages Using PHP and MySQL CS 320.
NMED 3850 A Advanced Online Design January 12, 2010 V. Mahadevan.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
Website Development with PHP and MySQL Saving Data.
1 Welcome to CSC 301 Web Programming Charles Frank.
Variables and ConstantstMyn1 Variables and Constants PHP stands for: ”PHP: Hypertext Preprocessor”, and it is a server-side programming language. Special.
Intro to PHP IST2101. Review: HTML & Tags 2IST210.
What is PHP? PHP stands for PHP: Hypertext Preprocessor PHP is a server-side scripting language, like ASP PHP scripts are executed on the server PHP supports.
Overview of Form and Javascript fundamentals. Brief matching exercise 1. This is the software that allows a user to access and view HTML documents 2.
JavaScript Scripting language What is Scripting ? A scripting language, script language, or extension language is a programming language.
Server-Side Scripting with PHP ISYS 475. PHP Manual Website
JavaScript, Fourth Edition
1 WWW. 2 World Wide Web Major application protocol used on the Internet Simple interface Two concepts –Point –Click.
הרצאה 4. עיבוד של דף אינטרנט דינמי מתוך Murach’s PHP and MySQL by Joel Murach and Ray Harris.  דף אינטרנט דינמי משתנה עפ " י הרצת קוד על השרת, יכול להשתנות.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Introduction to Scripting.
JavaScript. JavaScript Introduction JavaScript is the world's most popular programming language. It is the language for HTML and the web, for servers,
IS2803 Developing Multimedia Applications for Business (Part 2) Lecture 2: Introduction to IS2803 Rob Gleasure
1 PHP Intro PHP Introduction After this lecture, you should be able to: Know the fundamental concepts of Web Scripting Languages in general, PHP in particular.
PHP Form Processing * referenced from
Internet & World Wide Web How to Program, 5/e © by Pearson Education, Inc. All Rights Reserved.
Dr. Abdullah Almutairi Spring PHP is a server scripting language, and a powerful tool for making dynamic and interactive Web pages. PHP is a widely-used,
PHP Tutorial. What is PHP PHP is a server scripting language, and a powerful tool for making dynamic and interactive Web pages.
CGS 3066: Web Programming and Design Spring 2016 PHP.
IST 210: PHP Basics IST 210: Organization of Data IST2101.
PHP using MySQL Database for Web Development (part II)
Introduction to Dynamic Web Programming
Chapter 6 JavaScript: Introduction to Scripting
Introduction to Programming
JavaScript Syntax and Semantics
PHP Introduction.
Chapter 27 WWW and HTTP.
WEB PROGRAMMING JavaScript.
PHP.
Web DB Programming: PHP
Introduction to Programming
HYPERTEXT PREPROCESSOR BY : UMA KAKKAR
Intro to PHP.
Tutorial 6 PHP & MySQL Li Xu
PHP an introduction.
Introduction to Programming
Web Programming and Design
SEEM 4540 Tutorial 4 Basic PHP based on w3Schools
Presentation transcript:

Introduction to Web Programming with PHP Scripting Language for Applications in Agricultural Climatology Title

Course Outline Background & Introduction Resources Setup Input Comment & Output Data Type Variable Scope Control Flow Function File Input (combo box) Project Exercises

Background Why web programming  Broader impact  Increasing use of internet  Exclusivity  Restriction & monitoring ability  Increasing interests in dynamic web, ie:  Simple conversion (Rothamsted Research, England) Simple conversion  Water balance (University of Georgia) Water balance Why PHP?  Efficient delivery  No compiler (developer)  No installation (user)  Potential link to database (ie. Mysql)  Open source & flexible syntax Source: International Telecommunication Union (ITU)

About PHP Php Recursive acronym: Hypertext Preprocessor Open source scripting language suited for web application Server side execution rather than client-side (ie. JavaScript) Requirement: Server (web host) supports PHP Characteristic: somewhat flexible syntax ServerClient javascript browser php web-host

Server & File Transfer Example of Php-enabled server HPRCC - SSH approach AgilityHoster - FTP approach File transfer methods SSH –SSH - Secure Shelln, a network protocol that allows data to be exchanged using a secure channel between two networked devices –SSH is used primarily on Linux and Unix based systems to access shell accounts. –SSH is a replacement for telnet and other insecure remote shells FTP –FTP – file transfer protocol –FTP is built on a client-server architecture

Server Set Up For this course, you will set up an account with AgilityHoster.com Go to the setup pagesetup page Follow the steps below –Choose 'Free hosting' plan, continue, sign up, enter personal info, continue, –Click link to login, enter username and password given in the , enter the member page (menu on top and left with account statistic at the bottom left of the page). –Go to WebsiteManager –Select SubDomain Manager –Enter a subdomain name: ie your personalized name (it will take 5 minutes to get set up) –Setup ftp: go to website manager, ftp manager, enter cutsom ftp name: ####_name, andpassword.

Resources For this course, you will also set up resources for writing php codes File transfer: WSFTP Text editor: Texpad Download the resources Setting up WSFTP –Enter new profile name, ie: php training agilityhoster –Enter host name/address: customizedname.agilityhoster.com –UserID: -- should be automatically filled –Password: enter the custom password you set up previously –The Ftp is ready to do file transfer –Create a folder in your hardrive to store all your web/php files

Basic syntax & first exercise Basic syntax start and end processing instruction Semicollon (;) after each statement, case insensitive! First exercise (hello world!) <?php ?> PHP Test <?php echo " Hello World "; ?>

Input (basic) Required HTML form Functions: isset - Determines if a variable is set and is not NULL. $_POST['variable'] is an associative array of variables passed to the current script via the HTTP POST method.HTTP $_POST is a superglobal contains information pertinent to any parameters passed using the POST method. –POST is a preferred option (the other option is GET) as it can handle considerably more data –A POST request includes a message body in addition to a URL used to specify information for the action being performed.URL –Example of URL encoding is as follow: Name: Jonathan Doe Age: 23 Formula: a + b == 13%! Encoded as: Name=Jonathan+Doe&Age=23&Formula=a+%2B+b+%3D%3D+13%25%21

Input (syntax) Syntax (example): View this example PHP Test <?php if (isset($_POST['submit'])) { echo "Hi, ". $_POST['name']. "! "; } ?> Name:

Comments & Output Comments Output Print –displaying output to screen –return boolean Single line // comment Multi line /* comment */ <?php print ("test print"); print "test print"; ?>

Output (cont'd) Output echo –displaying output to screen –return void –identical to print theoretically echo would be faster (efficient) as it returns nothing, however, the difference is impossible to notice. The decision to use is rather stylistic concern. printf() –displaying formatted output to screen –example: printf("01.2f", 43.2); // –for description of format variables, go to: sprintf() –identical to printf(), but the output is assigned to a string variable –example: $var = sprintf("%01.2f",43.2); echo "$var"; //

Data types Boolean (true or false) $variable = false; // $variable is false $variable = 0; // $variable is false $variable = true; // $variable is true $variable = 1; // $variable is true $variable = 5; // $variable is true Any non-zero value – true Integer Whole number, no fractional parts Maximum supported integer size is typicalla 2^31 Float Floating-point number -- contains fractional parts. String Sequence of character treated as a contiguous group

Data types (cont'd) Array Series of similar items. Index collection of data values. Each index (key) references to a corresponding value. Example: member[0] = "John"; member[1] = "Marry"; member[2] = "Suzzie";

Data types (cont'd) Object Must be explicitly declared: Class -- attribute, function Class definition serves as template and cannot itself be manipulated. Instead, objects are created based on this template -- use 'new' keyword. soybean object is created and can then it attribute can be set by making us of the method setGroup() Class plant { private $group; function setGroup($status){ $this->group = $status; } $soybean = new plant; $soybean->setGroup("dicots");

Type casting Converting one type to the other example: $variable1 = 13; $variable2 = (double) $variable1; // 13.0 $variable1 = 4.2; $variable2 = (int) $variable1; // 4 (truncated, not round)

Variables Scope Local Variables A variable declared in a function is considered local. It can only be referenced in that function. When you exit the function in which a local variable has been declared, that variable and its corresponding value are destroyed. View this example $x = 2; function assignx() { $x = 0; echo "x inside function is $x "; } assignx(); echo "x outside function is $x ";

Variables Scope (cont'd) Global Variables Global variables can be accessed in any part of the program To modify global variabl, it must be explicitly declared to be a global in the function in which itis to be modified. View this example $x = 2; function assignx() { Global $x; $x = 0; echo "x inside function is $x "; } assignx(); echo "x outside function is $x ";

Variables Scope (cont'd) Static Variables Static variable does not lose its value when the function exists. View example without static View example with static function keep_track() { Static $count = 0; $count++; echo "$count "; } keep_track();

Variables Scope (cont'd) Superglobal Variables Predefined variables View example HTTP_USER_AGENT provide user's browser information For more examples of similar superglobal variables, go to: echo "Your browser is: $_SERVER['HTTP_USER_AGENT']";

Operators For list of operators in php, go to: The list includes: arithmetic operators (*, /, +, -) string operator, ie concatenate with "." logical operators (&&, ||) equality operators (==, !=)

Control flow Conditional Controlling the flow of execution depending on the specified condition defined by expression Exercise 1: if statement – thermal time calculation Exercise file View output if (expression) { statement; } if (expression) { statement; } else { statement; } if (expression) { statement; } else if (expression) { statement; } else { statement; }

Control flow (cont'd) Conditional Use as variant of if-else combination when need to compare with large number of values switch($catagory) { case "1": statement1; break; case "2": statement2; break; case "3": statement3; break; case "4": statement4; break; }

Control flow (cont'd) While loop Specifies a condition that must be met before execution is terminated View example *We will be using 'while loop' in the final project exercise, to read weather data while (expression) { statements; } //Example: incremental value global $i; $i = 0; while ($i <= 5) { echo "$i "; $i++; }

Control flow (cont'd) For loop Statement which allows code to be repeatedly executed View example *We will be using 'for loop' in the final project exercise, to perform calculation of cumulative thermal time for (expression1; expression2; expression3) { statements; } //Example: Incremental values global $i; for ($i=0; $i<=5; $i++) { echo "$i "; }

Functions Consist of: (1) Function definition, (2) Function implementation View example function definition function function_name (parameters) { statements; } //function definition: converting degrees to radians function rad($deg_in) { $result = $deg_in *(pi()/180); return $result; } //function implementation: converting degrees to radians $radvalue = rad(30.0); echo "radvalue= $radvalue "; //radvalue= function implementation //value-returning function: $value = function_name(parameters); //non-returning function: function_name(parameters);

Arrays Series of similar items, accessible via index Index can be integer or string Array size is accessible by using 'count()' function //Basic syntax to access array's item $array_name[index] = array value Exercise 2: array Exercise file View output

File Server Client php codes files php codes files File Reading & Writing Steps: (1) Connecting file handler to a file (2) Capturing file content (3) Closing file (ending file handler connection to a file)

File Reading //assigning file handler to a file $file_handler = fopen("filename","mode"); //capturing file content $var = fgetcsv($file_handler,1000,","); //closing file fclose($file_handler); maximum char per line mode: r = read only w = write only rt = read only, text file more on modes:

File Reading (cont'd) File Reading Exercise Exercise file View output Create "input_files" directory in the ftp folder Create date.txt file with the following content:

File Writing File Writing Exercise Exercise file View output Create "output_files" directory in the ftp folder //assigning file handler to a file $file_handler = fopen("filename","mode"); //writing file fwrite($filehandler,"$variable_to_write"); //closing file fclose($file_handler); mode: w = write only, wt = write only, text file, a = append more on modes:

File Reading – Multiple Columns Multiple columns of data are common, ie: weather data File Reading Example – Multi Columns View code View output Trick: Create an intermediate 'clean' file (two reading steps) The 'clean' file has a consistent delimited, ie: one space User ereg_replace() function to clean extra white spaces $originalvar = "10 20"; $cleanvar = ereg_replace(' +', ' ', $originalvar); echo "$cleanvar"; // File to read: data2.txt

Combo box Example View this example Month: Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec

Project Exercise Goal Reading weather file from long-term weather data from NASA Eventually calculate cumulative thermal time (GDU) for a user-given starting and ending dates Preparation Download new weather data from NASA site *,NASA site or use the existing weather data for Lincoln, NELincoln, NE * Required lat & long input Online resource for finding lat long of a location: itouchmapitouchmap Save weather file as text file under your input_files folder

Project Exercise 1 Objective Reading weather file (NASA-DSSAT format) Output tmax, tmin, and tmean for the first 10 days Topics covered - Form - Combo box - File reading - For loop - While loop - If statement - String manipulation (ereg_replace) - Functions (date->doy conversion)

Project Exercise 1 (cont'd) View output weather data: Lincoln, NE lat: 40.82, long: , To skip a header line, you can assign it to a dummy variable $header = fgets($file_handler); Additional cleaning step would be needed if there is extra whie space to the left of the first column of the data. You can use the ltrim approach: Example: $array_output[$i] = ltrim($array_output[$i]); The goal is to read tmax and tmin. However, the data contains other weather variables (ie. solar radiation, rh, ect). You can assign dummy variables for the extra variables, or it doesn't hurt to assign each to uniqe variable (in case you would need it for something else) Particular important variable is tmean, not in the data, it's calculated as: Tmean = 0.5 * (Tmax + Tmin)

Project Exercise 2 Objective Reading weather file (NASA-DSSAT format) Output tmax, tmin, and tmean for the first 10 days from a defined starting date Topics covered - Form - Combo box - File reading - For loop - While loop - If statement - String manipulation (ereg_replace) - Functions (date->doy conversion)

Project Exercise 2 (cont'd) View output Table of day of year vs date Use practically all the component from the previous exercise For day selection combo box, you can use for loop, ie from i=1 to i=31 View Example The conversion from Date to DOY is needed because the user input is date while the weather data is index by year and DOY. View Date to DOY function Use if statement to identify starting point (year & doy) to start displaying the output, within a for loop going thru the whole index of data. ie: for ($i=0; $i<=$array_size; $i++) { if (($year_array[$i] == $yearinput) && ($doy_array[$i] >= $doyinput) && ($doy_array[$i] < $doyval+9)) { //put output statement here } Use $_POST['var'] to capture form inputs $yearval = $_POST['year']; $monthval = $_POST['month']; $dayval = $_POST['day'];

Project Exercise 3 Objective Reading weather file (NASA-DSSAT format) Output tmax, tmin, and tmean, thermal time, and cumulative thermal time for a given range between starting and ending dates Topics covered - Form - Combo box - File reading - For loop - While loop - If statement - String manipulation (ereg_replace) - Functions (date->doy conversion)

Project Exercise 3 (cont'd) Everything the same as the previous exercise, except: (1)add inputs in the forms also for the ending date (2)add text inputs for 'tbase' and 'topt' tbase = temperature below which plant growth/development rate equals zero topt = temperature at which plant growth/development rate is maximal and thereafter it is to continue at such maximal rate Modify if statement to identify both starting and ending point (year & doy) to start displaying the output & calculating thermal time & it's cumulative value ie: if (($year_array[$i] >= $yearval) && ($doy_array[$i] >= $doyval) && ($year_array[$i] <= $yearendval) && ($doy_array[$i] <= $doyendval)) Use the previous thermal time algorithm, but should applied as a function (see example)example To calculate cumulative thermal time, use the following accumulation algorithm: $cvalue = $cvalue + $value_array[$i]; To obtain final cumulative thermal time value, you can use max function: $CTTfinal = max($cval_array)); View output

Misc. Definitions Uniform Resource Locators (URLs) URLs provide the hypertext links between one document and another. It specifies where an identified resource is available and the mechanism for retrieving it. Hypertext Markup Language (HTML) WWW documents contain a mixture of directives (markup), and text or graphics. It provides a means to describe the structure of text-based information in a document—by denoting certain text as links, headings, paragraphs, lists, et. The World Wide Web is composed primarily of HTML documents transmitted from Web servers to Web browsers using the Hypertext Transfer Protocol (HTTP).