Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
2 views

php (1)

This PHP tutorial provides an overview of PHP as a server-side scripting language, covering its capabilities, syntax, data types, and variable handling. It includes sections on installation, improvements in PHP 7, operators, conditional statements, loops, functions, arrays, and form handling. Additionally, it emphasizes the importance of data validation and sanitization in web applications.

Uploaded by

ann karagwa
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

php (1)

This PHP tutorial provides an overview of PHP as a server-side scripting language, covering its capabilities, syntax, data types, and variable handling. It includes sections on installation, improvements in PHP 7, operators, conditional statements, loops, functions, arrays, and form handling. Additionally, it emphasizes the importance of data validation and sanitization in web applications.

Uploaded by

ann karagwa
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 33

PHP TUTORIAL

GROUP J
Group J
INTRODUCTION
What is PHP?
· PHP stands for "PHP: Hypertext Preprocessor," originally "Personal Home Page."
· It is an open-source server-side scripting language for web development.
· PHP scripts run on the server, and the output is returned as HTML.
· PHP is free to download and use.

PHP File Basics


· PHP files can include text, HTML, CSS, JavaScript, and PHP code.
· PHP code is executed on the server, outputting HTML to the browser.
· Files typically have a .php extension.

PHP Capabilities
· Manage files (create, read, write, delete).
· Collect and process form data.
· Handle cookies and sessions.
· Perform database operations (add, delete, modify data).
· Control user access and encrypt data.
· Output content including HTML, JSON, XML, images, and PDFs.
IMPROVEMENTS AND INSTALLATION
PHP 7 Improvements
· Faster performance than PHP 5.6.
· Improved error handling with throwable exceptions.
· Stricter type declarations for function arguments.
· New operators like the spaceship operator (<=>).

INSTALLATION LINKS
https://www.youtube.com/watch?v=-dfJUm2qXA8 for macOS
https://www.youtube.com/watch?v=vUxr0yYiQbE for Linux
https://www.youtube.com/watch?v=n04w2SzGr_U for windows

WEBSITES FOR DOWNLOADING PHP


https://www.php.net/
SYNTAX
SYNTAX AND COMMENTS
php script can be placed anywhere in the document
A PHP script starts with <?php and ends with ?>
The default file extension for PHP files is ".php".
A PHP file normally contains HTML tags, and some PHP scripting code
With a PHP script that uses a built-in PHP function "echo" to output the text
In PHP, keywords (e.g. if, else, while, echo, etc.), classes, functions, and user-defined functions
are not case-sensitive. However; all variable names are case-sensitive!

COMMENTS IN PHP
A comment in PHP code is a line that is not executed as a part of the program. Its only
purpose is to be read by someone who is looking at the code.
Comments can be used to:
· Let others understand your code
· Remind yourself of what you did
· Leave out some parts of your code
Single line comments start with //. You can also use # for single line comments
Mulitple line comment are written as /**/
Definition:
PHP VARIABLES
· Variables are "containers" for storing information in PHP.
· Declared using a $ followed by the variable name.

Example:
$x = 5;
$y = "John";

Rules for Naming Variables:


· Must start with a letter or _.
· Cannot start with a number.
· Can contain alphanumeric characters and _.
· Case-sensitive ($age ≠ $AGE).

Output Variables:
· Use echo or print to display values.
echo $x; // Outputs 5
VARIABLE SCOPE
Variable Scopes:
1. Local Scope: Declared within a function.
2. Global Scope: Declared outside a function.
3. Static Scope: Retains value between function
calls.

Global Keyword Example:


$x = 5; $y = 10;

function add() {
global $x, $y;
$y = $x + $y;
}

add();
echo $y; // Outputs 15
DATA TYPES AND LOOSE TYPING
PHP Data Types:
· String: "Hello World!"
· Integer: 42
· Float: 3.14
· Boolean: true/false
· Array: [1, 2, 3]
· Object: Created using a class.
· NULL: No value assigned.
· Resource: Reference external resources (e.g., database).

Loose Typing:
· PHP determines data type based on value.

