0% found this document useful (0 votes)
62 views52 pages

INFT 304 Advanced Web Engineering and PHP

This document provides an overview of HTML and web development topics including HTML tags and elements, web page structure, text formatting, hyperlinks, images, tables, forms, and CSS. It also lists the required tools and languages that will be covered in the course.

Uploaded by

Sam Berchie
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
62 views52 pages

INFT 304 Advanced Web Engineering and PHP

This document provides an overview of HTML and web development topics including HTML tags and elements, web page structure, text formatting, hyperlinks, images, tables, forms, and CSS. It also lists the required tools and languages that will be covered in the course.

Uploaded by

Sam Berchie
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 52

UNIVERSITY OF ENERGY AND NATURAL RESOURCES

Department of Computer Science and Informatics

INFT 304 Advanced Web Engineering and PHP


LECTURE NOTES
2021/2022 SECOND SEMESTER

Reference book:
PHP and MySQL from Novice to Ninja, 5th Edition, by Kevin Yank

Dr. Patrick Kwabena Mensah


email: pmensah@uds.edu.gh
WhatsApp: 0507120624

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 < >

<strong> Hi There </strong> emboldens the text


<img src="image.gif" /> specifies an image
• most tags come in pairs, marking a beginning and ending
<title> HELLO </title>

HTML Elements

• objects enclosed within a pair of tags


<title>My Home Page</title> is a TITLE element
<b>This text appears bold.</b> is a BOLD element
<p>Part of this text is <b>bold</b>.</p>

TAG Nesting

Dr. P. K. Mensah
Page 2 of 52
Web Development Tools

• Microsoft FrontPage, Netscape Composer, Adobe PageMill, DreamWeaver,


HotDog, Bluefish etc.

Structure:

• A HTML document has two main structural elements


 HEAD contains setup information for the browser & the Web page. e.g.,
the title for the browser window, style definitions, Script code, etc.
• BODY contains the actual content to be displayed in the Web page.
<HTML>
<HEAD>
</HEAD>
<BODY>
</BODY>
</HTML>
• HTML documents begin and end with <html> and </html> tags
• Comments appear between <!-- and -->
<html>
<!–- Comments go here
-- Description: introductory page –
-->

<head>
<title> My first HTML document </title>
</head>

<body>
Hello world!
</body>
Dr. P. K. Mensah
Page 3 of 52
</html>

• declares version of HTML used


<!DOCTYPE
o Describes <meta
o specifies information about the document rather than document content.
✓ E.g.describe content of the page for search engines and name of
author.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">


<html>
<head>
<title>My HTML Document</title>
<meta name="Author" content=“Patrick Mensah K.“
<meta name="copyright" content=“2013 UDS">
<meta name="keywords“ content="computing,webdesign,advertising">
<meta name="date" content="1994-11-06T08:49:37+00:00">
<meta http-equiv="Content-Type" content="text/htm; charset=iso-8859-1“>

<!–- Comments go here -->


</head>

<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:

• How would the text be displayed in a browser?


o Leave that to the browser.
• You can however:
o force a line break using the <br/> tag (no closing tag)
o specify a new paragraph (starts on a new line, preceded by a blank line)
using <p>…</p>
o force a space character using the symbol for a non-breaking space: &nbsp;

<h1>…</h1> tags produce a large, bold heading.


<h2>…</h2> tags produce a slightly smaller heading.
. . .
<h6>…</h6> tags produce a tiny heading.
<hr/> draws line across window
<hr width="50%" /> sets width
<hr size="10" /> sets thickness.
<b>… </b> specify bold
<i>… </i> specify italics
<tt>… </tt> specify typewriter-like (fixed-width) font
<big>… </big> increase the size of the font
<small>… </small> decrease the size of the font
<em>…</em> put emphasis
<strong>…</strong> put even more emphasis
<sub>… </sub> specify a subscript
<sup>… </sup> a superscript
<pre>…</pre> include ready-formatted text.
<ol>…</ol> specifies an ordered list (using numbers or letters to label each
list item)
<li> identifies each list item can set type of ordering, start index
<ul>…</ul> specifies unordered list (using a bullet for each)
<li> identifies each list item
<dl>…</dl> specifies a definition list <dt> identifies each term
<dd> identifies its definition
Hyperlinks or ANCHOR
• <a href="URL">…</a> where URL is the Web address of the page to be displayed
when the user clicks on the link
• If the page is accessed over the Web, must start with http:// if not, the browser
will assume it is the name of a local file
• <a href="URL" target="_blank">…</a> causes the page to be loaded in a new
Window
Dr. P. K. Mensah
Page 5 of 52
• <a href=mailto:email_add> Opens default email application
• <a name="ident">…</a> where ident is a variable for identifying this location.
• <a href="#ident">…</a> will then jump to that location within the file.
• <a href="URL#ident">…</a> can jump into the middle of another file.

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)

<span style="color:green">green text</span>.</p>

o <span> is used to group elements in the HTML document.


• Within a tag, we can list sequence of property:value pairs:

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.

