INFT 304 Advanced Web Engineering and PHP
INFT 304 Advanced Web Engineering and PHP
Reference book:
PHP and MySQL from Novice to Ninja, 5th Edition, by Kevin Yank
Dr. P. K. Mensah
Page 1 of 52
Requirements:
What you need:
1. PC
2. WAMP/XAMP Server
3. Adobe Dreamweaver CSC5 or higher
How Many Languages in this course?
1. PHP
2. HTML, HTML 5, etc
3. MySQL
4. GWT/ R
5. Any other language that may be necessary for the course.
WWW/HTML Basics:
• www is a protocol for exchanging information over TCP sockets, that specifies
static content of web pages.
• HTML: hypertext markup language means web pages are more than just text-can
contain multimedia, provide links for jumping within & without.
• markup implies that it works by augmenting text with special symbols (tags) that
identify structure and content type
• Language: Computer language used to describe syntax of tags that runs in web
browsers.
HTML Tags:
• tags identify structure and content type
• tags look like < >
HTML Elements
TAG Nesting
Dr. P. K. Mensah
Page 2 of 52
Web Development Tools
Structure:
<head>
<title> My first HTML document </title>
</head>
<body>
Hello world!
</body>
Dr. P. K. Mensah
Page 3 of 52
</html>
<body>
Hello world!
</body>
</html>
• The ff. is an example of a basic webpage:
<html>
<head>
<title> Talisoft Ghana </title>
</head>
<body bgcolor = “#0000CC”>
<h1> Talisoft Ghana </h1>
<h2>About our Company...</h2>
<p>This Web site provides clients, customers, and interested
parties with
information on our services; web design, e-learning, and
consultancy services.
</p>
<hr/>
<h3> Products </h3>
<p> We are probably the best web design and software company in
Africa </p>
<hr width="50%"/>
</body>
</html>
Dr. P. K. Mensah
Page 4 of 52
Text Layout:
Images:
• You can include images using IMG
• <img src="URL"|"name" height="n" width="n" alt="text" title= “text” />
Tables:
• <table>…</table> specify a table element
• <tr>…</tr> specify a row in the table
• <td>…</td> specify table data (i.e., each column entry in the table)
Frames
• Provide the ability to split the screen into independent parts.
• Frames are out of fashion, partly because they interact poorly with web search
engines.
• Frames can also “break” the regular behaviour of browsers, most notably the
“Back” button.
Content vs. Presentation
• Cascading Style Sheets associate presentation formats with HTML elements
• They can be defined at three areas:
o inline style sheets apply to the content of a single HTML element (use
style attribute)
o document style sheets apply to the whole BODY of a document
o external style sheets can be linked and applied to numerous documents
• Lower-level style sheets override higher-level style sheets.
<p style="font-family:Arial,sans-serif; text-align:right">This is a
right- justified paragraph in a sans serif font (preferably Arial)
Dr. P. K. Mensah
Page 6 of 52
Web Forms and PHP
• Each HTML form contains the following:
<FORM>...</FORM> tags
• The <FORM> tag has two required attributes:
o METHOD specifies the HTTP method used to send the request to the server
(when the user submits the form).
o ACTION specifies the URL the request is sent to.
Dr. P. K. Mensah
Page 7 of 52
FORM Method
• GET: any user input is submitted as part of the URL following a “?”. in name-value
pair
GET foo?name=joe&cookie=oreo HTTP/1.1
• POST:any user input is submitted as the content of the request (after the HTTP
headers).
Try: Which one is more secure?
Form Submission
Dr. P. K. Mensah
Page 8 of 52
o Browser uses the FORM method and action attributes to construct a
request.
o A query string is built using the (name,value) pairs from each form
element and sent to the server.
PHP syntax
Variables
Scalars:
<html>
<head>Trying ou php </head>
<body>
<p>
<?php
$foo = True;
if ($foo) echo "It is TRUE! <br /> \n";
$txt='1234';
echo "$txt <br /> \n";
$a = 1234;
echo "$a <br /> \n";
Dr. P. K. Mensah
Page 9 of 52
$a = -123;
echo "$a <br /> \n";
$a = 1.234;
echo "$a <br /> \n";
$a = 1.2e3; echo "$a <br /> \n";
$a = 7E-10; echo "$a <br /> \n";
echo 'Arnold once said: "I\'ll be back"', "<br /> \n";
$beer = 'Heineken';
echo "$beer's taste is great <br /> \n";
$str = <<<EOD Example of string spanning
multiple lines using “heredoc” syntax.EOD;
echo $str;
?> </p>
</body>
</html>
Arrays
• Create one using the keyword array( ).
Creating Arrays
• Use the array() function to create the array called $rainbow:
• Both approaches create an array with values starting at index 0 and ending at index 6.
• PHP handles the index numbering for you.
• You can choose the number the indices yourself though:
Egs.
<?php
$arr = array("foo"=>"bar", 12 =>true);
echo $arr["foo"]; // bar
echo $arr[12]; // 1
?>
<?php
array(5=>43,32,56, "b"=>12);
array(5=>43, 6=>32, 7=>56, "b"=>12);
?>
Dr. P. K. Mensah
Page 11 of 52
Multidimensional Arrays
Dr. P. K. Mensah
Page 12 of 52
Array Related Functions
• count() and sizeof()—Each of these functions counts the number of elements in an
array; eg.
o $colors = array(“blue”, “black”, “red”, “green”);
o count($colors); and sizeof($colors); returns 4.
• each() and list()—Appears together in the contest of stepping through an array
and returning its keys and values.
• foreach()—Used to step through an array, assigning the value of each element to
a given variable.
• reset($array_name)—This function rewinds the pointer to the beginning of the
array $array_name.
•
Dr. P. K. Mensah
Page 13 of 52
•
To be
continued...
<?php
$arr = array(5 => 1, 12 => 2);
$arr[] = 56; // the same as $arr[13] = 56;
$arr["x"] = 42; // adds a new element
unset($arr[5]); // removes the element
unset($arr); // deletes the whole array
$a = array(1 =>'one', 2 =>'two', 3 => 'three');
unset($a[2]);
$b = array_values($a);
?>
Operators
Dr. P. K. Mensah
Page 14 of 52
• Arithmetic Operators: +, -, *,/ , %, ++, --
• Assignment Operators: =, +=, -=, *=, /=, %=
• Comparison Operators: ==, !=, >, <, >=, <=
• Logical Operators: &&, ||, !
• String Operators: ., .=
$a = "Hello ";
$b = $a . "World!"; // now $b contains "Hello World!"
$a = "Hello ";
$a .= "World!";
Conditionals:
if else:
• date() is a built-in function that can be called with many different parameters to
return the date (and/or local time) in various formats.
• In this case we get a three letter string for the day of the week.
Mon Tue Wed Thu Fri Sat Sun
<html><head>
</head>
<body>
<?php
$d=date("D");
if ($d=="Fri")
echo "Have a nice weekend! <br/>";
else
echo "Have a nice day! <br/>";
$x=10;
if ($x==10)
{
echo "Hello<br />";
echo "Good morning<br />";
}
?>
</body>
</html>
switch:
Dr. P. K. Mensah
Page 15 of 52
switch (expression){
case label1:
code to be executed if expression = label1;
break;
case label2:
code to be executed if expression = label2;
break;
default:
code to be executed if expression is different from both label1 and
label2;
}
<html>
<head></head>
<body>
<!–- switch-cond.php -->
<?php
$x = rand(1,5); // random integer
echo “x = $x <br/><br/>”;
switch ($x)
{
case 1:
echo "Number 1";
break;
case 2:
echo "Number 2";
break;
case 3:
echo "Number 3";
break;
default:
echo "No number between 1 and 3";
}
?>
</body>
</html>
<html>
<head></head>
<body>
<?php
$i=0;
do
{
$i++;
echo "The number is $i <br />";
}
while( $i <= 10);
?>
</body>
</html>
<?php
$a_array=array("a","b","c");
foreach ($a_array as $key=>$value){
echo $key." = ".$value."\n";
}
?>
Functions
<?php
function foo($arg_1, $arg_2, /* ... */ $arg_n){
echo "Example function.\n";
return $retval;
}
Dr. P. K. Mensah
Page 17 of 52
?>
Try: Write a php function that will compute the square of a number given as an input to
it.
Within your document, call your function with a specified input number and output the
result to the document.
<?php
Function square($num){
return $num * $num;
}
echo square(4);
?>
<?php
function takes_array($input){
echo "$input[0] + $input[1] = ", $input[0]+$input[1];
}
takes_array(array(1,2));
?>
<?php
function small_numbers(){
return array (0, 1, 2);
}
File Open
<?php
if (!($fh=fopen("welcome.txt","r")))
Dr. P. K. Mensah
Page 18 of 52
exit("Unable to open file!");
?>
File Operations:
<?php
$myFile = "welcome.txt";
$fh = fopen($myFile, 'r');
$theData = fgets($fh);
fclose($fh);
echo $theData;
?>
<html>
<head></head>
<body>
<?php
echo "Referer: " . $_SERVER["HTTP_REFERER"] . "<br />";
Dr. P. K. Mensah
Page 19 of 52
echo "Browser: " . $_SERVER["HTTP_USER_AGENT"] . "<br />";
echo "User's IP address: " . $_SERVER["REMOTE_ADDR"];
?>
</body>
</html>
NB// $_SERVER["HTTP_REFERER"] =>When a web browser moves from one website to another
and between pages of a website, it can optionally pass the URL it came from.
<html>
<-- form.html -->
<body>
<form action="welcome.php" method="POST">
Enter your name: <input type="text" name="name" /> <br/>
Enter your age: <input type="text" name="age" /> <br/>
<input type="submit" /> <input type="reset" />
</form>
</body>
</html>
<html>
<!–- welcome.php -->
<body>
Welcome <?php echo $_POST["name"].”.”; ?><br />
You are <?php echo $_POST["age"]; ?> years old!
</body>
</html>
Cookies:
• creates cookies.
setcookie(name,value,expire,path,domain)
• setcookie() must appear BEFORE <html> as it’s part of the header information
sent with the page.
<?php
setcookie("uname", $_POST["name"], time()+36000);
?>
<html>
<body>
<p>
Dr. P. K. Mensah
Page 20 of 52
Dear <?php echo $_POST["name"] ?>, a cookie was set on this page!
The cookie will be active when the client has sent the cookie
back to the server.
</p>
</body>
</html>
• $_COOKIE contains all COOKIE data.
• isset() finds out if a cookie is set.
<html>
<body>
<?php
if (isset($_COOKIE["uname"]))
echo "Welcome " . $_COOKIE["uname"] . "!<br />";
else
echo "You are not logged in!<br />";
?>
</body>
</html>
Assignment:
• Student enters first name, last name and social security number and presses a
submit button.
• PHP program looks up grades for the student and returns a list of grades.
Dr. P. K. Mensah
Page 21 of 52
• Open up phpMyAdmin
• On the left panel, click your database name, enter the number of columns and create a
table. Click Go.
Dr. P. K. Mensah
Page 22 of 52
• Enter the fields and their types specifying default values (if any) , auto-increments and,
whether nulls are acceptable, etc.
• Click on Save.
• Click on the table name at the Left panel to see its structure
Dr. P. K. Mensah
Page 23 of 52
• You can Change, Drop, Update etc the table (columns) by selecting them.
• To Insert data into the table, click the Insert tab at the top of the page and fill the fields.
Dr. P. K. Mensah
Page 24 of 52
• Click on Go to Insert the data into the database
• Equally, the SQL statement can be written manually and entered in the SQL tab at the top
• Click on the table name in the left pane to see the data you just inserted
• Using SQL statements from the SQL tab, we can Create a table called staff as follows
Dr. P. K. Mensah
Page 25 of 52
Connecting to MySQL with PHP
• You can use PHP Data Objects (PDO) to establish a connection to a MySQL server:
• Create a php page and write the PHP database connection test code below:
• Output
Dr. P. K. Mensah
Page 26 of 52
PROJECT: 10 marks: 10 groups, each topic for two different groups. 2 weeks for
presentation
Dr. P. K. Mensah
Page 27 of 52
o library(shiny) or require(shiny) will load package shiny to current session.
• You may open your browser and type the above url
• Drag the slider on the left side of the page and see what happens to the histogram.
Dr. P. K. Mensah
Page 28 of 52
Structure of a Shiny App
• Two components:
o a user-interface script
o a server script
• The user-interface (ui.R) script controls the layout and appearance of your app.
• The above interface has the ff ui.R file
• The server.R script contains the instructions that your computer needs to build your app.
Dr. P. K. Mensah
Page 29 of 52
• Most of the script is wrapped in a call to renderPlot().
• Every shiny app has two R scripts saved together in the same directory.
• If your Shiny app is in a directory called my_app, run it with the following code:
Build a user-interface
• The minimum code needed to create a Shiny app is shown below.
• The result is an empty app with a blank user-interface.
• Output:
• Output
Dr. P. K. Mensah
Page 31 of 52
• titlePanel() and sidebarLayout() create a basic layout for your Shiny app, but you can
also create more advanced layouts.
• You can use navbarPage() to give your app a multi-page user-interface that includes a
navigation bar.
• Or you can use fluidRow() and column to build your layout up from a grid system.
• To create a first level header that says “My title” with h1("My title").
• pass h1("My title") as an argument to titlePanel( ), sidebarPanel( ), or mainPanel( ).
Dr. P. K. Mensah
Page 32 of 52
• You can place multiple elements in the same panel if you separate them with a comma.
• You could format texts (eg. align) by using HTML tag properties:
o h6("Episode IV", align = "center")
Dr. P. K. Mensah
Page 33 of 52
•
Images
• Use the img( ) function with the src argument to place image files in your app.
Dr. P. K. Mensah
Page 34 of 52
• e.g., img(src = "my_image.png")
Dr. P. K. Mensah
Page 35 of 52
Soltn://
Dr. P. K. Mensah
Page 36 of 52
Add control widgets
• A web element that your users can interact with.
• Widgets provide a way for your users to send messages to the Shiny app.
• Shiny widgets collect a value from your user.
• Shiny provides a function actionButton( ) that creates an Action Button and a function
namessliderInput( ) that creates a slider bar.
Dr. P. K. Mensah
Page 37 of 52
• Place a widget function in sidebarPanel( ) or mainPanel( ) in your ui.R file.
• Each widget function requires several arguments, eg
o Name for the widget: to be referenced in code
o A label: This label will appear with the widget in your app.
• In this example, the name is “action” and the label is “Action”:
o actionButton("action", label = "Action")
• The code below produces the user interface above:
Dr. P. K. Mensah
Page 38 of 52
Dr. P. K. Mensah
Page 39 of 52
• Try: Write the ui.R script for the ff. User Interface:
• ANSWER:
Dr. P. K. Mensah
Page 40 of 52
Reactive output
• Reactive output automatically responds when the user toggles a widget.
• We’ll try to make a simple Shiny app with two reactive lines of text.
• Each line will display the values of a widget based on user input.
• Place the output function inside sidebarPanel( ) or mainPanel() in the ui.R script.
o eg. add textOutput for a reactive line of text to appear on the main panel.
Dr. P. K. Mensah
Page 41 of 52
• textOutput( ) takes an argument, the character string “text1”.
• Each of the *Output( ) functions require a single argument: to serve as a variable name.
• Let’s provide the R code that builds the object in server.R.
• The code should appear in the unnamed function( ) that appears inside shinyServer( )
• The object named output contains all the code needed to update the R objects in your
app.
• Each R object needs to have its own output entry in the list.
• The element name should match the name of the reactive element that you created in
ui.R.
• In the script below, output$text1 matches textOutput("text1") in your ui.R
script.
Dr. P. K. Mensah
Page 42 of 52
• Each entry to output should contain the output of one of Shiny’s render* functions.
• These functions capture an R expression and do some light pre-processing on the
expression.
•
• This is how you create reactivity with Shiny, by connecting the values of input to the
objects in output.
TRY: Add a second line of reactive text to the main panel of your Shiny app. This line should
display “You have chosen a range that goes from something to something”, and each something
should show the current minimum (min) or maximum (max) value of the slider widget.
SOLTN://
Dr. P. K. Mensah
Page 44 of 52
•
Dr. P. K. Mensah
Page 45 of 52
R scripts and data
• We’ll learn how to load data, R Scripts, and packages to use in your Shiny apps.
• We want to build a sophisticated app that visualizes US Census data.
• counties.rds is a dataset of demographic data for each county in the United States,
collected with the UScensus2010 R package.
• Once you have the dataset,
o Create a new folder named data in your census-app directory.
o Move counties.rds into the data folder.
Dr. P. K. Mensah
Page 46 of 52
• The dataset in counties.rds contains
• Run
• Save helpers.R inside your census-app directory.
• The percent_map function in helpers.R takes five arguments:
•
• Load the maps and mapproj packages in the normal way with
• Since your app only needs to load helpers.R and counties.rds once, they should go
outside of the shinyServer function.
• This is also a good place to load the maps library (which percent_map uses).
Dr. P. K. Mensah
Page 48 of 52
Dr. P. K. Mensah
Page 49 of 52
Use reactive expressions
• Reactive expressions let you control which parts of your app update when, which
prevents unnecessary work and prevents latency.
• Continue at http://shiny.rstudio.com/tutorial/lesson6/
Dr. P. K. Mensah
Page 50 of 52
• runGist: If you don’t want to sign up for Github, is free to use this service on Github.
o Copy and paste your server.R and ui.R files to the Gist web page.
o Note the URL that Github gives the Gist.
• Your users can launch the app with runGist("<gist number>") where "<gist
number>" is the number that appears at the end of your Gist’s web address.
eg.
ui.R
Dr. P. K. Mensah
Page 51 of 52
server.R
Dr. P. K. Mensah
Page 52 of 52