Example:
$x = "Hello"; // String
$x = 42; // Integer
STRING MANIPULATIONS AND
NUMERIC OPERATIONS
String Functions:
· strlen($str) - Length of string.
· strtoupper($str) - Converts to uppercase.
· str_replace("find", "replace", $str) - Replace text.
· explode(",", $str) - Splits string into an array.

Numeric Operations:
· Check Type: is_int(), is_float(), is_numeric().
· Casting:
$x = (int) "42"; // String to Integer
$y = intval(4.9); // Float to Integer

· Infinity & NaN:


is_infinite($value);
is_nan($value);
PHP CASTING
Casting refers to changing a variable from one data type to
another.

Casting is done with these statements


·(string)-converts to data type string
·(int)-converts to data type integer
·(float)-converts to data type float
·(bool)-converts to data type Boolean
·(array)-converts to data type Array
·(object)-converts to data type Object
·(unset)-converts to data type NULL

General syntax
$x=5; //Original variable that is an integer
$y=(float)$x; //$y is the new data type variable
to which $x has been cast.

Londrina Shadow
PHP MATH
We can use a set of mathematical functions to perform
certain mathematical tasks which include the following;

· pi() function returns the value of PI.


· min() and max() functions can be used to the lowest and
highest values in a list if arguments.
· abs() returns the positive(absolute) value.
· sqrt() returns the square root of a number.
· round() rounds a floating number to the nearest integer.
· rand() function generates a random number.
PHP CONSTANTS
Constants are variables except that once they are declared
they cannot be changed.

Unlike variables, constants are automatically global across


the entire script.
To create a constant, we use the define() function

Syntax
define(name, value) where;
· name: specifies the name of the constant.
· value: specifies the value of the constant.
PHP MAGIC CONSTANTS
PHP has predefined constants that change value depending on where
they are used. And they are called magic constants.

These magic constants are listed below with their descriptions;


· _CLASS_ -If used inside a class, the class name is returned
· _DIR_ -The directory of the file
· _FILE_ -The file name including the full path
· _FUNCTION_ -If inside a function, the function name is returned
· _LINE_ -The current line number
· _METHOD_ -If used inside a function that belongs to a class, both
class and function name is returned.
· _NAMESPACE_ -If used inside a namespace, the name of the
namespace is returned.
· _TRAIT_ -If used inside a trait, the trait name is returned.
· ClassName::class -Returns the name of the specified class and the
name of the namespace, if any.
NB: The magic constants are case-insensitive.
PHP OPERATORS
Operators are used to perform operations on variables and
values.

They are divided into the following groups.


1. Arithmetic operators
They perform numeric operations such as subtraction, addition,
multiplication etc on numeric values.
They include; +, -, *, /, %, **

2. Assignment operators
These assign numeric values to variables. e.g., =, +=, -=, *=, /=, %=

3. Comparison operators
These compare two values.
They include; ==, ===,!=, <>, !==, >, <, >=,<=, <=>
4. Increment/Decrement Operators
The increment operators are used to increase a variable’s
value whereas the decrement operators decrement a
variables value.
They include; ++,--

5. Logical operators
They are used to combine conditional statements.
They include; and, or, xor ,&&,||,!

6. String operators
These are designed specifically for strings.
They include;
· . concatenation
· .= concatenation assignment
CONDITIONAL STATEMENTS
Conditional statements are used to perform different actions
based on different conditions.

if statement - executes some code


. if one condition is true

if…else statement - executes some code if a condition is true


and another code if that condition is false

if…elseif...else statement - executes different codes for more


than two conditions

switch statement - selects one of many blocks of code to be


executed.
2. To check more than one condition, we can use logical operators, like:
&& logical and operator
|| logical or operator
! logical not operator

3. If statements usually contain conditions that compare two values.


== Equal Returns true if the values are equal
=== Identical Returns true if the values and data types are identical
! = Not Equal Returns true if the values are not equal
> Greater than returns true if the first value is greater than the second value
4.Shorthand if
This if is used when you want to write if statements on
one line.

5. You can have if statements inside if statements, this


is called nested if statements.
SWITCH STATEMENT
The switch statement is used to perform different actions based on different
conditions.
Use the switch statement to select one of many blocks of code to be
executed.

THE break KEYWORD


