Вы находитесь на странице: 1из 121

The function of ci code to return a URI segment

$this->uri->segment

It is a URI Component that serve as persistent, location-independent identifiers


URN

The default file extension for PHP file is ".php"


True

Answer PHP version that uses void return type, class constant visibility modifiers, null

types.
7.1

PHP is one of the most widely used and recognizable web technology used on the Internet.
True

PHP 3 was released in 1998.


True

URN stands for?


Uniform Resource Name

The function or ci code to show or call the client-side "non-existing page" error
show_404()

PHP development began in 1995.


False

The first URI segment


Controller

The third URI Segment


Parameter

The page that displays a message that the requested page was not found.
Error 404

Andi Gutmans was the inventor of PHP.


False

The second URI segment


Method

URI stands for?


Uniform Resources Identifier

Answer What functionality was added to PHP 5.1 as interface for accessing databases?

PDO

It is the process of redirecting or remapping a controller class or method.


Routing

Answer Year that PHP was officially called Personal Home Page Tools.

1995

Answer Version of PHP that uses namespace support late static binding.

5.3

Answer Version of PHP that introduces the use of superglobals.

4.1

CI function code to load the database class.


$this->load->database();

Element can be placed onto a web page in a pre-checked fashion by setting the checked attribute.
Checkbox

CI method or code that display/echo error messages when form_validation->run() returns false.
Validation_errors()

It is a line that is not read/executed as part of the program.


Comment

CI method or code to set an error message in form validation.


$this->form_vaidation->set_message()

Query Builder class method that inserts record on the database.


$this->db->insert()

row_array() fetch the data as a single row and result_array() fetch the data as a multi-
dimensional array.
True

_construct() method executes when a class is created or instantiated.


True

PHP varianbles start with what symbol?


$

CI file directory where the database configuration settings and database groups is found.
Application/config/database.php

CI file directory where autoload classes and functions are defined.


Application/config/autoload.php

A variable declared within a function.


Local

Storage data in PHP


Variables

Define styles for your documents, including the design, layout and variations in display for
different devices and screen sizes.
CSS

A variable declared outside a function.


Global

Query Builder or Active Record pattern in CI replaces the traditional query string in php coding.
True

CI method or code to load the form validation library.


$this->load->library('form_validation')

These are functions which are passed to another function and takes this "other function" as a
parameter.
Callbacks

CI method or code to set a rule in form validation.


$this->form_validation->set_rules()

Form Helper method or code to return an HTML checkbox input type.


form_checkbox()
Matching Type. Choose the correct answer from the selection provided.

PHP’s superglobal type of variables that can


be accessed anywhere on the web Answer 1
application because it is stored on the SESSION VARIABLES
browser session.
A session variable name that checks if the Answer 2
user has privileges to the page. islogged

It is an algorithm that is used in security


Answer 3
hashing that transforms data into a 128 bit
MD5
string.
These are session variables that are only Answer 4
available until the next request. FLASHDATA

CI method or code to remove a session Answer 5


variable. $this->session->unset_userdata(‘item’)

CI method or code to create a session Answer 6


variable. $this->session->set_userdata(‘item’, ‘value’)

CI method or code to load the session Answer 7


library. $this->load->library('session')

MySQL function to hash data into a 128 bit Answer 8


string. MD5()
CI method or code to access a session Answer 9
variable. $this->session->userdata(‘item’)

These are session variable that expires Answer 10


within a given time. TEMPDATA

.htaccess file that will automatically route the index.php next to the Controller
True
CI uses Model-Viewable-Controller architecture

False
To load the view, the function is like this: $this->load->view('name');
True
is the process of redirecting or remapping a controller class or method.
routing
CI, basically contains 4 main folders Application, System, User, Help Guide

False
variables are just like session variables except it is only available on the next request.
Flashdata
URI is the historical name that serve as persistent, location-independent identifiers allowing the
simple mapping of namespaces into a single URN namespace

False
What do you call the 3rd, 4th segment of the URI?
Parameters
Controller is also knows as the data access layer.

False
HTML is a requirement in Code igniter
True
IDENTIFICATION: What do you call the 1st segment of the URI?

Controller
Meaning of URN
Uniform resource name
Data Access Layer or Persistence Layer of the MVC Layered Architecture.

Model
functions to help you build your form easier and faster.
Form helper
Meaning of URL.

Uniform resource locator


CodeIgniter is developed PHP.org
False
Segment is the process of redirecting or remapping a controller class or method.

False
are function that is passed to another function and takes this "other function" as a parameter
callbacks
will be loaded by the controller passing the returned data from the model.

URI stands for Uniform Resource Identity


False

Answer 1
It can be said as the entry point of application.
Controller

Variables that can be accessed anywhere on the web application Answer 2


because it is stored on the browser session superglobal

Answer 3
Organization that sponsors CI
Ellislab

Answer 4
You can display the error 404 page by using what function
show_404()

Answer 5
What function can be used to access session variables on webpages?
session_start()

Answer 6
Function that fetch the data as a multi-dimentional array
result_array()

Answer 7
variables are session variables that expires with a given time limit.
Tempdata

Answer 8
Method will execute codes once the class is created or instantiated.
__construct

Answer 9
Function that fetch the data as a single row array
row_array()

File that will automatically route the index.php next to the Controller Answer 10
Form helper class helps us by returning formatted HTML form elements.

True
Method that accepts 'secondary recipients' that receives the mail just to keep them informed
matches form validation rule checks 3 fields that should have an equal or same value.
False
It is any process or technology that allows users who forgot their passwords authenticate and reset
the passwords of their account

Forgot password
Method that accepts the recipient's email address

An input required to verify the user's record existence in order to reset his/her password.

Method that accepts the email's body or content

Method that accepts the email's title or heading text

Method that returns a string containing any server messages, email header and email message.

Method that returns a string containing any server messages, email header and email message.

$this->db->insert_id() inserts an id in the database.


False
Web Development

Module 6– Log-in and Log-out using Session Library

Topics
Introduction .................................................................................................................................. 2

Session Variables........................................................................................................................... 2

Loading the Session Library ........................................................................................................... 2

Creating Session Variables in CI ..................................................................................................... 3

Accessing Session Variables ........................................................................................................... 3

Removing Session Data ................................................................................................................. 4

Log In using CI Session ................................................................................................................... 4

Log Out ........................................................................................................................................ 10

Learning Objectives

At the end of the module the student is expected to:

1. Understand the concept of sessions variable.

2. Identify the syntax in creating, loading and removing session variable in CI.

3. Apply the commands needed in creating, loading and removing sessions in CI.

4. Create CI application showing the codes.

Module 6 – Log-in and Log-out using Session Library 1


Web Development

Introduction

Session Variables

We already know that sessions in native PHP are the “superglobal” variables that can be

accessed anywhere on the web application because it is stored on the browser session. They can be set

and accessed like any ordinary variables except that it uses the $_SESSION.

In order to use and access session variables on webpages, we must put the session_start()

function. The unsetting of the variable can be done by using unset() function on variables or

session_destroy() to erase all existing session variables.

CodeIgniter improve the utilization of session variables on its Session Library. It contains

different session methods with different functionalities to help us speed up the task and simplify coding.

There were the improved session variables, flashdata and tempdata. The only new here is the flashdata

and tempdata. Flashdata are session variables that are only available until the next request. If the same

webpage is requested, the flashdata will not be present as it expires on the first request. The Tempdata

are just like ordinary session variables but expires in the defined seconds. Flashdata and Tempdata were

previously discussed and used on our last chapter to help us display success or failed status messages.

Loading the Session Library

There are two ways to load CI’s session library.

You can load it in inside the controller’s constructor or on its methods by:

$this->load->library(‘session’)

or if you will frequently use it, make it autoloaded by adding the ‘session’ library in the library

array at application/config/autoload.php on line 61.

Module 6 – Log-in and Log-out using Session Library 2


Web Development

Creating Session Variables in CI

You can declare your own session variable on the $_SESSION superglobal but for the sake of this

tutorial on CodeIgniter, let CI do their thing because it’s much more simplified and structured. When the

session library is loaded, you don’t need to write session_start all over and over again, just declare the

session variable using $this->session->set_userdata()

Example:

Or pass an associative array with its field_name and value pattern.

Example:

Note: $this->session->set_userdata() is also used to set or change an existing session variable value.

Accessing Session Variables

To use or access session variables and its value, you may use the userdata() method.

Example when you have ‘item’ session variable name, you’ll use:

$this->session->userdata(‘item’)

or simply call:

$this->session->item

Module 6 – Log-in and Log-out using Session Library 3


Web Development

or basically call the $_SESSION superglobal:

$_SESSION[‘item’]

Removing Session Data

When you no longer need the session variable you have set, you can remove it

by using $this->session->unset_userdata()

Example you have ‘item’ session variable set, unset it by:

$this->session->unset_userdata(‘item’)

Or unset a session array:

$session_array = array(‘name’, ‘user_level’);

$this->session->unset_userdata($session_array)

Similarly, you can use native PHP’s unset() function on $_SESSION superglobals:

unset( $_SESSION[‘item’] )

Unsetting multiple variables:

unset( $_SESSION[‘item1’], $_SESSION[‘item2’] )

Log In using CI Session

User access and restriction is one of the must-need functionality of any website applications.

Log In modules are needed to limit users from accessing off-limits and restricted webpages or content.

Websites with database interactivity provide users to gain access to its backend or Administration Panel.

Module 6 – Log-in and Log-out using Session Library 4


Web Development

We’ll use the ‘users’ table

user_id user_name user_pass user_accountname

1 admin admin Administrator

2 dustin 12345 Leon Dustin

For the sake of security, we need to encrypt the user_pass column with md5. Use the md5()

function in your query when inserting passwords. MD5 is an algorithm that is used in security hashing

that transforms data into a 128 bit string. It is claimed that every encrypted string is as unique as

fingerprint.

MySQL query:

Updated ‘users’ table

user_id user_name user_pass user_accountname

1 admin 21232f297a57a5a743894a0e4a801fc3 Administrator

2 dustin 827ccb0eea8a706c4c34a16891f84e7b Leon Dustin

Create the Login Controller at application/controllers/Login.php with the below code:

Module 6 – Log-in and Log-out using Session Library 5


Web Development

Provide the login view at application/views/login.php:

The Log In form that accepts username and password. The form uses Form Helper to return

HTML Form elements. When the form is submitted, the post variables will be sent to the verify method of

the Login controller class.

Output:

Module 6 – Log-in and Log-out using Session Library 6


Web Development

Add the verify method on the Login controller with Form Validation:

We have set a required rule on both fields and a callback_check_user on the password field. This

callback will check the user if it exists. If the fields passed the validation, the page will be redirected to

the Home controller where only authorized or logged-in users can access.

Within the same controller, add the callback method check_user:

The login method of the Login Model will check the user if the username and password

parameters matched a record from the database. If it finds one, it will prepare our session variables for

logging in and will pass the callback_check_user form validation rule.

The islogged session variable will determine whether the user record is authenticated and will

be used on all user restricted webpages.

Module 6 – Log-in and Log-out using Session Library 7


Web Development

The Login model at application/models/login_model.php:

The login method will check the username and password parameters if it exists on the ‘users’

table and will return the login details.

After the Login functionality that checks allowed users, let’s create the landing page after the

logging in process. Create the Home controller at application/controllers/Home.php:

Module 6 – Log-in and Log-out using Session Library 8


Web Development

The Home controller and its method is exclusively for registered users. At the constructor

method, we need to include a condition that checks if the user has privileges on the page using the

islogged session variable. If not, they will be redirected back to the login page.

The homepage view at application/views/home.php:

This will display the user’s account name and a link for logging out

Output:

Module 6 – Log-in and Log-out using Session Library 9


Web Development

Log Out

For the Logout controller at application/controllers/Logout.php:

To logout a user, all we need to do is unset the session variable that keeps us in: the islogged

variable. To keep it neat, we have to unset all of our session variables and redirect back to Login

controller.

Module 6 – Log-in and Log-out using Session Library 10


Web Development 1
PHP and HTML FORMS

Introduction to PHP
Learning Objectives

At the end of the module the student is expected to:

1. Create PHP pages using


a. html forms;
b. select tags;
c. text area;
d. option / radio buttons;
e. checkbox tags
2. Understand the application of assigning values to variables and
appending text in PHP scripts.

HTML FORMS

In this section we will now explore the use of HTML forms.

HTML Forms

HTML Form are one of the main points of interaction between


a user and a web site or application. They allow users to send data to
the web site.

Here is the HTML output using


HTML form. The user is asked to
input his/her first name. After
the inputting the needed the
data, the user can now press the
Submit information button.

For the code refer to:


11html_forms.html

Course Module
Web Development 2
PHP and HTML FORMS

Here is the result of the data


submission, the users first name
is now displayed.

For the code refer to:


11html_forms.php

Here is the css code.

CSS define styles for your


documents, including the design,
layout and variations in display
for different devices and screen
sizes.

Filename: basic.css

Note: This is needed in the


succeeding codes.

Course Module
Web Development 3
PHP and HTML FORMS

This is the html code for the


form.

The variable name to be passed


to the php file.

Filename: 11html_forms.html

This is the PHP code. The


variable firstname is now dispay
here. Using the $_POST is
allowed us to collect data from
the htm file and display to the
php script.

Course Module
Web Development 4
PHP and HTML FORMS

USING SELECT Tag

The HTML select (<select>) element represents a control that


presents a menu of options. The options within the menu are
represented by <option> elements, which can be grouped
by <optgroup> elements. Options can be pre-selected for the user.

Here is the HTML output using


SELECT tag. The user is asked to
input his/her first name. After
the inputting the needed the
data, the user can select from the
dropdown list and press the
Submit information button.

For the code refer to:


12select_tag.html

Here is the result of the data


submission, the users first name
and position is now displayed.

For the code refer to:


12using_select.php

Course Module
Web Development 5
PHP and HTML FORMS

This is the html code for the


form.

Here the html form will contain a


textbox, and a dropdown list
showing the Administrator,
Faculty and Staff option.

Filename: 12Select_tag.html

This is the PHP code.


The variable $firstname and
$position stores the result from
the html page.

Filename: 12Using_Select.php

Course Module
Web Development 6
PHP and HTML FORMS

USING TEXT AREA TAG

The <textarea> tag defines a multi-line text input control.


A text area can hold an unlimited number of characters, and the text
renders in a fixed-width font (usually Courier). The size of a text
area can be specified by the cols and rows attributes, or even better;
through CSS' height and width properties.

Here is the HTML output using


Text Area tag. The user is asked
to input his/her first name. After
the inputting the needed the
data, the user can input a series
of text in the text area and press
the Submit information button.

For the code refer to:


13using_textarea.html

Here is the result of the data


submission, the users first name
and the comment is now
displayed.

For the code refer to:


13using_textarea.php

Course Module
Web Development 7
PHP and HTML FORMS

This is the html code for the


textarea.

Here the html form will contain a


textbox, and a textarea where
the user can input series of text.

Filename: 13using_textarea.html

This is the PHP code.


The variable $firstname and
$comment stores the result from
the html page.

Filename: 13using_textarea.php

Course Module
Web Development 8
PHP and HTML FORMS

USING OPTION / RADIO BUTTON TAG

Option buttons are sometimes called Radio Buttons, and they


force the user into choosing only one item in a list, such as a
Male/Female option, or selecting a payment method.

Here is the HTML output using


Option / Radio button. The user
is asked to input his/her first
name. After the inputting the
needed the data, the user can
now select from the employee
type and press the Submit
information button.

For the code refer to:


14using_radiobuttons.html

Here is the result of the data


submission, the users first name
and the employee type selected.

For the code refer to:


14using_radiobuttons.php

Course Module
Web Development 9
PHP and HTML FORMS

This is the html code for the


radio button.

Here the html form will contain a


textbox, and a option/radio
button where the user can select
type of employee

Filename:
14using_radiobuttons.html

This is the PHP code.


The variable $firstname and
$etype stores the result from the
html page.

Filename:
14using_radiobuttons.php

Course Module
Web Development 10
PHP and HTML FORMS

USING CHECKBOX TAG

Checkbox elements in a situation when the user must check all


boxes that apply (or none). A checkbox element can be placed onto a
web page in a pre-checked fashion by setting the checked attribute
with a "yes" value. By doing so, this element will now default to a
checked status each time the HTML page is loaded.

Here is the HTML output using


checkboxes. The user is asked to
input his/her first name. After
the inputting the needed the
data, the user can now select
from the different degree
received and press the Submit
information button.

For the code refer to:


15using_checkboxes.html

Here is the result of the data


submission, the users first name
and the degree earned.

For the code refer to:


15using_checkboxes.php

Course Module
Web Development 11
PHP and HTML FORMS

This is the html code for the


checkbox application.

Here the html form will contain a


textbox, and series of
checkboxes where the user can
select types of degree received.

Filename:
15using_checkboxes.html

This is the PHP code.


The variable $firstname and
several variables $BA, $MA,
$PHD, upon selection the
appropriate condition will be
displayed. The coded also uses
the isset() function that is used
to check whether a variable is set
or not.

Filename:
15using_checkboxes.php

Course Module
Web Development 12
PHP and HTML FORMS

ASSIGNING VALUES TO VARIABLES

In this section, it will illustrate how to have several inputs and


assign the output to variables to be displayed.

The HTML form contains 3 text


boxes, the user can input the
firstname, lastname and age.
Upon completion the result will
be displayed in the php file what
will have some operations.
Submit information button will
send information to the php file

For the code refer to:


16assigning_values.html

Here is the result of the data


submitted by the user. The
collected data are as follows,
firstname, lastname and age.

For the code refer to:


16assigning_values.php

Course Module
Web Development 13
PHP and HTML FORMS

This is the html code for the


assigning value application

Here the html form will contain


3 textboxes, and user must
supply data such as lastname,
firstname and age. Upon
submission the resulting values
will be send to the php script..

Filename:
16assigning_values.html

Upon submission of data from


the html file, the php script will
receive 3 variables firstname,
lastname and age.

The script will compute the age


by factor of 10 and add it to the
current age, it will also compute
the birth year by subtracting the
current_year with the ageplus
variable.

After the operation the results


are display in the browser using
the echo function.

Filename:
16assigning_values.php

Course Module
Web Development 14
PHP and HTML FORMS

APPENDING TEXT

In this section, you will learn how to append additional


variables to text.

The HTML form contains 3 text


boxes, the user can input the
firstname, lastname and age.
Upon completion the result will
be displayed in the php file what
will have some operations.
Submit information button will
send information to the php file

For the code refer to:


17appending_text.html

Here is the result of the data


submitted by the user. The
collected data are as follows,
firstname, lastname and age.

The script also appends values to


the existing input text supplied
by the user.

For the code refer to:


17appending_text.php

Course Module
Web Development 15
PHP and HTML FORMS

This is the html code for the


assigning value application

Here the html form will contain


3 textboxes, and user must
supply data such as lastname,
firstname and age. Upon
submission the resulting values
will be send to the php script..

Filename:
17appending_text.html

Upon submission of data from the


html file, the php script will receive
3 variables firstname, lastname and
age.

The script will compute the age by


factor of 10 and add it to the current
age, it will also compute the birth
year by subtracting the current_year
with the ageplus variable. It will aso
add the middle_init value to the
input text using the (.) operator.

After the operation the results are


display in the browser using the
echo function.

Filename: 17appending_text.php

Course Module
Web Development 16
PHP and HTML FORMS

Course Module
Web Development 17
PHP and HTML FORMS

References
Murach, J. (2014) Murach’s PHP and MYSQL (2nd Edition)

Yank, K, PHP and MYSQL: Novice to Ninja

WEBSITE

http://php.net/

http://www.w3schools.com/php/

https://www.tutorialspoint.com/php/

Course Module
Web Development 1
PHP Basics

PHP Basics
Learning Objectives

At the end of the module the student is expected to:

1. Understand how to use PHP Syntax


2. Understand and apply comments in PHP codes.
3. Understand the concept of case sensitivity in PHP codes.
4. Understand the use of variables.
5. Understand and apply the use of echo and print statements
6. Understand the concept of data types and use it in PHP programs
7. Apply string concatenation

INTRODUCTION

In the previous module, we have learned how to install and run


PHP for the first time. In this module we will learn PHP basics such as
syntax, comments, variables and more.

PHP BASICS

