COMPUTER SCIENCE CAFÉ
  • WORKBOOKS
  • BLOCKY GAMES
  • GCSE
    • CAMBRIDGE GCSE
  • IB
  • A LEVEL
  • LEARN TO CODE
  • ROBOTICS ENGINEERING
  • MORE
    • CLASS PROJECTS
    • Classroom Discussions
    • Useful Links
    • SUBSCRIBE
    • ABOUT US
    • CONTACT US
    • PRIVACY POLICY
  • WORKBOOKS
  • BLOCKY GAMES
  • GCSE
    • CAMBRIDGE GCSE
  • IB
  • A LEVEL
  • LEARN TO CODE
  • ROBOTICS ENGINEERING
  • MORE
    • CLASS PROJECTS
    • Classroom Discussions
    • Useful Links
    • SUBSCRIBE
    • ABOUT US
    • CONTACT US
    • PRIVACY POLICY

WEB SCIENCE | PHP PRINCIPLES

Topics from the International Baccalaureate (IB) 2014 Computer Science Guide. 
For Option C - Web Science, this section looks at PHP principles
ALSO IN THIS SECTION
CREATING THE WEB PART 1
CREATING THE WEB PART 2​
SEARCHING THE WEB
DISTRIBUTED APPROACHES TO THE WEB
THE EVOLVING WEB
ANALYSING THE WEB
THE INTELLIGENT WEB

​NETWORK COMPONENTS
XML AND XMLT
PHP PRINCIPLES
JAVASCRIPT PRINCIPLES

REVISION CARDS
ANSWERS

Picture

PHP PRINCIPLES

SECTION 1 | WHAT IS PHP
PHP, which stands for "PHP: Hypertext Preprocessor," is a widely-used, open-source scripting language. PHP scripts are executed on the server and the result is returned to the browser as plain HTML. It's particularly suited for web development and can be embedded into HTML.

The Role of PHP in Web Development
PHP is primarily used for server-side scripting. This means you can use PHP to create web page content dynamically, manage session tracking, or even build entire e-commerce sites. It works seamlessly with data stored in databases, making it a crucial tool for developing interactive and dynamic websites.

Server-side scripting is a critical concept in web development, where operations are performed on the server before the content reaches the user's browser. Unlike client-side scripting, where scripts run on the user's device, server-side scripts are processed on the web server. PHP is a prime example of a server-side scripting language. When a user requests a webpage, the server where the PHP scripts are stored processes these scripts. The key advantage of server-side scripting is that it enables the creation of dynamic, interactive, and customised webpages. For instance, when you log into a website, PHP scripts can process your login details, interact with a database to check your credentials, and then deliver the appropriate content to your browser. This approach not only enhances functionality and user experience but also adds a layer of security, as the underlying code is not visible or accessible to the end-user.

PHP was created by Rasmus Lerdorf in 1994. Originally designed to maintain his personal homepage, PHP has since evolved into a major scripting language used by millions of websites worldwide. Its ease of use and efficiency have made it a popular choice among developers.

PHP vs JavaScript
PHP is executed on the server, and the client receives the output without knowing what the underlying code was.
JavaScript is a client-side language, executed on the user's browser, allowing for interactive features on web pages.
Both languages are integral in web development but serve different purposes.

PHP's importance lies in its flexibility and ease of use. It's compatible with almost all servers used today and supports a wide range of databases. PHP is free to download and use, which makes it an accessible tool for programmers and developers.
SECTION 2 | BASIC SYNTAX
Syntax Overview
PHP scripts start with <?php and end with ?>. These tags enclose PHP code, which can be embedded in HTML. In PHP, statements end with a semicolon (;). Comments can be added using // for a single-line comment or /* ... */ for a multi-line comment. The echo or print statement is used to output text to the screen.

Example:
PHP

    
Variables and Data Types
Variables in PHP start with a dollar sign ($) followed by the name of the variable. PHP is a loosely typed language, which means you don't have to declare the data type of a variable. The major data types are:
  • Strings | Text values enclosed in quotes. Example: $name = "John";
  • Integers | Whole numbers. Example: $age = 25;
  • Floats (also called doubles) | Numbers with a decimal point. Example: $price = 10.50;
  • Booleans | Represents true or false. Example: $is_valid = true;

Basic Operators
Operators are used to perform operations on variables and values. PHP supports a wide range of operators, some of the basic ones include:
  • Arithmetic Operators | Used for calculations. Examples include + (addition), - (subtraction), * (multiplication), / (division), and % (modulus).
  • Assignment Operators | Used to write values to variables. The most common assignment operator is =. Example: $x = 10;
  • Comparison Operators | Used to compare two values. Examples include == (equal), != (not equal), > (greater than), < (less than).
  • Logical Operators | Used to combine conditional statements. Examples include && (and), || (or), ! (not).