·When PHP reaches a break keyword, it breaks out of the switch block.
·This will stop the execution of more code, and no more cases are tested.
·The last block does not need a break, the block breaks (ends) there anyway.

Warning: If you omit the break statement in a case that is not the last, and
that case gets a match, the next case will also be executed even if the
evaluation does not match the case.
SYNTAX
switch (expression) {
case label1:
//code block
break;
case label2:
//code block;
break;
case label3:
//code block
break;
default:
//code block
}
This is how it works:
The expression is evaluated once
The value of the expression is compared with the values of each case
If there is a match, the associated block of code is executed
The break keyword breaks out of the switch block
The default code block is executed if there is no match
LOOPS
Loops are used to execute the same block of code again and again, as
long as a certain condition is true.

In PHP, we have the following loop types:


while- loops through a block of code as long as the specified condition
is true.

NB: With the break statement we can stop the loop even if the condition is
still true:

2. With the continue statement we can stop the current iteration, and
continue with the next.
do…while - loops through a block of code at least once, and then
repeats the loop as long as the specified condition is true.

for - loops through a block of code a specified number of times.

for (expression1, expression2, expression3) {


// code block
}

This is how it works:


Ø expression1 is evaluated once
Ø expression2 is evaluated before each iteration
Ø expression3 is evaluated after each iteration

foreach - loops through a block of code for each element in an array.


FUNCTIONS
A function is a block of code that performs a specific task.
To let a function return a value, use the return statement:

1. PHP has over 1000 built-in functions that can be called directly, from
within a script, to perform a specific task.

2. Besides the built-in PHP functions, it is possible to create your own


functions.
A user-defined function declaration starts with the keyword function,
followed by the name of the function:
function myMessage(){
//code
}
3.Some functions have ARGUMENTS. These arguments are just like
variables.
Arguments are specified after the function name, inside the parentheses.
Ie:
function familyName($fname)

4. Use of a default parameter. If we call the function that is supposed to


take in arguments without arguments it takes the default value as
argument:

ie: setting the default value


function setHeight($minheight = 50)
ARRAYS
You can create arrays by using the array() function.

1. INDEXED ARRAY
In indexed arrays each item has an index number.
By default, the first item has index 0, the second item has item 1, etc.

NB: You can use the array_push() function to add a new item or multiple items
to the array.

2.ASSOCIATIVE ARRAYS
· Associative arrays are arrays that use named keys that you assign to them.
· To access an array item, you can refer to the key name.
· To add items to an associative array, or key/value array, use brackets [] for
the key, and assign value with the = operator.
3.SORTING ARRAY ELEMENTS
sort() - sort arrays in ascending order ie, sort($arrayname)
rsort () - sort arrays in descending order
asort () - sort associative arrays in ascending order, according to the
value
ksort () - sort associative arrays in ascending order, according to the key
arsort () - sort associative arrays in descending order, according to the
value
krsort () - sort associative arrays in descending order, according to the
key

4. MULTI-DIMENSIONAL ARRAYS
A multidimensional array is an array containing one or more arrays.
To get access to the elements of the $cars array we must point to the two
indices (row and column)
PHP FORMS
What is Form Handling?
The process of collecting and processing user inputs
submitted via HTML forms.

Why is it important?
Forms are the primary way users interact with web
applications (e.g., login pages, registration forms, search
bars).

PHP's Role:
PHP processes form inputs, validates data, and interacts with
databases or APIs.
RECEIVING FORM DATA IN PHP
$_POST vs. $_GET :
$_POST : Used for secure data transmission (e.g., passwords).
$_GET : Sends data via the URL (e.g., for search queries).

Accessing Data:
BASIC FORM STRUCTURE

Key attributes:
action : Specifies the PHP file to process the form.
method : Defines the HTTP method ( GET or POST ).
VALIDATING FORM DATA
Why validate?
Ensure data integrity and security.

Types of validation:
Client-side validation: Done via JavaScript or HTML5
attributes.
Server-side validation (in PHP): Ensures data is valid
even if client-side validation is bypassed.
SANITIZING USER INPUT
Why sanitize?
Prevent malicious input (e.g., SQL injection, XSS attacks).
Group J
THANK YOU

You might also like