PHP Syntax

To embed PHP code, you must use the following syntax.

php
// PHP code goes here
?>

Every time you want to use php scripts, the codes must be
enclose inside <?php ?> , all codes that are place inside the php block
are read by the php.

PHP Comments

Course Module
Web Development 2
PHP Basics

A comment in PHP code is a line that is not read/executed as


part of the program. Its purpose is to provide information or details to
the codes.

The following are the use of comments.

1. Let developers understand the code you are writing.


2. Serves as a reminder.

Sample Code:
Filename: 02basics_adding_comments.php

The code shows the use of


including comments into a PHP
code.

It helps the user identify the


functions/commands included in
the program.

Here is the output of the


program that add comments to
the PHP code. All comments are
hidden to the user, its only
viewable in the code.

PHP Case Sensitivity

In PHP, all keywords (e.g. if, else, while, echo, etc.), classes,
functions, and user-defined functions are NOT case-sensitive. In the
example below, all three echo statements below are legal (and equal):

Course Module
Web Development 3
PHP Basics

Sample Code:
Filename: 03case_sensitivity.php

The code shows the use of case


sensitivity of PHP commands

here is the result of the html


code, it still display the text hello
world even with different case of
the command ECHO.

Note: all variable names are case-sensitive. In the example below, only
the first statement will display the value of the $color variable (this is because
$color, $COLOR, and $coLOR are treated as three different variables):

Course Module
Web Development 4
PHP Basics

Sample Code:
Filename: 04case_sensitivity.php

The code shows the use of


variables and its case sensitivity.

Since, the only declared variable


is $color, the remaining
variables $COLOR and $coLOR
are not recognized by PHP so it
resulted an error.

PHP Variables

A variable can have a short name (like x and y) or a more descriptive


name (age, carname, total_volume).

Rules for PHP variables:

 A variable starts with the $ sign, followed by the name of the


variable
 A variable name must start with a letter or the underscore
character
 A variable name cannot start with a number
 A variable name can only contain alpha-numeric characters and
underscores (A-z, 0-9, and _ )
 Variable names are case-sensitive ($age and $AGE are two
different variables)

Course Module
Web Development 5
PHP Basics

Note: Remember that PHP variable names are case-sensitive

Sample Code:
Filename: 05_PHP_Variables.php

The code below shows the use of


variables in PHP.

Here is result of the code that


uses variables.

PHP is a Loosely Typed Language

PHP automatically converts the variable to the correct data type,


depending on its value. In other languages such as C, C++, and Java, the
programmer must declare the name and type of the variable before
using it.

Course Module
Web Development 6
PHP Basics

PHP Variables Scope

In PHP, variables can be declared anywhere in the script. The


scope of a variable is the part of the script where the variable can be
referenced/used.

PHP has three different variable scopes:

 Local - A variable declared within a function has a LOCAL SCOPE and


can only be accessed within that function
 Global - A variable declared outside a function has a GLOBAL SCOPE
and can only be accessed outside a function
 Static - a static variable will not lose its value when the function exits
and will still hold that value should the function be called again.

PHP 5 echo and print statements

In PHP there are two basic ways to get output: echo and print.
echo and print are more or less the same. They are both used to output
data to the screen. The differences are small: echo has no return value
while print has a return value of 1 so it can be used in expressions. echo
can take multiple parameters (although such usage is rare) while print
can take one argument. echo is marginally faster than print.

PHP Data Types

Variables can store data of different types, and different data


types can do different things. PHP supports the following data types:

 String
 Integer
 Float (floating point numbers - also called double)
 Boolean
 Array

Course Module
Web Development 7
PHP Basics

The code below shows the


application on the use of
variables in PHP.

This example shows the


application of integer, float
variables.

Filename:
06_Variables1.php

Here is the result of using


variables

Course Module
Web Development 8
PHP Basics

The code shows the use of string


in PHP.

Filename:
07_Variables2.php

Here is the result on using string


variables.

Course Module
Web Development 9
PHP Basics

In this code, shows the


application of variables, it also
show the use of conditional
statement if..else.

Filename:
08_Variables3.php

Here is the result of the


condition. Since the variable
$validUser is set to True, the
output is “User is Valid”.

In the second variable


declaration the $validUser is
now set to False. Now the
output of the code is User is NOT
Valid.

Course Module
Web Development 10
PHP Basics

The code shows the data type of


the variables.

To show the data type, you can


use var_dum();

The var_dump() function is used


to display structured
information (type and value)
about one or more variables.

Filename:
09_Variables3.php

The code snippet shows the data


type of the variable use.

Course Module
Web Development 11
PHP Basics

String Concatenation

The PHP concatenation operator (.) is used to combine 2 sting


values to create one string.

In this code, there are variables


that shows the address of a
person, to combine the address
we use the (.) operator to
concatenate the string

Filename:
10_String_Concatenation.php

Here is the output of the string


concatenation.

Course Module
Web Development 12
PHP Basics

References
Murach, J. (2014) Murach’s PHP and MYSQL (2nd Edition)

Yank, K, PHP and MYSQL: Novice to Ninja

WEBSITE

http://php.net/

http://www.w3schools.com/php/

https://www.tutorialspoint.com/php/

Course Module
Web Application Development 2
1
Views

Views

At the end of the module the student is expected to:


1. Understand and apply the concept of views in CI.
2. Know how to pass data using views in CI.
3. Understand the use of URI and apply its use in CI.
4. Identify the URI segments.
5. Use .htaccess to remove index.php
6. Understand the concept of routing and its parameters
7. Use CI 404 page for error page.

Introduction
A view is simply a web page, or a page fragment, like a header, footer,
sidebar, etc. Views serves as User Interfaces where web users can interact,
request and receive data. Controllers can load views and pass data to them

Creating Views
Views are php files containing html elements. They are stored in
application/views folder. Lets have an example of a view. Create a file place
it at application/views/ and give it a name index.php. now type the following
codes.

Now we need to load the index.php (view) to our controller. To load the view
we need go to the controller, name the file as Home.php directory should be
like this: application/controllers/Home.php

Course Module
To load the view, the function is like this $this->load->view('name'); the
name is the name of the view file, in our example to load the view you type
$this->load->view(‘index’);
To test it out, go to http://localhost/index.php/Home. This should output:

Passing Data to View


Views are used to present data. Most data passed in a view are from the
controller or model (from the database). Data can be a string value, an array
or an object. $this->load->view method has an optional second parameter,
which is the data to be passed.
$this->load->view(‘view_file_name’, $data);
All you need is to define an array or array index to be passed. If you know
what php extract function does, the passed array from the controller is
automatically extracted when passed on a view. The associated array names
turn into variables.
Example:

Controller View

$data[“greeting”] = “Hello World”; //some_page.php


<?php
$this->load->view(‘some_page’, echo $greeting;
$data); ?>
//outputs:
//Hello World

$data = array( //some_page.php


‘lname’ => ‘Juan’, User: <?php echo $lname.’,
‘fname’ => ‘Cruz’ ’.$fname; ?>

);
//outputs:
//User: Cruz, Juan
$this->load->view(‘some_page’,
$data);

Let’s pass some data to our index.php view Update the index method on the
Home controller: Don’t forget the second parameter $data.
Web Application Development 2
3
Views

And also to our index view:

In this way, our title will be dynamic by using the $title variable.
Output:

Notice that our Title Bar show our passed $data[“title”] from our Controller
to our view using $title.

Passing More Data


Let’s pass more values from our controller using Arrays. Arrays are like
variables. Array store multiple values or elements that can be accessed by its
index or position. Arrays can be Indexed (numerical positions starting with
0), Associative (or named positions), and multi-dimensional (arrays within
array).
Say we have an array of products on our controller
application/controller/Products.php

Course Module
$data is an associative array containing the key products with array values:
Spaghetti, Baked Mac, Fettucine, Lasagna and the key title contains “Products”
string for our <title>
And displays it on our view at application/views/products.php

The $data array from the Products controller was extracted to our view. It will
simply display the $title inside the <title> tag and loop our $products array
values into our <ul> (unordered list).
If you want to pass more values on variables or array, just store it on
$data associative array on the controller’s method and don’t forget to $this-
>load->view(‘your_view’, $data) with $data as the second parameter.
Example:
$data[“num_of_products”] = count(array('Spaghetti', 'Baked Mac',
'Fettucine', 'Lasagna'));
$data[“date_today”] = date(‘F d, Y’);
Output:

The array values are loaded by the foreach loop.


Web Application Development 2
5
Views

Understanding URI
What is URI? URI stands for Uniform Resource Identifier. It is a string of
characters used to identify a resource. URL (Uniform Resource Locator) and
URN (Uniform Resource Name) are forms of URI.

Location (URL)
URI

Name (URN)

URI, URL and URNs


To make it easier to understand, for an example, there was Juan Dela Cruz as
our given URN. There are many Juan Dela Cruz in the country, thus we need
to know whose Juan dela Cruz of what place or address are we looking for.
When you are searching for Juan Dela Cruz of Bulacan, it is now URL. Did you
get the idea? URN can be of any given name or address. We use URL to define
what method and address is the requested web page. The combination of
both URL and URN resource is what we call specifically URI.

URL URN

https://facebook.com.com/dustoutlaw23 /profile/dustoutlaw23

https://www.youtube.com/channel/UCNHX /channel/UCNHXyYCEqfm
yYCEqfmO8jBTlbFvLHA O8jBTlbFvLHA

URL is the location that includes the components: the path/method and the
domain. It is basically called Web Address. URN is the historical name that
serve as persistent, location-independent identifiers allowing the simple
mapping of namespaces into a single URN namespace.

URI Segments
URI segments in CodeIgniter:
http://www.websitedomain.com/controller/method/param1/param2...

1 2 3 4
After the domain name, the controller comes the 1st segment of the URI. The
second follows the method. The 3rd, 4th and so on are the parameters. These

Course Module
parameters are mostly required by the method, it can be used as control,
settings or input.
Examples:
products/view/3 Viewing Product with the id 3
salary/calculate_daily_gross/8/100 Calculating daily gross salary with
8 hrs worked and with the pay rate
of 100 per hour
To get the uri segments on the address bar, we will use $this->uri-
>segment(n) where n is the requested segment position number.
Example:
http://suzuki.com.ph/motors/motorcycles/big-bikes/bandit-650/
Code Return String
$this->uri->segment(1) motors
$this->uri->segment(2) motorcycles
$this->uri->segment(3) big-bikes
$this->uri->segment(4) bandit-650
To see how it works, add the spaghetti method on our Products controller:
application/controlers/Products.php