​Example: A Simple PHP Script
Simple script that demonstrates variables, data types, and operators.
PHP

    
SECTION 3 | CONDITIONAL STATEMENTS
Conditional statements are used to perform different actions based on different conditions. They are essential in PHP for decision-making processes.
​
If Statement
Used to execute some code if a condition is true. Syntax:

if (condition) {
    // code to be executed if condition is true
}

If...Else Statement
Used to execute some code if a condition is true and another code if the condition is false.Syntax:

if (condition) {
    // code to be executed if condition is true
} else {
    // code to be executed if condition is false
}

If...Elseif...Else Statement
Used to specify several conditions to execute different code blocks. Syntax:

if (condition1) {
    // code if condition1 is true
} elseif (condition2) {
    // code if condition2 is true
} else {
    // code if both condition1 and condition2 are false
}

Switch Statement
The switch statement is used to perform different actions based on different conditions. It's like a series of if statements on the same expression. Syntax:

switch (n) {
    case label1:
        // code to be executed if n=label1
        break;
    case label2:
        // code to be executed if n=label2
        break;
    ...
    default:
        // code to be executed if n is different from all labels
}
SECTION 4 | LOOPS
Loops are used for executing a block of code repeatedly until a specified condition is met.

While Loop
Executes a block of code as long as the specified condition is true. Syntax:

while (condition) {
    // code to be executed
}

Do-While Loop
First executes the code block once, then checks the condition, and repeats the loop as long as the specified condition is true. Syntax:

do {
    // code to be executed
} while (condition);

For Loop
Used when you know in advance how many times you want to execute a statement or a block of statements. Syntax:

for (init counter; test counter; increment counter) {
    // code to be executed for each iteration
}

​Foreach Loop

Used for looping through a block of code for each element in an array. Syntax:

foreach ($array as $value) {
    // code to be executed
}
PHP

    
SECTION 5 | FORMS WITH PHP
Forms are a crucial part of web applications, allowing for user interaction and data collection. PHP provides powerful ways to handle form data efficiently and securely.

FORM METHODS | GET vs POST
GET Method
  • Description | Data is sent as URL parameters and is visible in the browser's address bar.
  • Usage | Suitable for form submissions where security is not a concern and data size is small.
  • PHP Retrieval | Use the global $_GET array in PHP to access the data.
  • Example | Search queries, simple data filtering.
POST Method
  • Description | Data is sent through the HTTP request body, not visible in the URL.
  • Usage | Ideal for sensitive data and large amounts of data.
  • PHP Retrieval | Use the global $_POST array in PHP to access the data.
  • Example | Login forms, data submission forms.

Basic Form Handling in PHP
HTML forms are used to collect user input. Example of a simple form:
PHP

    
​Processing Form Data in PHP
The submit.php file contains PHP code to process the form data.
PHP

    
The given lines of code are part of a PHP script that processes form data. Here is a break down each component of the code above.

if ($_SERVER["REQUEST_METHOD"] == "POST"):
  • This line checks the method used to send data to the server. $_SERVER["REQUEST_METHOD"] retrieves the request method used for accessing the page. In this case, it checks if the form data was sent using the POST method.
  • The POST method is typically used for sending form data securely as it does not append data to the URL (unlike GET method), making it a preferred choice for transferring sensitive information.

$name = htmlspecialchars($_REQUEST['name']);:
  • This line is intended to retrieve the 'name' field from the form data and sanitize it using the htmlspecialchars() function.
  • $_REQUEST['name'] fetches the value entered in the form's 'name' input field. The $_REQUEST superglobal is a combination of $_GET, $_POST, and $_COOKIE arrays and can retrieve request variables regardless of the request method.
  • htmlspecialchars() is a PHP function that converts special characters to HTML entities. This is crucial for preventing Cross-Site Scripting (XSS) attacks by ensuring that any HTML tags entered in the form are treated as plain text and not executed as code in the browser.

$email = htmlspecialchars($_REQUEST['email']);:
  • Similar to the previous line, this line retrieves the 'email' field from the form data and applies the htmlspecialchars() function.
  • It ensures that the email data entered in the form is safely processed, converting any special characters to HTML entities to avoid XSS vulnerabilities.

Security Considerations
  • Always validate and sanitise user input to protect against malicious data (e.g., using htmlspecialchars()).
  • Be cautious about the data that is displayed back to the user to prevent XSS (Cross-Site Scripting) attacks.

