Web Development 1 - Lecture 1 - PHP

Download as pdf or txt
Download as pdf or txt
You are on page 1of 30

Web Development 1

Lecture 1 – Getting started with PHP

1
Contents 1/2
• History
• Language
• How it works
• What it looks like
• Configuration
• Debugging
• Development environment

2 Web Development 1
Contents 2/2
• HTTP requests
• GET URL parameters
• + in class programming exercise

• POST form data


• + in class programming exercise

3 Web Development 1
History lesson
Rasmus Lerdorf developed PHP in 1994 to provide
server-side functionality for his personal homepage.

The first release to the public was in 1995. A year later, PHP was used on
15.000 websites.

PHP used to stand for Personal Home Page tools, but eventually PHP:
Hypertext Preprocessor (a recursive acronym 🤔) was chosen as the
official meaning of PHP in 1998.
4 Web Development 1
How many websites use PHP?
https://w3techs.com/technologies/details/pl-php

5
The language
The PHP syntax is based on C, with its familiar variables, control structures
(if/elseif/else, switch and various loops), scoping with { } and parameterized
functions or methods. There is also support for classes (OOP)!
Luckily for us, this means you can get quite far in PHP with your knowledge
of C# and Java. We will not explain these language basics in this course.
There are some important differences that we will discuss. For example, PHP
supports string interpolation out of the box, by prefixing all variable names
with $. Also, PHP is not a compiled language but an interpreted language.

6 Web Development 1
How it works
PHP is an interpreted language. The PHP parser processes the lines of code
in a PHP file. This means we essentially run source code!
Suppose a browser requests http://mywebsite.com/index.php. PHP then
interprets this file and generates the HTML that is sent back to the browser.

7 Web Development 1
What PHP looks like
<?php We could also write
echo 'Hello $myvariable!‘ (single quotes),
$myvariable = "world"; What would the difference be?

echo "Hello $myvariable!";


?>
• A PHP script is always opened with <?php and closed with ?>.
• “The file itself has .php as an extension.
• Variables are always preceded by a $ sign.
• Note the variables are ‘loosely-typed’. PHP determines the data type.
•8 ‘echo’ writes1 variables to the screen.
Web Development
Operators
Familiar operators can be used, such as +, -, *, /, <, >
But we also have ** for power (3**2 = 9)

We have == to check if the content is the same, and === to check if both
content and type are equal:
$x = 1, means that ‘$x becomes 1’
$x == 1, means ‘is $x equal to 1?’
$x === 1, means ‘is $x identical to 1?’

And we have the dot . instead of the plus + to concatenate strings:


$result = “Ham"." ".“burger", will mean $result becomes “Ham burger”
9 Web Development 1
PHP configuration
PHP is configured in the php.ini file. We can open and modify this file using any text editor.
To see all configuration settings, you can call the phpinfo() function from a PHP script:

<?php
phpinfo();
?>

10 Web Development 1
PHP debugging
Research among PHP developers has shown that most do not use a debugger
with breakpoints and code stepping as we are used to from C#/Java.
Instead, PHP developers just run their files and watch for errors.

<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// the code above forces errors to show