$this->uri->segment() method of the URI Class is automatically loaded in CI.


With this URL/web address instance,

It will output:

Removing Index.php
http://localhost/index.php/controller/method/param
This makes our URL longer that it consumes space. Why not remove it to
make it cleaner? We are not referring all of our pages in a single php file and
by that it looks more confusing.
The Answer? Create an .htaccess file that will automatically route the
index.php next to the Controller
Web Application Development 2
7
Views

Create the .htaccess file

Save it to your server’s root directory or your project’s directory

You can now type in the URL without the index.php! (e.g.
http://localhost/controller/method/param)

Routing
For a quick review, here’s an example of CodeIgniter URL:
http://www.websitedomain.com/controller/method/param1/param2...
And also you can do this:
http://www.websitedomain.com/profile/dustin
Instead of:
http://www.websitedomain.com/profile/view/23

controller method parameter value


This is how routing works, instead of requesting an address with controller-
method-params relationship, you can request a specific address as alias or
redirect (re-route) to a different controller. Routing is the process of
redirecting or remapping a controller class or method. Defining or creating
your own routing rules are set in the CI’s application/config/routes.php file.
Constructing a routing rule uses wildcards or regular expression.
Examples:

Course Module
$route[“bikes”] = ‘motorcycles’;
A URL that contains ‘bikes’ as controller will be remapped to ‘motorcycles’
controller class
$route[“profle/dustin”] = ‘profile/view/23’;
A URL containing the first segment ‘profile’ and second segment ‘dustin’ will be
rerouted to ‘profile’ controller, to the view method and to the profile id.
$route[“bikes/(:any)”] = ‘motorcycles/bike_lookup’;
A URL that contains any character or word on the second segment will be
redirected to ‘motorcycles’ controller class and bike lookup method as it will
search the motorcycle database for any given word or character.
$route[“bikes/(:num)”] = ‘motorcycles/view/$1’;
A URL that contains the ‘bikes’ controller associated with any number will be
readdressed to the ‘motorcycles’ controller and will trigger the ‘view’ method
and will accept the given number as a parameter value.

Setting the Default Controller


$route['default_controller'] = 'welcome';
By default, its value is the CodeIgniter’s welcome controller class. When a
URI segment or Controller class is not present, CI will load its default
controller configuration at application/config/routes.php file.

404 Page
Have you ever encountered “Error 404: Page not found”? This happens when
you try to reach a webpage but could not be found on the server. This can be
because you typed In the URL incorrectly, the URL was moved or it does not
exist. CodeIgniter allows you to show this client-side error and use it to catch
errors on your code intentionally or not.
When an Error 404 is met, application/views/errors/html/error_404.php file
is shown. Now you know where to customize this error In CodeIgniter.
You can display the error 404 page by using the function show_404() in the
controller method.
Example:

References
Web Development 1
PHP and HTML FORMS

Introduction to PHP
Learning Objectives

At the end of the module the student is expected to:

1. Create PHP pages using


a. html forms;
b. select tags;
c. text area;
d. option / radio buttons;
e. checkbox tags
2. Understand the application of assigning values to variables and
appending text in PHP scripts.

HTML FORMS

In this section we will now explore the use of HTML forms.

HTML Forms

HTML Form are one of the main points of interaction between


a user and a web site or application. They allow users to send data to
the web site.

Here is the HTML output using


HTML form. The user is asked to
input his/her first name. After
the inputting the needed the
data, the user can now press the
Submit information button.

For the code refer to:


11html_forms.html

Course Module
Web Development 2
PHP and HTML FORMS

Here is the result of the data


submission, the users first name
is now displayed.

For the code refer to:


11html_forms.php

Here is the css code.

CSS define styles for your


documents, including the design,
layout and variations in display
for different devices and screen
sizes.

Filename: basic.css

Note: This is needed in the


succeeding codes.

Course Module
Web Development 3
PHP and HTML FORMS

This is the html code for the


form.

The variable name to be passed


to the php file.

Filename: 11html_forms.html

This is the PHP code. The


variable firstname is now dispay
here. Using the $_POST is
allowed us to collect data from
the htm file and display to the
php script.

Course Module
Web Development 4
PHP and HTML FORMS

USING SELECT Tag

The HTML select (<select>) element represents a control that


presents a menu of options. The options within the menu are
represented by <option> elements, which can be grouped
by <optgroup> elements. Options can be pre-selected for the user.

Here is the HTML output using


SELECT tag. The user is asked to
input his/her first name. After
the inputting the needed the
data, the user can select from the
dropdown list and press the
Submit information button.

For the code refer to:


12select_tag.html

Here is the result of the data


submission, the users first name
and position is now displayed.

For the code refer to:


12using_select.php

Course Module
Web Development 5
PHP and HTML FORMS

This is the html code for the


form.

Here the html form will contain a


textbox, and a dropdown list
showing the Administrator,
Faculty and Staff option.

Filename: 12Select_tag.html

This is the PHP code.


The variable $firstname and
$position stores the result from
the html page.

Filename: 12Using_Select.php

Course Module
Web Development 6
PHP and HTML FORMS

USING TEXT AREA TAG

The <textarea> tag defines a multi-line text input control.


A text area can hold an unlimited number of characters, and the text
renders in a fixed-width font (usually Courier). The size of a text
area can be specified by the cols and rows attributes, or even better;
through CSS' height and width properties.

Here is the HTML output using


Text Area tag. The user is asked
to input his/her first name. After
the inputting the needed the
data, the user can input a series
of text in the text area and press
the Submit information button.

For the code refer to:


13using_textarea.html

Here is the result of the data


submission, the users first name
and the comment is now
displayed.

For the code refer to:


13using_textarea.php

Course Module
Web Development 7
PHP and HTML FORMS

This is the html code for the


textarea.

Here the html form will contain a


textbox, and a textarea where
the user can input series of text.

Filename: 13using_textarea.html

This is the PHP code.


The variable $firstname and
$comment stores the result from
the html page.

Filename: 13using_textarea.php

Course Module
Web Development 8
PHP and HTML FORMS

USING OPTION / RADIO BUTTON TAG

Option buttons are sometimes called Radio Buttons, and they


force the user into choosing only one item in a list, such as a
Male/Female option, or selecting a payment method.

Here is the HTML output using


Option / Radio button. The user
is asked to input his/her first
name. After the inputting the
needed the data, the user can
now select from the employee
type and press the Submit
information button.

For the code refer to:


14using_radiobuttons.html

Here is the result of the data


submission, the users first name
and the employee type selected.

For the code refer to:


14using_radiobuttons.php

Course Module
Web Development 9
PHP and HTML FORMS

This is the html code for the


radio button.

Here the html form will contain a


textbox, and a option/radio
button where the user can select
type of employee

Filename:
14using_radiobuttons.html

This is the PHP code.


The variable $firstname and
$etype stores the result from the
html page.

Filename:
14using_radiobuttons.php

Course Module
Web Development 10
PHP and HTML FORMS

USING CHECKBOX TAG

Checkbox elements in a situation when the user must check all


boxes that apply (or none). A checkbox element can be placed onto a
web page in a pre-checked fashion by setting the checked attribute
with a "yes" value. By doing so, this element will now default to a
checked status each time the HTML page is loaded.

Here is the HTML output using


checkboxes. The user is asked to
input his/her first name. After
the inputting the needed the
data, the user can now select
from the different degree
received and press the Submit
information button.

For the code refer to:


15using_checkboxes.html

Here is the result of the data


submission, the users first name
and the degree earned.

For the code refer to:


15using_checkboxes.php

Course Module
Web Development 11
PHP and HTML FORMS

This is the html code for the


checkbox application.

Here the html form will contain a


textbox, and series of
checkboxes where the user can
select types of degree received.

Filename:
15using_checkboxes.html

This is the PHP code.


The variable $firstname and
several variables $BA, $MA,
$PHD, upon selection the
appropriate condition will be
displayed. The coded also uses
the isset() function that is used
to check whether a variable is set
or not.

Filename:
15using_checkboxes.php

Course Module
Web Development 12
PHP and HTML FORMS

ASSIGNING VALUES TO VARIABLES

In this section, it will illustrate how to have several inputs and


assign the output to variables to be displayed.

The HTML form contains 3 text


boxes, the user can input the
firstname, lastname and age.
Upon completion the result will
be displayed in the php file what
will have some operations.
Submit information button will
send information to the php file

For the code refer to:


16assigning_values.html

Here is the result of the data


submitted by the user. The
collected data are as follows,
firstname, lastname and age.

For the code refer to:


16assigning_values.php

Course Module
Web Development 13
PHP and HTML FORMS

This is the html code for the


assigning value application

Here the html form will contain


3 textboxes, and user must
supply data such as lastname,
firstname and age. Upon
submission the resulting values
will be send to the php script..

Filename:
16assigning_values.html

Upon submission of data from


the html file, the php script will
receive 3 variables firstname,
lastname and age.

The script will compute the age


by factor of 10 and add it to the
current age, it will also compute
the birth year by subtracting the
current_year with the ageplus
variable.

After the operation the results


are display in the browser using
the echo function.

Filename:
16assigning_values.php

Course Module
Web Development 14
PHP and HTML FORMS

APPENDING TEXT

In this section, you will learn how to append additional


variables to text.

The HTML form contains 3 text


boxes, the user can input the
firstname, lastname and age.
Upon completion the result will
be displayed in the php file what
will have some operations.
Submit information button will
send information to the php file

For the code refer to:


17appending_text.html

Here is the result of the data


submitted by the user. The
collected data are as follows,
firstname, lastname and age.

The script also appends values to


the existing input text supplied
by the user.

For the code refer to:


17appending_text.php

Course Module
Web Development 15
PHP and HTML FORMS

This is the html code for the


assigning value application

Here the html form will contain


3 textboxes, and user must
supply data such as lastname,
firstname and age. Upon
submission the resulting values
will be send to the php script..

Filename:
17appending_text.html

Upon submission of data from the


html file, the php script will receive
3 variables firstname, lastname and
age.

The script will compute the age by


factor of 10 and add it to the current
age, it will also compute the birth
year by subtracting the current_year
with the ageplus variable. It will aso
add the middle_init value to the
input text using the (.) operator.

After the operation the results are


display in the browser using the
echo function.

Filename: 17appending_text.php

Course Module
Web Development 16
PHP and HTML FORMS

Course Module
Web Development 17
PHP and HTML FORMS

References
Murach, J. (2014) Murach’s PHP and MYSQL (2nd Edition)

Yank, K, PHP and MYSQL: Novice to Ninja

WEBSITE

http://php.net/

http://www.w3schools.com/php/

https://www.tutorialspoint.com/php/

Course Module
Web Application Development 2
1
Views

Views

At the end of the module the student is expected to:


1. Understand and apply the concept of views in CI.
2. Know how to pass data using views in CI.
3. Understand the use of URI and apply its use in CI.
4. Identify the URI segments.
5. Use .htaccess to remove index.php
6. Understand the concept of routing and its parameters
7. Use CI 404 page for error page.

Introduction
A view is simply a web page, or a page fragment, like a header, footer,
sidebar, etc. Views serves as User Interfaces where web users can interact,
request and receive data. Controllers can load views and pass data to them

Creating Views
Views are php files containing html elements. They are stored in
application/views folder. Lets have an example of a view. Create a file place
it at application/views/ and give it a name index.php. now type the following
codes.

Now we need to load the index.php (view) to our controller. To load the view
we need go to the controller, name the file as Home.php directory should be
like this: application/controllers/Home.php

Course Module
To load the view, the function is like this $this->load->view('name'); the
name is the name of the view file, in our example to load the view you type
$this->load->view(‘index’);
To test it out, go to http://localhost/index.php/Home. This should output:

Passing Data to View


Views are used to present data. Most data passed in a view are from the
controller or model (from the database). Data can be a string value, an array
or an object. $this->load->view method has an optional second parameter,
which is the data to be passed.
$this->load->view(‘view_file_name’, $data);
All you need is to define an array or array index to be passed. If you know
what php extract function does, the passed array from the controller is
automatically extracted when passed on a view. The associated array names
turn into variables.
Example:

Controller View

$data[“greeting”] = “Hello World”; //some_page.php


<?php
$this->load->view(‘some_page’, echo $greeting;
$data); ?>
//outputs:
//Hello World

$data = array( //some_page.php


‘lname’ => ‘Juan’, User: <?php echo $lname.’,
‘fname’ => ‘Cruz’ ’.$fname; ?>

);
//outputs:
//User: Cruz, Juan
$this->load->view(‘some_page’,
$data);

Let’s pass some data to our index.php view Update the index method on the
Home controller: Don’t forget the second parameter $data.
Web Application Development 2
3
Views

And also to our index view:

In this way, our title will be dynamic by using the $title variable.
Output:

Notice that our Title Bar show our passed $data[“title”] from our Controller
to our view using $title.

Passing More Data


Let’s pass more values from our controller using Arrays. Arrays are like
variables. Array store multiple values or elements that can be accessed by its
index or position. Arrays can be Indexed (numerical positions starting with
0), Associative (or named positions), and multi-dimensional (arrays within
array).
Say we have an array of products on our controller
application/controller/Products.php

Course Module
$data is an associative array containing the key products with array values:
Spaghetti, Baked Mac, Fettucine, Lasagna and the key title contains “Products”
string for our <title>
And displays it on our view at application/views/products.php

The $data array from the Products controller was extracted to our view. It will
simply display the $title inside the <title> tag and loop our $products array
values into our <ul> (unordered list).
If you want to pass more values on variables or array, just store it on
$data associative array on the controller’s method and don’t forget to $this-
>load->view(‘your_view’, $data) with $data as the second parameter.
Example:
$data[“num_of_products”] = count(array('Spaghetti', 'Baked Mac',
'Fettucine', 'Lasagna'));
$data[“date_today”] = date(‘F d, Y’);
Output:

The array values are loaded by the foreach loop.


Web Application Development 2
5
Views

Understanding URI
What is URI? URI stands for Uniform Resource Identifier. It is a string of
characters used to identify a resource. URL (Uniform Resource Locator) and
URN (Uniform Resource Name) are forms of URI.

Location (URL)
URI

Name (URN)

URI, URL and URNs


To make it easier to understand, for an example, there was Juan Dela Cruz as
our given URN. There are many Juan Dela Cruz in the country, thus we need
to know whose Juan dela Cruz of what place or address are we looking for.
When you are searching for Juan Dela Cruz of Bulacan, it is now URL. Did you
get the idea? URN can be of any given name or address. We use URL to define
what method and address is the requested web page. The combination of
both URL and URN resource is what we call specifically URI.

URL URN

https://facebook.com.com/dustoutlaw23 /profile/dustoutlaw23

https://www.youtube.com/channel/UCNHX /channel/UCNHXyYCEqfm
yYCEqfmO8jBTlbFvLHA O8jBTlbFvLHA

URL is the location that includes the components: the path/method and the
domain. It is basically called Web Address. URN is the historical name that
serve as persistent, location-independent identifiers allowing the simple
mapping of namespaces into a single URN namespace.

URI Segments
URI segments in CodeIgniter:
http://www.websitedomain.com/controller/method/param1/param2...

1 2 3 4
After the domain name, the controller comes the 1st segment of the URI. The
second follows the method. The 3rd, 4th and so on are the parameters. These

Course Module
parameters are mostly required by the method, it can be used as control,
settings or input.
Examples:
products/view/3 Viewing Product with the id 3
salary/calculate_daily_gross/8/100 Calculating daily gross salary with
8 hrs worked and with the pay rate
of 100 per hour
To get the uri segments on the address bar, we will use $this->uri-
>segment(n) where n is the requested segment position number.
Example:
http://suzuki.com.ph/motors/motorcycles/big-bikes/bandit-650/
Code Return String
$this->uri->segment(1) motors
$this->uri->segment(2) motorcycles
$this->uri->segment(3) big-bikes
$this->uri->segment(4) bandit-650
To see how it works, add the spaghetti method on our Products controller:
application/controlers/Products.php

$this->uri->segment() method of the URI Class is automatically loaded in CI.


With this URL/web address instance,

It will output:

Removing Index.php
http://localhost/index.php/controller/method/param
This makes our URL longer that it consumes space. Why not remove it to
make it cleaner? We are not referring all of our pages in a single php file and
by that it looks more confusing.
The Answer? Create an .htaccess file that will automatically route the
index.php next to the Controller
Web Application Development 2
7
Views

Create the .htaccess file

Save it to your server’s root directory or your project’s directory

You can now type in the URL without the index.php! (e.g.
http://localhost/controller/method/param)

Routing
For a quick review, here’s an example of CodeIgniter URL:
http://www.websitedomain.com/controller/method/param1/param2...
And also you can do this:
http://www.websitedomain.com/profile/dustin
Instead of:
http://www.websitedomain.com/profile/view/23

controller method parameter value


This is how routing works, instead of requesting an address with controller-
method-params relationship, you can request a specific address as alias or
redirect (re-route) to a different controller. Routing is the process of
redirecting or remapping a controller class or method. Defining or creating
your own routing rules are set in the CI’s application/config/routes.php file.
Constructing a routing rule uses wildcards or regular expression.
Examples:

Course Module
$route[“bikes”] = ‘motorcycles’;
A URL that contains ‘bikes’ as controller will be remapped to ‘motorcycles’
controller class
$route[“profle/dustin”] = ‘profile/view/23’;
A URL containing the first segment ‘profile’ and second segment ‘dustin’ will be
rerouted to ‘profile’ controller, to the view method and to the profile id.
$route[“bikes/(:any)”] = ‘motorcycles/bike_lookup’;
A URL that contains any character or word on the second segment will be
redirected to ‘motorcycles’ controller class and bike lookup method as it will
search the motorcycle database for any given word or character.
$route[“bikes/(:num)”] = ‘motorcycles/view/$1’;
A URL that contains the ‘bikes’ controller associated with any number will be
readdressed to the ‘motorcycles’ controller and will trigger the ‘view’ method
and will accept the given number as a parameter value.

Setting the Default Controller


$route['default_controller'] = 'welcome';
By default, its value is the CodeIgniter’s welcome controller class. When a
URI segment or Controller class is not present, CI will load its default
controller configuration at application/config/routes.php file.

404 Page
Have you ever encountered “Error 404: Page not found”? This happens when
you try to reach a webpage but could not be found on the server. This can be
because you typed In the URL incorrectly, the URL was moved or it does not
exist. CodeIgniter allows you to show this client-side error and use it to catch
errors on your code intentionally or not.
When an Error 404 is met, application/views/errors/html/error_404.php file
is shown. Now you know where to customize this error In CodeIgniter.
You can display the error 404 page by using the function show_404() in the
controller method.
Example:

References
Web Development

Module 6– Log-in and Log-out using Session Library

Topics
Introduction .................................................................................................................................. 2

Session Variables........................................................................................................................... 2

Loading the Session Library ........................................................................................................... 2

Creating Session Variables in CI ..................................................................................................... 3

Accessing Session Variables ........................................................................................................... 3

Removing Session Data ................................................................................................................. 4

Log In using CI Session ................................................................................................................... 4

Log Out ........................................................................................................................................ 10

Learning Objectives

At the end of the module the student is expected to:

1. Understand the concept of sessions variable.

2. Identify the syntax in creating, loading and removing session variable in CI.

3. Apply the commands needed in creating, loading and removing sessions in CI.

4. Create CI application showing the codes.

Module 6 – Log-in and Log-out using Session Library 1


Web Development

Introduction

Session Variables

We already know that sessions in native PHP are the “superglobal” variables that can be

accessed anywhere on the web application because it is stored on the browser session. They can be set

and accessed like any ordinary variables except that it uses the $_SESSION.

In order to use and access session variables on webpages, we must put the session_start()

function. The unsetting of the variable can be done by using unset() function on variables or

session_destroy() to erase all existing session variables.

CodeIgniter improve the utilization of session variables on its Session Library. It contains

different session methods with different functionalities to help us speed up the task and simplify coding.

There were the improved session variables, flashdata and tempdata. The only new here is the flashdata

and tempdata. Flashdata are session variables that are only available until the next request. If the same

webpage is requested, the flashdata will not be present as it expires on the first request. The Tempdata

are just like ordinary session variables but expires in the defined seconds. Flashdata and Tempdata were

previously discussed and used on our last chapter to help us display success or failed status messages.

Loading the Session Library

There are two ways to load CI’s session library.

You can load it in inside the controller’s constructor or on its methods by:

$this->load->library(‘session’)

or if you will frequently use it, make it autoloaded by adding the ‘session’ library in the library

array at application/config/autoload.php on line 61.

Module 6 – Log-in and Log-out using Session Library 2


Web Development

Creating Session Variables in CI

You can declare your own session variable on the $_SESSION superglobal but for the sake of this

tutorial on CodeIgniter, let CI do their thing because it’s much more simplified and structured. When the

session library is loaded, you don’t need to write session_start all over and over again, just declare the

session variable using $this->session->set_userdata()

Example:

Or pass an associative array with its field_name and value pattern.

Example:

Note: $this->session->set_userdata() is also used to set or change an existing session variable value.

Accessing Session Variables

To use or access session variables and its value, you may use the userdata() method.

Example when you have ‘item’ session variable name, you’ll use:

$this->session->userdata(‘item’)

or simply call:

$this->session->item

Module 6 – Log-in and Log-out using Session Library 3


Web Development

or basically call the $_SESSION superglobal:

$_SESSION[‘item’]

Removing Session Data

When you no longer need the session variable you have set, you can remove it

by using $this->session->unset_userdata()

Example you have ‘item’ session variable set, unset it by:

$this->session->unset_userdata(‘item’)

Or unset a session array:

$session_array = array(‘name’, ‘user_level’);

$this->session->unset_userdata($session_array)

Similarly, you can use native PHP’s unset() function on $_SESSION superglobals:

unset( $_SESSION[‘item’] )

Unsetting multiple variables:

unset( $_SESSION[‘item1’], $_SESSION[‘item2’] )

Log In using CI Session

User access and restriction is one of the must-need functionality of any website applications.

Log In modules are needed to limit users from accessing off-limits and restricted webpages or content.

Websites with database interactivity provide users to gain access to its backend or Administration Panel.

Module 6 – Log-in and Log-out using Session Library 4


Web Development

We’ll use the ‘users’ table

user_id user_name user_pass user_accountname

1 admin admin Administrator

2 dustin 12345 Leon Dustin

For the sake of security, we need to encrypt the user_pass column with md5. Use the md5()

function in your query when inserting passwords. MD5 is an algorithm that is used in security hashing

that transforms data into a 128 bit string. It is claimed that every encrypted string is as unique as

fingerprint.

MySQL query:

Updated ‘users’ table

user_id user_name user_pass user_accountname

1 admin 21232f297a57a5a743894a0e4a801fc3 Administrator

2 dustin 827ccb0eea8a706c4c34a16891f84e7b Leon Dustin

Create the Login Controller at application/controllers/Login.php with the below code:

Module 6 – Log-in and Log-out using Session Library 5


Web Development

Provide the login view at application/views/login.php:

The Log In form that accepts username and password. The form uses Form Helper to return

HTML Form elements. When the form is submitted, the post variables will be sent to the verify method of

the Login controller class.

Output:

Module 6 – Log-in and Log-out using Session Library 6


Web Development

Add the verify method on the Login controller with Form Validation:

We have set a required rule on both fields and a callback_check_user on the password field. This

callback will check the user if it exists. If the fields passed the validation, the page will be redirected to

the Home controller where only authorized or logged-in users can access.

Within the same controller, add the callback method check_user:

The login method of the Login Model will check the user if the username and password

parameters matched a record from the database. If it finds one, it will prepare our session variables for

logging in and will pass the callback_check_user form validation rule.

The islogged session variable will determine whether the user record is authenticated and will

be used on all user restricted webpages.

Module 6 – Log-in and Log-out using Session Library 7


Web Development

The Login model at application/models/login_model.php:

The login method will check the username and password parameters if it exists on the ‘users’

table and will return the login details.

After the Login functionality that checks allowed users, let’s create the landing page after the

logging in process. Create the Home controller at application/controllers/Home.php:

Module 6 – Log-in and Log-out using Session Library 8


Web Development

The Home controller and its method is exclusively for registered users. At the constructor

method, we need to include a condition that checks if the user has privileges on the page using the

islogged session variable. If not, they will be redirected back to the login page.

The homepage view at application/views/home.php:

This will display the user’s account name and a link for logging out

Output:

Module 6 – Log-in and Log-out using Session Library 9


Web Development

Log Out

For the Logout controller at application/controllers/Logout.php:

To logout a user, all we need to do is unset the session variable that keeps us in: the islogged

variable. To keep it neat, we have to unset all of our session variables and redirect back to Login

controller.

Module 6 – Log-in and Log-out using Session Library 10


Web Development 1
PHP Basics

PHP Basics
Learning Objectives

At the end of the module the student is expected to:

1. Understand how to use PHP Syntax


2. Understand and apply comments in PHP codes.
3. Understand the concept of case sensitivity in PHP codes.
4. Understand the use of variables.
5. Understand and apply the use of echo and print statements
6. Understand the concept of data types and use it in PHP programs
7. Apply string concatenation

INTRODUCTION

In the previous module, we have learned how to install and run


PHP for the first time. In this module we will learn PHP basics such as
syntax, comments, variables and more.

PHP BASICS

PHP Syntax

To embed PHP code, you must use the following syntax.

php
// PHP code goes here
?>

Every time you want to use php scripts, the codes must be
enclose inside <?php ?> , all codes that are place inside the php block
are read by the php.

PHP Comments

Course Module
Web Development 2
PHP Basics

A comment in PHP code is a line that is not read/executed as


part of the program. Its purpose is to provide information or details to
the codes.

The following are the use of comments.

1. Let developers understand the code you are writing.


2. Serves as a reminder.

Sample Code:
Filename: 02basics_adding_comments.php

The code shows the use of


including comments into a PHP
code.

It helps the user identify the


functions/commands included in
the program.

Here is the output of the


program that add comments to
the PHP code. All comments are
hidden to the user, its only
viewable in the code.

PHP Case Sensitivity

In PHP, all keywords (e.g. if, else, while, echo, etc.), classes,
functions, and user-defined functions are NOT case-sensitive. In the
example below, all three echo statements below are legal (and equal):

Course Module
Web Development 3
PHP Basics

Sample Code:
Filename: 03case_sensitivity.php

The code shows the use of case


sensitivity of PHP commands

here is the result of the html


code, it still display the text hello
world even with different case of
the command ECHO.

Note: all variable names are case-sensitive. In the example below, only
the first statement will display the value of the $color variable (this is because
$color, $COLOR, and $coLOR are treated as three different variables):

Course Module
Web Development 4
PHP Basics

Sample Code:
Filename: 04case_sensitivity.php

The code shows the use of


variables and its case sensitivity.

Since, the only declared variable


is $color, the remaining
variables $COLOR and $coLOR
are not recognized by PHP so it
resulted an error.

PHP Variables

A variable can have a short name (like x and y) or a more descriptive


name (age, carname, total_volume).

Rules for PHP variables:

 A variable starts with the $ sign, followed by the name of the


variable
 A variable name must start with a letter or the underscore
character
 A variable name cannot start with a number
 A variable name can only contain alpha-numeric characters and
underscores (A-z, 0-9, and _ )
 Variable names are case-sensitive ($age and $AGE are two
different variables)

Course Module
Web Development 5
PHP Basics

Note: Remember that PHP variable names are case-sensitive

Sample Code:
Filename: 05_PHP_Variables.php

The code below shows the use of


variables in PHP.

Here is result of the code that


uses variables.

PHP is a Loosely Typed Language

PHP automatically converts the variable to the correct data type,


depending on its value. In other languages such as C, C++, and Java, the
programmer must declare the name and type of the variable before
using it.

Course Module
Web Development 6
PHP Basics

PHP Variables Scope

In PHP, variables can be declared anywhere in the script. The


scope of a variable is the part of the script where the variable can be
referenced/used.

PHP has three different variable scopes:

 Local - A variable declared within a function has a LOCAL SCOPE and


can only be accessed within that function
 Global - A variable declared outside a function has a GLOBAL SCOPE
and can only be accessed outside a function
 Static - a static variable will not lose its value when the function exits
and will still hold that value should the function be called again.

PHP 5 echo and print statements

In PHP there are two basic ways to get output: echo and print.
echo and print are more or less the same. They are both used to output
data to the screen. The differences are small: echo has no return value
while print has a return value of 1 so it can be used in expressions. echo
can take multiple parameters (although such usage is rare) while print
can take one argument. echo is marginally faster than print.

PHP Data Types

Variables can store data of different types, and different data


types can do different things. PHP supports the following data types:

 String
 Integer
 Float (floating point numbers - also called double)
 Boolean
 Array

Course Module
Web Development 7
PHP Basics

The code below shows the


application on the use of
variables in PHP.

This example shows the


application of integer, float
variables.

Filename:
06_Variables1.php

Here is the result of using


variables

Course Module
Web Development 8
PHP Basics

The code shows the use of string


in PHP.

Filename:
07_Variables2.php

Here is the result on using string


variables.

Course Module
Web Development 9
PHP Basics

In this code, shows the


application of variables, it also
show the use of conditional
statement if..else.

Filename:
08_Variables3.php

Here is the result of the


condition. Since the variable
$validUser is set to True, the
output is “User is Valid”.

In the second variable


declaration the $validUser is
now set to False. Now the
output of the code is User is NOT
Valid.

Course Module
Web Development 10
PHP Basics

The code shows the data type of


the variables.

To show the data type, you can


use var_dum();

The var_dump() function is used


to display structured
information (type and value)
about one or more variables.

Filename:
09_Variables3.php

The code snippet shows the data


type of the variable use.

Course Module
Web Development 11
PHP Basics

String Concatenation

The PHP concatenation operator (.) is used to combine 2 sting


values to create one string.

In this code, there are variables


that shows the address of a
person, to combine the address
we use the (.) operator to
concatenate the string

Filename:
10_String_Concatenation.php

Here is the output of the string


concatenation.

Course Module
Web Development 12
PHP Basics

References
Murach, J. (2014) Murach’s PHP and MYSQL (2nd Edition)

Yank, K, PHP and MYSQL: Novice to Ninja

WEBSITE

http://php.net/

http://www.w3schools.com/php/

https://www.tutorialspoint.com/php/

Course Module
Web Application Development 2
1
Introduction

Introduction

At the end of the module the student is expected to:


1. Understand what is codeigniter / CI.
2. List the reasons why developers use CI.
3. Enumerate the skills needed in using CI.
4. Understand the steps in installing CI.
5. Understand the MVC web framework and its structure in CI.

Introduction
Learning and Development in PHP is simple. CodeIgniter – “a powerful PHP
framework with a very small footprint, built for developers who need a
simple and elegant toolkit to create full-featured web applications.” It sounds
very complex but it’s pretty straightforward.
CodeIgniter is developed by Ellislab and used by millions worldwide.
Developers prefer to use CI for its rapid application development. It has rich
and reusable libraries and class for your website’s foundation.
Instead of creating your website from native PHP scratch, why not make it
more organized and powerful using CodeIgniter.

Why use CodeIgniter or CI.


1. CI is an application framework
2. CI is free
3. CI is light weight
4. CI is fast
5. CI uses Model-View-Controller architecture
6. CI generates Clean URLs
7. CI is Extensible
8. CI is thoroughly documented
9. CI has a friendly community of users

Skills needed
The following are the items you need to know before starting to play around
CI.
PHP – A good understanding of the PHP language is a must. As long as you
can perform simple instructions (e.g. variable declaration/assignments,
conditions, loops), you will nearly understand everything here since the
CodeIgniter is made up of PHP!

Course Module
HTML – Well, you do need those html elements to manipulate to. You’ll use
this for the layout design, inputs and presentation of data.
CSS – It’s good if you know Cascading Style Sheets (CSS), and even better if
you’re using external style sheets. There are more web design processors
available if you want to level-up your knowledge on styling however if you
don’t know how, still, you can learn CI.
MySQL – This means your SQL Basic queries are required. There will some
modules on this book where you need to manipulate I/O (inputs and
outputs) from your data storage or your database. Models communicate with
the database and uses your fundamental knowledge on SQL.
JavaScript – It makes the website interact with the HTML elements. If you do
not know JS, maybe learn it sometime, okay? You need these for future
developments.

CI Installation
Step 1. Visit its website on https://www.codeigniter.com/

Step 2. Find your way to the Download link and click Download.
The current version is 3.0.6

Step 3. Extract the downloaded .zip file and place it on your local server.

Make sure your Apache server is running and online then do:
Web Application Development 2
3
Introduction

Step 4. If you can see this Welcome Message. Your installation was a
success!

MVC Web Framework


Before you start CI, you should know what MVC is.
MVC stands for Model-View-Controller. MVC is an architectural pattern for
Web Development that is properly structured into layers:

Course Module
Controller – This contains the Business logic (Business Logic Layer). The
controller controls the Model and View. A controller is a class that contains
methods that decides what to call, or perform and display.
When a user sends a request on a browser, the controller will determine the
process and perform tasks based on its method; it includes calling a method
returning a value from a model, displaying and passing values on a view or
showing a 404 error page.
Views – The Presentation layer. This contains designs, layouts or templates. It
is the collection of what will show up on your browser. The view is where the
user sees and interacts with.
Models – It is also referred as the Data Access Layer. The Model
communicates with your database. It comprises of methods that execute
queries using the CodeIgniter’s Active Record pattern.

CI Directory
Basically, CodeIgniter has 3 main folders: Application, System and User
Guide. You will work with your website in Application Folder. The System
folder, keep it a habit to avoid making changes to any of the files inside. It
contains the CodeIgniter’s core files which is necessary to make it run.
User_Guide contains the offline documentations you need in developing with
websites in CI.
Web Application Development 2
5
Introduction

Let’s get a little familiar with the directories:


• Cache: This directory will contain all kinds of cached files if you are
using so. However, you will may need to provide write access for the
application to this directory as codeigniter will need to create
temporary files on this folder. To know how to use caching, please
refer to CodeIgniter caching tutorial.
• Config: This directory includes settings/configuration related
information like database settings, route information, constants
declaration, items to be auto loaded etc.
• Controller: This directory includes all controller definitions. It can be
said as the entry point of application also, every requests triggers a
certain method of a controller.
• Core : If we need to extend the functionality of any core classes like
controller, loader, router etc, then we can declare new class here
which will extend those core classes and put the implementation
inside those.
• Errors: This directory includes some basic template for showing
various kind of errors like db error, php errors, 404 errors etc, which
we can change later as per our requirements.
• Helpers: This directory will include all helper files.
• Hooks: This directory will include all hooks declaration.
• Language: This directory will include language files. By loading
different language files, we can make our application multilingual
supported.
• Libraries: This directory will include all library class files that might
need to be created for our applications.

Course Module
• Logs: This directory will include all application logs. TO know how to
write log for debug/error/info, please more about error handling
• Migrations: This directory will include migration helpers.
• Models: This directory will include all model classes used in our
application. This section can be said as the ‘data access layer’ of our
application.
• Third_party : This directory will include library files, but only those,
which are imported from third-party. So, difference between the
‘third_party’ and ‘libraries’ is that, one is for self-made libraries, for
app specific, other one is for importing party libraries.
• Views : This directory will include all view template files.

Activities and Exercises


Web Application Development 2
1
Introduction

Introduction

At the end of the module the student is expected to:


1. Understand what is codeigniter / CI.
2. List the reasons why developers use CI.
3. Enumerate the skills needed in using CI.
4. Understand the steps in installing CI.
5. Understand the MVC web framework and its structure in CI.

Introduction
Learning and Development in PHP is simple. CodeIgniter – “a powerful PHP
framework with a very small footprint, built for developers who need a
simple and elegant toolkit to create full-featured web applications.” It sounds
very complex but it’s pretty straightforward.
CodeIgniter is developed by Ellislab and used by millions worldwide.
Developers prefer to use CI for its rapid application development. It has rich
and reusable libraries and class for your website’s foundation.
Instead of creating your website from native PHP scratch, why not make it
more organized and powerful using CodeIgniter.

Why use CodeIgniter or CI.


1. CI is an application framework
2. CI is free
3. CI is light weight
4. CI is fast
5. CI uses Model-View-Controller architecture
6. CI generates Clean URLs
7. CI is Extensible
8. CI is thoroughly documented
9. CI has a friendly community of users

Skills needed
The following are the items you need to know before starting to play around
CI.
PHP – A good understanding of the PHP language is a must. As long as you
can perform simple instructions (e.g. variable declaration/assignments,
conditions, loops), you will nearly understand everything here since the
CodeIgniter is made up of PHP!

Course Module
HTML – Well, you do need those html elements to manipulate to. You’ll use
this for the layout design, inputs and presentation of data.
CSS – It’s good if you know Cascading Style Sheets (CSS), and even better if
you’re using external style sheets. There are more web design processors
available if you want to level-up your knowledge on styling however if you
don’t know how, still, you can learn CI.
MySQL – This means your SQL Basic queries are required. There will some
modules on this book where you need to manipulate I/O (inputs and
outputs) from your data storage or your database. Models communicate with
the database and uses your fundamental knowledge on SQL.
JavaScript – It makes the website interact with the HTML elements. If you do
not know JS, maybe learn it sometime, okay? You need these for future
developments.

CI Installation
Step 1. Visit its website on https://www.codeigniter.com/

Step 2. Find your way to the Download link and click Download.
The current version is 3.0.6

Step 3. Extract the downloaded .zip file and place it on your local server.

Make sure your Apache server is running and online then do:
Web Application Development 2
3
Introduction

Step 4. If you can see this Welcome Message. Your installation was a
success!

MVC Web Framework


Before you start CI, you should know what MVC is.
MVC stands for Model-View-Controller. MVC is an architectural pattern for
Web Development that is properly structured into layers:

Course Module
Controller – This contains the Business logic (Business Logic Layer). The
controller controls the Model and View. A controller is a class that contains
methods that decides what to call, or perform and display.
When a user sends a request on a browser, the controller will determine the
process and perform tasks based on its method; it includes calling a method
returning a value from a model, displaying and passing values on a view or
showing a 404 error page.
Views – The Presentation layer. This contains designs, layouts or templates. It
is the collection of what will show up on your browser. The view is where the
user sees and interacts with.
Models – It is also referred as the Data Access Layer. The Model
communicates with your database. It comprises of methods that execute
queries using the CodeIgniter’s Active Record pattern.

CI Directory
Basically, CodeIgniter has 3 main folders: Application, System and User
Guide. You will work with your website in Application Folder. The System
folder, keep it a habit to avoid making changes to any of the files inside. It
contains the CodeIgniter’s core files which is necessary to make it run.
User_Guide contains the offline documentations you need in developing with
websites in CI.
Web Application Development 2
5
Introduction

Let’s get a little familiar with the directories:


• Cache: This directory will contain all kinds of cached files if you are
using so. However, you will may need to provide write access for the
application to this directory as codeigniter will need to create
temporary files on this folder. To know how to use caching, please
refer to CodeIgniter caching tutorial.
• Config: This directory includes settings/configuration related
information like database settings, route information, constants
declaration, items to be auto loaded etc.
• Controller: This directory includes all controller definitions. It can be
said as the entry point of application also, every requests triggers a
certain method of a controller.
• Core : If we need to extend the functionality of any core classes like
controller, loader, router etc, then we can declare new class here
which will extend those core classes and put the implementation
inside those.
• Errors: This directory includes some basic template for showing
various kind of errors like db error, php errors, 404 errors etc, which
we can change later as per our requirements.
• Helpers: This directory will include all helper files.
• Hooks: This directory will include all hooks declaration.
• Language: This directory will include language files. By loading
different language files, we can make our application multilingual
supported.
• Libraries: This directory will include all library class files that might
need to be created for our applications.

Course Module
• Logs: This directory will include all application logs. TO know how to
write log for debug/error/info, please more about error handling
• Migrations: This directory will include migration helpers.
• Models: This directory will include all model classes used in our
application. This section can be said as the ‘data access layer’ of our
application.
• Third_party : This directory will include library files, but only those,
which are imported from third-party. So, difference between the
‘third_party’ and ‘libraries’ is that, one is for self-made libraries, for
app specific, other one is for importing party libraries.
• Views : This directory will include all view template files.

Activities and Exercises


Identification. Write your answer on the space provided.
What year did PHP began its development
Answer: 1994

Identification. Write your answer on the space provided. Year that PHP 3 was released.
Answer: 1998

Identification. Write your answer on the space provided.


Year that PHP was officially called Personal Home Page Tools.
Answer: 1995

Identification. Write your answer on the space provided.


Inventor of PHP
Answer: Rasmus Lerdorf

Identification. Write your answer on the space provided. What functionality was added to PHP 5.1 as interface for
accessing databases?
Answer: PDO

Identification. Write your answer on the space provided.


Version of PHP that introduces the use of superglobals
Answer: 4.1

Identification. Write your answer on the space provided. Version of PHP what uses namespace support late static
binding
Answer: 5.3

Identification. Write your answer on the space provided. PHP version that uses void return type, class constant
visibility modifiers, null types
Answer: 7.1

Identification. Write your answer on the space provided. PHP version that enabled the filter extension by default
Native JSON default
Answer: 5.2

Identification. Write your answer on the space provided. PHP version currently in use on most websites and
included several new features such as support for object-oriented programming
Answer: PHP 5

php.org is the official php resource.


Select one:
True
False

PHP in now known as "PHP: Hypertexts Preprocessor"


Select one:
True
False

Facebook, wordpress uses php as script language.


Select one:
True
False

PHP is one of the most widely used and recognizable web technology use on the internet.
Select one:
True
False

Andi Gutmans was the inventor of PHP.


Select one:
True
False

Working locally you an access php script by using http://localhosts/filename.php


Select one:
True
False

PDO stands for Personal Data Objects


Select one:
True
False

PHP runs on various platforms operating system such as apache and IIS
Select one:
True
False

PHP is proprietary software.


Select one:
True
False
Originally PHP is known as PHP: Hypertext Preprocessor (Personal Home Page)
Select one:
True
False

PHP 3 was released in 1998.


Select one:
True
False

Version 4 of php supports global variables $Get etc. (v4.1)


Select one:
True
False

PHP script tags ends with ?>;


Select one:
True
False

Originally PHP is known as "Personal Home Pages"


Select one:
True
False

PHP project originally started in 1995 by RasmusLerdorf. (1994)


Select one:
True
False

PHP only runs in Apache web server.


Select one:
True
False

PHP development began in 1995.


Select one:
True
False

The default file extension for PHP files is ".php".


Select one:
True
False

Using XAMPP server you can use SQL Server database.


Select one:
True
False
<html>
<body>

What is the function of the ucfirst and lcfirst functions?


-To make the string's first character uppercase or lowercase, respectively
What will the following script output?-$array=array
-78

comment
Script use in every php code. (Note : No spaces needed)
<?php?>
PHP in now known as "PHP: Hypertexts Preprocessor"
false
Define styles for your documents, including the design, layout and variations in
display for different devices and screen sizes.
CSS
Identification. Write your answer on the space provided. PHP version that uses
void return type, class constant visibility modifiers, null types
php 7.1
Symbol used to combine 2 sting values to create one string.
.
Symbol use to append data or string
.=
PHP is proprietary software.
false
PHP 3 was released in 1998.
true
What does PHP stand for?
PHP: Hypertext Preprocessor
PHP variables need to be declared before adding a value to it?
false
PHP can be run on Microsoft Windows IIS(Internet Information Server):
false
Which one of these variables has an illegal name?
$my-Var
It is a function that removes an existing file from the server.
unlink

PHP development began in 1995.


false
All text in a multiple line comment block is ignored?
true
Inventor of PHP
text input control.
Function is used to display structured information (type and value) about one or
more variables.
var_dump()

All text to the right of a single line comment is not ignored?


false
For maximum compatibility, you should use the shorthand form to create PHP
scripts?
false
Version of PHP what uses namespace support late static binding
5.3
Syntax is a set of rules that must be followed to write properly structured
code?
true
How do you start the standard form PHP scripting block?
<?php � ?>
Which of the following is the incorrect way to declare a PHP variable?
$a Variable;
If a source file contains PHP code, what extension should be used?
.php
Multiple Choice. Select the best answer
In PHP you can use both single quotes ( ' ' ) and double quotes ( " " ) for
strings:
/ *...* /
php.org is the official php resource.
false
When a variable is declared, it can only be used 1 time in your PHP source file?
false
Identification. Write your answer on the space provided.
This are used with numeric values to perform common arithmetical operations,
such as addition, subtraction, multiplication etc
arithmetic operators
Identification. Write your answer on the space provided.
Which operator will check if two variables are the same?
comparison operator
( (2 >= 2 && 8 < 1) || (11 == 33 || 5 > 3) )
true
True or False - The operator OR, when used to link two or concept terms will
retrieve fewer records because both terms need not be present in each article.
false
Identification. Write your answer on the space provided.
+, -, *, /, %, are all examples of what category of operators
arithmetic operator
The following condition will return TRUE or FALSE: (7 >= 7 && 9 < 2)
false
Which of the following that can be use to access session variables in PHP?
$_SESSION
It is an array containing information such as headers, paths and script
locations wherein it is created by the web server itself
$_SERVER
Sorts by value in reverse order; keeps the same key
arsort()
This function is used to close the current session.
session_destroy()
Generate fatal error.
define
It is a SQL keyword that creates an autoincrementing field.
AUTO_INCREMENT
It opens a connection to a MySQL database server
mysql_connect / mysqli_connect
It is a function that saves the uploaded file permanently into the server.
move_uploaded_file()
It is a file function mode that is used to open a file for reading, writing or
appending.
fopen
Allow for multiple items of the same type to be aggregated under a single
representative entity.
Compound Datatypes
It specifies the name of the field in the form to be processed by the $_FILES
file
It is used to access submitted form values
$_POST
It is an attribute that must be used in the form tag in specifying an input file
type
enctype
It is placed within the code of a loop to cause the program to stop the loop
statement.
break
It proceeds the statement causes execution of the current loop iteration to end
and commence at the beginning of the next loop.
continue
It is a function that retrieves the content of one cell from a MySQL result set.
mysql_fetch_row()
mysqli_fetch_row()
Format character of Date function that display the day of the month in 2 digits
with leading zeros such as 01 to 31
d
Assume you would like to sort an array in ascending order by value while
preserving key associations. Which of the following PHP sorting functions would
you use?
asort()
Array values are keyed by ______ values (called indexed arrays) or using ______
values (called associative arrays). Of course, these key methods can be combined
as well.
integer,string
Generate fatal error.
iInclude_once()
It is a function that retrieves the number of rows from a query result set.
mysql_affected_rows()
mysqli_affected_rows()
Format character of Date function that display a full textual representation of
the day of the week such us Sunday to Saturday
d
Which of the following that can be use read cookies in PHP?
setcookie()
This function removes the white spaces and other predefined characters from both
sides of a string
trim
Join array elements to form a string.
implode
Managing of cookies can be done using this function
cookie()

</body>
</html>
All are benefits of information protection except one.

Ans : e-mailing the suppliers and partners with updated services

Failure to protect sensitive information can result in __________ issued by regulatory agencies
or lawsuits from other companies or individuals.

Ans : fines

In addition to security, information assurance ensures the identified answers except one.

Ans : enhanced visuals

In IA, this automatically happened as well as availability and reliable and timely access to
information.

Ans : confidentiality

No organization can be considered "safe" for any time beyond the last verification of
adherence to its policy.

Ans : security

This is roughly equivalent to privacy.

Ans : confidentiality

This assured that the information is authentic and complete.

Ans : integrity

This is an assurance that the systems responsible for delivering, storing, and processing
information are accessible when needed, by those who need them.

Ans : availability
This is "the environment in which communication over computer networks occurs.“

Ans : cyberspace

Cyber security, also referred to as____________________, focuses on protecting computers,


networks, programs and data from unintended or unauthorized access, change or
destruction

information technology security

The state of being protected against the criminal or unauthorized use of electronic data, or
the measures taken to achieve this.

cyber security

This refers to the body of technologies, processes, and practices designed to protect
networks, devices, programs, and data from attack, damage, or unauthorized access.

cyber security

A significant portion of data can be sensitive information, whether that be __________________,


financial data, personal information, or other types of data for which unauthorized access or
exposure could have negative consequences.

intellectual property

Organizations transmit sensitive data across networks and to other devices in the course of
doing businesses, and this describes the discipline dedicated to protecting that information
and the systems used to process or store it.

cyber security

As the volume and sophistication of cyber attacks grow, companies and organizations need
to take steps to protect their sensitive business and personnel information.

'True'.
The organizations and the government have focused most of their cyber security resources
on perimeter security to protect all the encrypted system components.

'False'.

This issued guidelines in its risk assessment framework that recommend a shift
toward continuous monitoring and real-time assessment.

National Institute of Standards and Technology

This recommends a top-down approach to cyber security in which corporate management


leads the charge in prioritizing cyber security management across all business practices.

National Cyber Security Alliance

This advises that companies must be prepared to “respond to the inevitable cyber incident,
restore normal operations, and ensure that company assets and the company’s reputation are
protected.”

NCSA

_______________ should also consider any regulations that impact the way the company
collects, stores, and secures data, such as PCI-DSS, HIPAA, SOX, FISMA.

Cyber Risk Assessment

Following a cyber risk assessment, develop and implement a plan to mitigate cyber risk and
protect the “_____________” outlined in the assessment.

crown jewels

Combining sound cyber security measures with an educated and security-minded


employee base provides the best defense against ________________attempting to gain access
to your company’s sensitive data.

cyber criminals
This consists of the cyber-physical systems that modern societies rely on.

critical infrastructure security

This is not an example of critical infrastructure.

agricultural farm

Negotiations are much more accessible over networks, causing the adoption of security
measures during the development phase to be an imperative phase of the project.

False'

This is not a type of application security.

photo enhancement

This ensures that internal networks are secure by protecting the infrastructure and inhibiting
access to it.

network security

These are all common examples of network security implementation except one.

clean storage feature

These are constantly creating and implementing new security tools to help enterprise users
better secure their data.

cloud providers

The data is more secure when stored on physical servers and systems the user owned and
controlled.

'False'.