​This example below demonstrates a form with basic validation in PHP.
PHP

    
SECTION 6 | PHP IN WEBPAGES
Integrating PHP into web pages is a fundamental skill in web development. PHP can dynamically generate HTML content, allowing for interactive and customized user experiences.

​PHP code can be embedded directly into HTML pages. The PHP code is enclosed in PHP tags and can be placed anywhere in the HTML file.
PHP EMBEDDED IN HTML

    
In this example, PHP is used within the HTML to dynamically generate content, such as a heading and a paragraph.

PHP and HTML Forms
PHP is commonly used to process form data. When a form is submitted, PHP can handle the incoming data and perform actions like validation, database interactions, or sending emails.
PHP

    
Processing Form Data with PHP
From the process-form.php in the form action from the code above, the data collected from the input will have been posted to the PHP file.
PHP

    
​This PHP script retrieves form data, sanitizes it, and then performs an action – in this case, displaying a message with the inputted name and email.

Dynamic Content Generation
PHP can dynamically generate web page content based on different conditions, user inputs, or database interactions.

Example | Displaying Different Messages
PHP

    
The script above checks the current hour and displays a corresponding greeting message.

PHP in Client-Side Scripting
Although PHP is a server-side language, it can be used to set values or configurations for client-side scripts.

​Example | Setting JavaScript Variables with PHP
Making the variable 'serverTime' equal to current Hours, Minutes, Seconds then concatenating the varible with a string in the console.log command.
PHP

    
​Integrating PHP into web pages allows for the creation of dynamic, interactive, and personalized web experiences. The ability to embed PHP within HTML and process data like form submissions makes PHP a powerful tool in web development.
SECTION 7 | SERVER-SIDE SCRIPTING
​Server-side scripting is a powerful aspect of web development, where scripts are executed on the server rather than on the client's browser. PHP is a popular server-side scripting language used to create dynamic and interactive web pages.
​

Server-side scripting refers to scripts that run on a web server, processing user requests before sending the resulting web page to the user's browser. It handles the backend processing, database interactions, and decision-making based on user input or actions.

How Does It Work?
  • Process Flow | When a user requests a PHP page, the request is sent to the server. The PHP interpreter on the server processes the PHP script and sends back the resulting HTML to the user's browser.
  • Invisible Logic | Users do not see the PHP code, just the resulting output. This makes server-side scripting secure for sensitive operations like user authentication and data manipulation.

PHP IN SERVER-SIDE SCRIPTING
Dynamic Content Generation
  • PHP can generate HTML content dynamically. This means the web page can change based on user inputs, time of day, or other factors.
  • Example | Displaying user-specific greetings or information based on session data.

Database Interactions
  • PHP can interact with databases, such as MySQL, to store, retrieve, modify, and delete data.
  • Example | Handling user registration, login, and data retrieval for a profile page.

Handling Forms and User Input
  • PHP is commonly used to process and validate form data.
  • Example | Contact forms, search queries, and login forms.

Security in Server-Side Scripting
  • Input Validation | Ensuring that the user input is sanitized and validated to prevent SQL injection and XSS attacks.
  • Data Protection | Encrypting sensitive data and using secure protocols for data transmission.
  • Error Handling | Implementing proper error handling to prevent revealing sensitive server information.

Advantages of Server-Side Scripting
  • Flexibility and Control | Complete control over the content and structure of the web application.
  • Efficiency | Reduced load on the client side as the processing is done on the server.
  • Accessibility | Since the output is HTML, it can be accessed by any browser without the need for client-side scripting support.

Server-side scripting in PHP is a cornerstone of web development, enabling the creation of dynamic, interactive, and secure web applications. 
SECTION 7 | SERVER-SIDE SCRIPTING SCENARIO
​Let's consider a website like Amazon or eBay, where server-side scripting plays a crucial role in various functionalities. Browsing and Purchasing a Product on an E-commerce Website,  focusing on PHP as the server-side scripting language and Javascript as client-side scripting language. 

1. User Login
  • Server-Side Scripting | PHP processes login credentials and validates them against the database.
  • Client-Side Scripting | JavaScript might be used to validate the input fields (like checking if the email format is correct) before the form is submitted to the server.
2. Searching for Products
  • Server-Side Scripting |The PHP script processes the search query and retrieves product information from the database.
  • Client-Side Scripting | JavaScript could be used for autocomplete functionality in the search bar, enhancing user experience by suggesting possible search terms as the user types.
3. Displaying Product Information
  • Server-Side Scripting | PHP fetches and dynamically generates detailed product information.
  • Client-Side Scripting | JavaScript may handle interactive elements like image carousels or expanding sections for product descriptions.