<FORM METHOD=“POST” ACTION=“http://www.talisoftgh.com/requests”>


<FORM METHOD=“GET” ACTION=“myprog.php”>
<FORM METHOD=“POST” ACTION=“mailto:info@talisoftgh.com”>

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

• Form is submitted to a server side technology to handle:


o Perl
o Python
o ColdFusion
o PHP
• We need a web server to implement the above technology:
o IIS – In Microsoft windows.
o Apache – Free open source (XAMP, MAMP, WAMP, Apache2Triad, etc).
✓ Root folder: www folder.
✓ Webpage: http://localhost
<FORM METHOD=POST ACTION=”handleFormData.php”>
Your Name:
<INPUT TYPE=TEXT NAME="Name"><BR>
Your Password: <INPUT TYPE=PASSWORD NAME=“pWord"><BR>
<INPUT TYPE=SUBMIT VALUE="Submit">
<INPUT TYPE=RESET>
</FORM>

Try: Read on the following topics:

o Using Tables to present form elements in a nice way.


o Using checkboxes.
o Using radio buttons.
o Using Multiline Textarea.
o Using select options or pull down list of items.
o How to upload a file unto your server, ie.

Form Submission to Server


• When the user pushes SUBMIT button the following happens:

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-Hypertext PreProcessor To be continued from here...

• Server-side middleware embedded in HTML using tags.


• File extension is .php or .phtml.

PHP syntax

• Starts with <?php and ends with ?>.


• print and echo for output.
• A semicolon (;) at the end of each statement.
• // for a single-line comment.
• /* and */ for multi-line comment.
• Use the function phpinfo() to learn more about your version of php.

Variables

• All variables start with a $.


• There is no strong-typing; a variable’s type is determined from how it is used.

Scalars:

• Four scalar types:


o boolean : TRUE or FALSE
o integer : just numbers
o float : float point numbers
o string : single quoted, double quoted

<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:

o or equally, we can use the ff approach to create the array

• 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:

• You can add a new element “violet” to the array by typing


Dr. P. K. Mensah
Page 10 of 52
Creating Associative Arrays

• An ordered map of value,key pairs.


o value = any PHP type.
o key = either an integer or a string.
• Syntax:
array(
key => value,
key2 => value2,
key3 => value3,
...
)

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);
?>

• To add a new element to $character

Dr. P. K. Mensah
Page 11 of 52
Multidimensional Arrays

• 3 more array() are created inside the initial array.


• The 3 array() can be referred to as $characters[0], $characters[1], and $characters[2].
• If you print echo $characters[1]; , you will get the output: Array
• However, if you want “superhero”, type
echo $characters[1][‘occupation’];
• To iterate through the key=>value pairs of the above array, use a foreach loop with list( )
and each( ) functions:

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...

• unset() removes a key/value pair.


• array_values() makes reindex effect (indexing numerically).

<?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);
?>

Try: Visit the php manual for more on arrays:


http://php.net/manual/en/language.types.array.php

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:

• Select one of many statements to execute.

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>

while and do-while


<html>
<head> </head>
<body>
<?php
$i=1;
while( $i <= 5)
{
echo "The number is $i <br />";
$i++;
Dr. P. K. Mensah
Page 16 of 52
}
?>
</body>
</html>

<html>
<head></head>
<body>
<?php
$i=0;
do
{
$i++;
echo "The number is $i <br />";
}
while( $i <= 10);
?>
</body>
</html>

for and foreach:


<?php
for ($i=1; $i<=5; $i++){
echo "Hello World!<br />";
}
?>

<?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);
}

list($zero, $one, $two) = small_numbers();


echo $zero, $one, $two;
?>

File Open

• fopen("file_name","mode") function is used to open files in PHP.


• “mode” can be any of the ff:
o r Read only. r+ Read/Write.
o w Write only. w+ Read/Write.
o a Append. a+ Read/Append.
o x Create and open for write only.
o x+ Create and open for read/write.

<?php
if (!($fh=fopen("welcome.txt","r")))
Dr. P. K. Mensah
Page 18 of 52
exit("Unable to open file!");
?>

File Operations:

• fclose() closes a file.


• feof() determines if the end is true.
• fgetc() reads a single character.
• fgets() reads a line of data.
• fwrite(), fputs writes a string with and without \n.
• file() reads entire file into an array.
<?php
$myFile = "welcome.txt";
if (!($fh=fopen($myFile,'r')))
exit("Unable to open file.");
while (!feof($fh)) {
$x=fgetc($fh);
echo $x;
}
fclose($fh);
?>

<?php
$myFile = "welcome.txt";
$fh = fopen($myFile, 'r');
$theData = fgets($fh);
fclose($fh);
echo $theData;
?>

Handling user input data from HTML forms:


• User fills out a form and presses submit.
• PHP gets a set of name,value pairs - one for each form field.
• PHP decides what to do with them.
• $_SERVER is a reserved variable that contains all server information.
o It is a super global variable, i.e. it's available in all scopes of a PHP script.

<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.

• and $_GET are reserved global variables available at the server,