?>
11 Web Development 1
What do we need to develop PHP?
• A browser – To view our work
• A code editor – To write our code
• A webserver application – To process HTTP requests and forward them to PHP
• The PHP interpreter – To interpret the PHP code
• A database engine – For dynamic data storage
• A database management tool – For example PHPMyAdmin
We could manually install all this
We could use an all-in-one package, for example Xampp (https://www.apachefriends.org/)
We could use Docker and use a preconfigured image
12 Web Development 1
Next steps
Install Docker 🐳 and set it up (I mailed you a link to a github repo to get started)
Note: If you haven’t used docker before, it can be daunting. But it is worth the challenge!

If you prefer any other method, go for it!


However, if you don’t use docker, the grading teacher cannot replicate your development
environment. Discuss with your teacher how to deal with this issue.

13 Web Development 1
Let’s get a cup of tea
(and check on your development environment – The next part of the
lecture will be more practical!)
Part 2
Goals:
• A deep understanding of HTTP request processing by a web server
• Know about HTTP status codes
• Passing data to PHP using the URL (GET request)
• Passing data to PHP using a form (POST request)

15 Web Development 1
HTTP requests
HyperText Transfer Protocol was developed for communication between web clients
(browsers) and webservers. The protocol describes various request and response
messages.
Today, most websites should use https: HyperText Transfer Protocol Secure.
This adds encryption to HTTP messages through the TLS protocol. TLS requires installing a
trusted certificate on the webserver, which can be free (Let’s Encrypt) or paid (Verisign)

HTTP describes the format of messages between client/server

TLS encrypts http messages


TCP establishes a reliable communication session
IP locates another system and transfers data

16 Web Development 1
HTTP GET request
Suppose you open your browser and enter: www.inholland.nl.
What does the browser actually send to the server?
Answer: a HTTP GET request that describes what the client wants from the server:

GET /actueel HTTP/1.1


Host: www.inholland.nl
Connection: keep-alive
Cache-Control: max-age=0
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106
Safari/537.36
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8
Accept-Encoding: gzip, deflate
Accept-Language: nl-NL,nl;q=0.9,en-US;q=0.8,en;q=0.7

17 Web Development 1
HTTP GET response
Of course, we see a web page in the browser. This is because the web server replied to our
GET request with a response
The response contains headers and the HTML content:
HTTP/1.1 200 OK
Date: Mon, 10 Sep 2021 12:16:56 GMT
Server: Kestrel
Content-Type: text/html; charset=utf-8
Vary: Accept-Encoding
Content-Encoding: gzip
Content-Length: 1355
Keep-Alive: timeout=5, max=100
Connection: Keep-Alive

<!DOCTYPE html>
<html>….and the rest of the web page content appears here but does not fit on the slide 

18 Web Development 1
HTTP status code
Note the first line:
HTTP/1.1 200 OK

200 OK is the HTTP status code. This tells the client what to expect. There are various
categories of status codes, some of which you probably encountered before:

1xx: Informational (e.g., 100: Continue


2xx: Success (e.g., 200: OK, 201: Created & 202: Accepted)
3xx: Redirect (e.g., 307: temporary redirect & 308: permanent redirect)
4xx: Client error (e.g., 401: unauthorized & 404: not found)
5xx: Server error (e.g., 500: internal server error & 503: Service unavailable)

19 Web Development 1
HTTP methods
So far, we only discussed the GET request. GET is what we call an HTTP method. Not to be
confused with methods in a programming language.
The most used HTTP methods (message types) are:
• GET: Retrieves data from the server
• POST: Sends data to the server
• PUT: Updates data on the server
• DELETE: Removes data from the server
A normal web browsing session usually only consists of GET and POST requests.

20 Web Development 1
Sending data using the URL
We discussed that HTTP GET is meant for retrieving data from the server. But can we send
data to the server in a GET request?

Ever noticed those long URLs like:


http://www.somewebsite.com/index.php?name1=value1&someguid= 182964a8-668c-4990-
8e73-fb7c7c3ec9ae

21 Web Development 1
Sending data using the URL
We can send parameters to a PHP script using the URL.
The part behind the ? is what we call the query string. This allows us to pass parameters.
For example, we can call our script like this:
demo.php?name=rasmus&birthdate=1968-11-22
In PHP code, we have access to the $_GET array. This contains all URL query parameters.
To access the name that is sent in the URL, we simply access:
$_GET[‘name’]

Can we write some code to display the name and age? Let’s do an exercise.

22 Web Development 1
In-class exercise
Write a script that retrieves a name and birthdate from URL parameters:
demo.php?name=rasmus&birthdate=1968-11-22
Then display the name and age on the resulting webpage.
Hints
• PHP code goes in a .php file in your web root
• PHP code is written between <?php and ?>
• Variables do not require a datatype and start with $, for example: $name = “Rasmus”
• Output can be generated using echo, for example: echo “His name is $name”;
• URL parameters are stored in an array called $_GET[]
• A string can be converted to a date using the function strtotime
• Functions can be looked up on php.net
23 Web Development 1
POST request
So far, we discussed HTTP GET request.
But how can we send data using a POST request?
A common way is to use an HTML form with it’s method specified as post.
<form action="/formdemo.php" method="POST">
<label for="firstname">First name:</label><br>
<input type="text" id="firstname" name="firstname" value="John"><br>
<label for="lastname">Last name:</label><br>
<input type="text" id="lastname" name="lastname" value="Doe"><br><br>
<input type="submit" value="Submit">
</form>

24 Web Development 1
POST request
<form action="/formdemo.php" method="POST">
<label for="firstname">First name:</label><br>
<input type="text" id="firstname" name="firstname" value="John"><br>
<label for="lastname">Last name:</label><br>
<input type="text" id="lastname" name="lastname" value="Doe"><br><br>
<input type="submit" value="Submit">
</form>
If we submit this form to a PHP script (by clicking the submit button), the form field data is
available in the array $_POST[]
For example, $_POST["firstname"] will contain the contents of the first input field.

25 Web Development 1
In-class exercise
Copy the script from the last exercise. Rewrite it into a script that retrieves the name and
birthdate from a form.
You can write the form in the same script as the processing code, but then make sure to
gracefully handle what happens if the form has not yet been posted (and $_POST does not
contain any data).
Hints
• You might want to use input type ‘date’ in your HTML form
• Set the method attribute of the form to POST
• Form field data is stored in an array called $_POST[]
• The index in this array is determined by the name attribute of the form field
• The form action attribute determines the URL that the form is posted to.
If you leave this empty, the form will post to the current URL of the page.
26 Web Development 1
Summary & next steps
Today, you learned:
• What PHP is and how to use it to respond to HTTP GET and POST requests
• using echo and $variables to display and work with data
• using phpinfo() to show the PHP configuration in php.ini
• using error messages and settings to do php debugging
• understanding HTTP requests and status codes
• using the $_GET[] and $_POST[] arrays to work with externally provided data

In the next lecture, we will discuss:


• Working with relational databases in PHP.

27 Web Development 1
Homework
The Web Development 1 exam is an individual application development project.
Your first homework is to write a proposal for this project.
More details can be found on Moodle.

28 Web Development 1
Any questions?

29 Web Development 1

You might also like