4. Adding Items to Cart
  • Server-Side Scripting | PHP updates the session or database with the cart's contents.
  • Client-Side Scripting | JavaScript can be used for updating the cart icon or number of items in the cart dynamically without needing to reload the page.
5. Checkout Process
  • Server-Side Scripting | PHP manages the checkout, calculates totals, and prepares the order summary.
  • Client-Side Scripting | JavaScript might be used for form validations (like checking if the address field is filled) and updating the total cost dynamically when the user changes the quantity of items or selects different shipping options.
6. Payment Processing
  • Server-Side Scripting | PHP securely interacts with a payment gateway.
  • Client-Side Scripting | JavaScript could be employed for real-time validation of payment details (like credit card number formatting) and to enhance the user interface during the payment process.
7. Order Confirmation and Notification
  • Server-Side Scripting | PHP generates a confirmation message and triggers an automated email.
  • Client-Side Scripting | JavaScript can be used to display a success message or animation once the order is confirmed.
8. Post-Purchase Actions
  • Server-Side Scripting | PHP allows users to submit reviews and tracks user behavior for recommendations.
  • Client-Side Scripting | JavaScript might be used for interactive features like rating stars, review submission forms, and dynamically updating the page with new recommendations without a full page reload.

In this scenario, the roles of server-side scripting (PHP) and client-side scripting (JavaScript) are distinct yet complementary. Server-side scripting handles data processing, database interactions, and overall functionality logic. In contrast, client-side scripting primarily enhances user experience, provides interactivity, and validates user input in real-time.
1: What is PHP primarily used for in web development?
a) Client-side scripting
b) Server-side scripting
c) Desktop applications
d) Mobile applications

2: Which PHP statement is used to output text to the screen?
a) print
b) echo
c) output
d) display

3: How are variables in PHP represented?
a) With a hashtag (#)
b) With a dollar sign ($)
c) With an at sign (@)
d) With an underscore (_)

4: What does 'i' stand for in the PHP date format string "H:i:s"?
a) Interval
b) Instance
c) Integer
d) Minutes

5: Which method should be used for transmitting sensitive data in a form?
a) GET
b) POST
c) PUSH
d) FETCH

Open-Ended Questions
6: Explain the difference between server-side scripting and client-side scripting.

7: Describe how you would use PHP to interact with a database.

8: What are the security considerations to keep in mind when handling form data in PHP?

9: Provide an example of how a foreach loop might be used in a PHP script.

10: Explain the process flow of a user submitting a form on a website and how PHP handles this form submission.
EXAMINATION SYTLE QUESTION
Question 1: PHP Scripting and Data Handling
(a) (i) In PHP, what global arrays are commonly used to retrieve data sent from a form? [2]
(ii) Explain the purpose and typical use case for each of these arrays. [4]

(b) Describe the steps a PHP script takes to connect to a MySQL database and execute a query. Include details on the functions or methods used in each step. [4]

Consider the following PHP script for a user registration form:
<?php
  $db = mysqli_connect("serverName", "username", "password", "databaseName");
  $query = "INSERT INTO users (username, email, password) VALUES ('".$_POST["username"]."', '".$_POST["email"]."'
  , '".$_POST["password"]."')";
  mysqli_query($db, $query);
  mysqli_close($db);
?>


(c) (i) Outline the steps the server takes to process the registration form data sent from the client. [4]

In the context of web application security,
(ii) Discuss why server-side validation of form data is crucial, providing two reasons. [4]

Question 2: Data Encryption and Secure Web Transactions
(a) (i) Identify the primary purpose of using SSL certificates in web communications. [2]
(ii) Explain how SSL certificates contribute to secure communications between a web server and a client. [4]

(b) Describe the process of a secure transaction from the moment a user selects an item to purchase on an e-commerce site to the completion of the payment. [4]

Given the following PHP snippet for handling login authentication:
<?php
  $username = $_POST['username'];
  $password = sha1($_POST['password']);
  $db = new PDO("mysql:host=localhost;dbname=users", "root", "");
  $query = $db->prepare("SELECT * FROM accounts WHERE username = :username AND password = :password");
  $query->bindParam(':username', $username);
  $query->bindParam(':password', $password);
  $query->execute();
?>

(c) (i) Describe the sequence of operations performed by this PHP script during user authentication. [4]

In relation to web security,
(ii) Explain two advantages of using hashed passwords for user authentication in web applications. [4]
Picture
SUGGESTIONS
We would love to hear from you
SUBSCRIBE 
To enjoy more benefits
We hope you find this site useful. If you notice any errors or would like to contribute material then please contact us.