$_POST
o They contain all client name-value pair.
$vName = $_POST[“visitor_name"]:

<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>

• NB: time() returns current Unix timestamp.

GET vs. POST:

• When using forms it’s generally better to use POST:


o There are limits on the maximum size of a GET query string.
• A POST query string doesn’t show up in the browser as part of the current URL.

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.

PHP and MySQL

Dr. P. K. Mensah
Page 21 of 52
• Open up phpMyAdmin

• Click Databases tab, name the database and click Create

• 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

• We can Insert data into the staff table

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

• Try: How to set Username and Password in WAMP server.

Read Table Data from Database


• Use a SELECT statement with a while loop to show your table values:

Dr. P. K. Mensah
Page 26 of 52
PROJECT: 10 marks: 10 groups, each topic for two different groups. 2 weeks for
presentation

• 1. Website for selling sports gears.


• 2. Website for army recruitment
• 3. Website for Navrongo Prison
• 4. Website for Library (borrowing of books)
• 5. Website for registering birth and deaths.

Web Application Development with Shiny in R (RStudio)


To be continued...
• Download RStudio from http://cran.r-project.org.
• Install Shinny using install.packages(“shiny”)
• Run some of the examples:

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.

• fluidPage( ) creates a display that automatically adjusts to the dimensions of your


browser window.
Dr. P. K. Mensah
Page 30 of 52
• You lay out your app by placing elements in the fluidPage( ) function.

• Output:

• sidebarLayout( ) always takes two arguments:


o sidebarPanel( ) function output
o mainPanel( ) function output
• These functions place content in either the sidebar or the main panels.
• The sidebar panel will appear on the left side of your app by default.
• You can move it to the right side by giving sidebarLayout() the optional argument
position = "right".

• 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.

Adding HTML Content


• Add content to your Shiny app by placing it inside a *Panel() function.
o eg. sidebarPanel("sidebar panel")
• To add more advanced content, use one of Shiny’s HTML tag functions:

• 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")

• TRY: Use shiny to produce the page below

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.

• We need a ui.R and server.R files in the folder census-app.


• Shiny provides a family of functions that turn R objects into output for your user-
interface.

• 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.

• Each render* function takes a single argument: an R expression surrounded by braces,


{}.
• The expression can be one simple line of text, or it can involve many lines of code.
• If you run the server.R script above, the Shiny app will display “You have selected this”
in the main panel.
o not reactive yet.
• To make it reactive, call a widget value when it builds the text.
• The unnamed function in server.R mentions two arguments, input and output.
o output is a list-like object that stores instructions for building the R objects in
your app.
o input is a second list-like object.
▪ It stores the current values of all of the widgets in your app.
▪ These values will be saved under the names that you gave the widgets in
ui.R.
• Eg. Your app has two widgets, one named “var” and one named “range”.
• The values “var” and “range” will be saved in input as input$var and input$range.
• Since the slider widget has two values (min and max), input$range will be a vector of
length two.
Dr. P. K. Mensah
Page 43 of 52
• If an object uses an input$ value, Shiny will automatically make it reactive.
• Eg. the server.R file below creates a reactive line of text by calling the value of the select
box widget to build the text using input$var
o —note that var is the variable for the selectInput widget.

• 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

o the name of each county in the United States


o the total population of the county
o the percent of residents in the county who are white, black, hispanic, or Asian
o Download the data from http://shiny.rstudio.com/tutorial/lesson5/census-
app/data/counties.rds

• helpers.R is an R script that can help you make choropleth maps.


o A choropleth map is a map that uses color to display the regional variation of a
variable.
o In our case, helpers.R will create percent_map, a function designed to map the
data in counties.rds.
• Download from http://shiny.rstudio.com/tutorial/lesson5/census-app/helpers.R
• helpers.R uses the maps and mapproj packages in R.
• If you’ve never installed these packages before, you’ll need to do so before you make this
app.

• Run
• Save helpers.R inside your census-app directory.
• The percent_map function in helpers.R takes five arguments:

• Load helpers.R using


Dr. P. K. Mensah
Page 47 of 52
• Load the dataset with

• 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/

Share your apps


• You have two basic options:
o Share your Shiny app as two files: server.R and ui.R.
▪ This is the simplest way to share an app, but it works only if your users
have R on their own computer.
▪ Your user can place the files into an app directory in their working
directory. They can launch the app in R with the same commands you
used on your computer.

o Share your Shiny app as a web page:


• Shiny has three built in commands that make it easy to use files that are hosted online:
runUrl, runGitHub, and runGist.
• runUrl will download and launch a Shiny app straight from a weblink.

• To share an app through Github, create a project repository on Github.


o Then store your server.R and ui.R files in the repository, along with any
supplementary files that the app uses.
• Your users can launch your app by running:

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.

Share as a web page


• http://shiny.rstudio.com/tutorial/lesson7/

=========================================================
Eg. Shiny app to calculate the area of a Triangle:

ui.R

Dr. P. K. Mensah
Page 51 of 52
server.R

Dr. P. K. Mensah
Page 52 of 52

You might also like