You are on page 1of 73

PHP Introduction

CMPS 246: Web Programming

Web Programming 1
Server-side programming

The type of web programming we have been doing so far is called


client-side programming:
- The code we write gets run in a browser on the user's
(client's) machine

Today we will begin to learn about server-side programming:


- The code we write gets run on a server.
- Servers are computers that run programs to generate web
pages and other web resources.

Web Programming 2
Let’s review how clients and
servers work...

Web Programming 3
CLIENT: You type a URL in
the address bar and hit
"enter"
http://www.bau.edu.lb

Web Programming 4
Browser sends an HTTP GET
request saying "Please GET me
the index.html file at
http://www.bau.edu.lb

Let’s review this process...

Web Programming 5
GET main/index/HTTP/1.1
Host: bau.edu.lb
Browser C++ code creates an
array of bytes that is formatted
in HTTP request message
format

Browser asks operating system,


"Hey, can you send this HTTP Get
request message to
http://www.bau.edu.lb"?

Web Programming 6
DNS
Server
Operating system sends a
DNS query to look up the IP
address of DNS server replies with the
(Routing,
http://www.bau.edu.lb etc…) IP address, e.g.
171.67.215.200

Web Programming 7
171.67.215.200

Operating system opens a


TCP connection with the
computer at (Routing,
etc…)
171.67.215.200

Web Programming 8
171.67.215.200

Client
(Routing,
etc…)
Server

A TCP connection is established between the


client and the server computer, so now the
client and server can send messages directly to
teach other.

Web Programming 9
171.67.215.200

On this computer is a web server program:


- The web server program is listening for incoming
messages that are sent to it.
- The web server program can respond to messages that
are sent to it.

php: The language we will use to write scripts that get


executed on the web server

Web Programming 10
OS to server program (HTTP Request):
"Hey, here's a message that was sent to me."

171.67.215.200

Now the operating system is receiving TCP packets from


the wire, and the operating system begins sending the
contents of the request to the server program.

Web Programming 11
OS to server program (HTTP Request):
"Hey, here's a message that was sent to me."

171.67.215.200

Server program to OS (HTTP Response):


"OK, can you send this message back to
the client?"

Web Programming 12
(Routing,
etc…)

This HTTP response is then sent


back to the client's OS, which
notifies the browser of the HTTP
response, and then the browser
displays the web page.

Web Programming 13
Summary
When you navigate to a URL:
- Browser creates an HTTP GET request
- Operating system sends the GET request to the server over TCP
When a server computer receives a message:
- The server's operating system sends the message to the server software
- The server software then parses the message
- The server software creates an HTTP response
- The server OS sends the HTTP response to the client over TCP

Client Server

(Routing,
etc…)

Web Programming 14
PHP Language
Web Programming 15
Introduction
• acronym for “PHP: Hypertext Preprocessor”
• It is a widely-used open source general-purpose scripting language
• suited for web development and can be embedded into HTML.

Web Programming 16
Introduction
• PHP is a server-side scripting language (executed on the server)
• PHP supports many databases (more on this later)
• PHP is open source software
• PHP is free to download and use

Web Programming 17
Introduction
• Instead of lots of commands to output HTML, PHP pages contain
HTML with embedded code that does "something" (like in the next
slide, it outputs "Hi, I'm a PHP script!").

• The PHP code is enclosed in special start and end processing


instructions <?php and ?> that allow you to jump into and out of PHP
mode.

Web Programming 18
PHP Example

Web Programming 19
PHP Introduction

Web Programming 20
PHP Getting Started
• You need a webserver to host and parse php code
• Find a web host with PHP and MySQL support
• You can download and install XAMPP on your pc
• With one installation and you get an Apache webserver, database server and php.

https://www.apachefriends.org/download_success.html

Web Programming 21
Viewing PHP files
• The default file extension for PHP files is ".php".
• PHP files executed on the web server
• Therefore we cannot save them anywhere and view them, as with
HTML files
• Must save .php files in subdirectory of web server
• <xamp_location>/xampp/htdocs/<php_script>.php
• Make call to web server via localhost if on your own computer

Web Programming 22
HelloWorld.php

Above is the PHP source code.

Web Programming 23
HelloWorld.php
It renders as HTML that looks like this:

Web Programming 24
PHP Hello World
• This program is extremely simple and you really did not need to use
PHP to create a page like this.
• All it does is display: Hello World using the PHP echo() statement.

• Think of this as a normal HTML file which happens to have a set of


special tags available to you that do a lot of interesting things.

Web Programming 25
PHP Syntax
Web Programming 26
Same as Java and Javascript
for-loops:
for ( $ i =0 ; $i < 5 ; $i + + ) { … }
while-loops:
while (notFinished) { … }
comments:
/ / comment or / * comment* /
conditionals (if statements):
if(...){
...
} else{
...
}
Web Programming 27
PHP Variables
• All variables in PHP start with a $ sign symbol.
• The correct way of declaring a variable in PHP:

• In PHP, similar to Javascripts, a variable does not need to be declared


before adding a value to it.
• PHP automatically converts the variable to the correct data type,
depending on its value.
Web Programming 28
PHP Variables

• A variable name must start with a letter or an underscore "_"


• A variable name can only contain alpha-numeric characters,
underscores (a-z, A-Z, 0-9, and _ )

Web Programming 29
PHP Concatenation
• The concatenation operator (.) is used to put two string values
together.
• To concatenate two string variables together, use the concatenation
operator:

https://www.w3schools.com/php/php_string.asp
Web Programming 30
PHP Concatenation

• The output of the code on the last slide will be:

• If we look at the code you see that we used the concatenation


operator two times. This is because we had to insert a third string (a
space character), to separate the two strings.

Web Programming 31
PHP Arrays
• In PHP, there are three kind of arrays:
• Numeric array - An array with a numeric index
• Associative array - An array where each ID key is associated with a value
• Multidimensional array - An array containing one or more arrays

Web Programming 32
PHP Numeric Arrays
• A numeric array stores each array element with a numeric index.
• There are two methods to create a numeric array.

Web Programming 33
PHP Associative Arrays
• With an associative array, each ID key is associated with a value.
• When storing data about specific named values, a numerical array is
not always the best way to do it.
• With associative arrays we can use the values as keys and assign values
to them.

Web Programming 34
PHP Associative Arrays

Web Programming 35
PHP Multidimensional Arrays

•In a multidimensional array, each element in the main array can also be
an array.

•And each element in the sub-array can be an array, and so on.

Web Programming 36
PHP Multidimensional Arrays

Web Programming 37
PHP Multidimensional Arrays

Web Programming 38
PHP Functions (same as Javascript)
One way of defining a PHP function is with the following syntax:

F u n c t i o n name() {
statement;
statement;
...
}

Web Programming 39
PHP Functions
A simple function that writes a name when it is called:

Web Programming 40
PHP Superglobals
Web Programming 41
Superglobals
• A few special associative arrays that can be accessed from anywhere
in a PHP file
• Always $_ALLCAPS
• The $_SERVER superglobal gives information about server and client
• $_SERVER[‘SERVER_ADDR’] → server IP
• $_SERVER[‘REMOTE_ADDR’] → client IP
• $_SERVER[‘HTTP_USER_AGENT’] → client OS and browser

Web Programming 42
Passing information to the server
• Sometimes, we require additional values from client to server
• Login: username and password
• Form information to be stored on server

• pass information via the URL


• Access values server-side using $_GET or $_POST superglobal
• $_GET[‘firstparam’] => ‘firstvalue’
• $_POST[‘secondparam’] => ‘secondvalue’

Web Programming 43
$_GET Function
• The built-in $_GET function is used to collect values from a form sent
with method="get".
• Information sent from a form with the GET method is visible to
everyone
• displayed in the browser's address bar
• has limits on the amount of information to send (max. 100
characters).

Web Programming 44
$_GET Function

Notice how the URL carries the information after the file name.

Web Programming 45
$_GET Function
• When using method="get" in HTML forms, all variable names and
values are displayed in the URL.
• This method should not be used when sending passwords or other
sensitive information!
• However, because the variables are displayed in the URL, it is possible
to bookmark the page. This can be useful in some cases.
• The get method is not suitable for large variable values; the value
cannot exceed 100 chars.

Web Programming 46
$_POST Function
• The built-in $_POST function is used to collect values from a form sent
with method="post".
• Information sent from a form with the POST method is invisible to
others and has no limits on the amount of information to send.

Web Programming 47
$_POST Function

And here is what the code of action.php might look like:

Web Programming 48
$_POST Function

•Apart from htmlspecialchars() and (int), it should be obvious what this


does. htmlspecialchars() makes sure any characters that are special in
html are properly encoded so people can't inject HTML tags or Javascript
into your page.

•For the age field, since we know it is a number, we can just convert it to
an integer which will automatically get rid of any stray characters. The
$_POST['name'] and $_POST['age'] variables are automatically set for you
by PHP.

Web Programming 49
$_POST Function
• When to use method="post"?
• Information sent from a form with the POST method is invisible to
others and has no limits on the amount of information to send.
• However, because the variables are not displayed in the URL, it is not
possible to bookmark the page.

Web Programming 50
PHP Example
Web Programming 51
Login System

Signup and login


https://www.youtube.com/watch?v=8K4Wt37Itc4

Verification
https://www.youtube.com/watch?v=C-ZSQMbsm7A

Web Programming 52
signup.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Register</title>
</head>
<body>

</body>
</html>

Web Programming 53
Using Precompiled CSS file from
BootstrapCDN
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/c
ss/bootstrap.min.css">

(add to html header)

See https://getbootstrap.com/

Web Programming 54
Form
<body>

<div class="container">
<div class="row">
<div class="col-md-4 form-div">
<form action="signup.php" method="post">
</form>
</div>
</div>
</div>

</body>

Web Programming 55
Header

<h3 class="text-center">Register</h3>

Web Programming 56
Username Textfield

<div class="form-group">
<label for="username">Username</label>
<input type="text" name="username"
class="form-control form-control-lg">
</div>

Web Programming 57
Similarly for Email, Password and Confirm
Password
<div class="form-group">
<label for="email">Email</label>
<input type="text" name="email" class="form-control form-control-lg">
</div>

<div class="form-group">
<label for="password">Password</label>
<input type="password" name="password" class="form-control form-control-lg">
</div>

<div class="form-group">
<label for="passwordConf">Confirm Password</label>
<input type="password" name="passwordConf" class="form-control form-control-lg">
</div>

Web Programming 58
Sign Up Button

<div class="form-group">
<button type="submit" name="signup-btn"
class="btn btn-primary btn-block btn-lg">
Sign Up
</button>
</div>

Web Programming 59
Already a member? Message

<p class="text-center">
Already a member?
<a href="login.php">Sign In</a>
</p>

Web Programming 60
Using your own style.css file

.form-div{ link rel="stylesheet" href="style.css">


margin: 50px auto 50px;
(add to html header)
padding: 25px 15px 10px 15px;
border: 1px solid #80ced7;
border-radius: 5px;
font-size: 1.1em;
}

Web Programming 61
Do the same for the login.php page

Web Programming 62
index.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Home</title>
</head>
<body>

</body>
</html>

Web Programming 63
No form needed

<body>

<div class="container">
<div class="row">
<div class="col-md-4 form-div">
</div>
</div>
</div>

</body>

Web Programming 64
Logged in alert

<div class="alert alert-success">


You are now logged in!
</div>

Web Programming 65
Welcome message

<h3>Welcome, Lama</h3>

Web Programming 66
Logout link + css style

<a href=“index.php" class="logout">Logout</a>

.logout{
color: red;
}

Web Programming 67
Verification alert

<div class="alert alert-warning">


You need to verify your account.
Verfication email sent to you at
<strong>email@email.com</strong>
</div>

Web Programming 68
Test the webpages

Web Programming 69
authController.php
• Create controllers/authController.php

• Include it into signup.php and login.php


<?php require_once ’controllers/authController.php'; ?>

Web Programming 70
Get entered variables if user presses submit
$username = "";
$email = "";

if(isset($_POST['signup-btn'])){
$username=$_POST['username'];
$email=$_POST['email'];
$password=$_POST['password'];
$passwordConf=$_POST['passwordConf’];
}

Web Programming 71
Validate Entries
$errors = array();

//validation
if(empty($username)){
$errors['username'] = "Username Required";
}
if(empty($email)){
$errors['email'] = "Email Required";
}
if(empty($password)){
$errors['password'] = "Password Required";
}
if($password!==$passwordConf){
$errors['passwordConf'] = "Passwords don't match!";
}
Web Programming 72
Display errors on signup.php

<?php if(count($errors)>0):?>
<div class="alert alert-danger">
<?php foreach($errors as $error): ?>
<li><?php echo $error; ?></li>
<?php endforeach?>
</div>
<?php endif?>

Web Programming 73

You might also like