بسمه تعالی
Internet Engineering
Chapter 5
University of Guilan
Department of Computer Engineering
Taha Yasin Rezapour
[email protected]
@tahayasin_rezapour
“
Introduction to PHP
@tahayasin_rezapour
2
Incorporating PHP Within HTML
• PHP documents end with the extension .php .
• Your PHP program is responsible for passing back a clean file suitable for
display in a web browser.
• a PHP document will output only HTML.
• To trigger the PHP commands, you need to learn a new tag.
3 @tahayasin_rezapour
The Structure of PHP
Using Comments
.1کامنت گذاری یک خطی : •
کامنت کردن یک خط کد :
کامنت کردن یک خط متن معمولی
برای توضیحات :
.2کامنت گذاری به صورت چند خط : •
4 @tahayasin_rezapour
The Structure of PHP
Basic Syntax
5 @tahayasin_rezapour
The Structure of PHP
Tree different types of variable assignment
• Whether your variables are numbers, strings, or arrays, they should all look
something like those in here
6 @tahayasin_rezapour
The Structure of PHP
Variable-naming rules
➢ Variable names, after the dollar sign, must start with a letter of the alphabet or the _ (underscore)
character.
➢ Variable names can contain only the characters a–z, A–Z, 0–9, and _ (underscore).
➢ Variable names may not contain spaces. If a variable name must comprise more than one word, a
good idea is to separate the words with the _ (underscore) character (e.g., $user_name).
➢ Variable names are case-sensitive. The variable $High_Score is not the same as the variable
$high_score.
7 @tahayasin_rezapour
The Structure of PHP
Your first PHP program
Now you can call it up by entering the following into your browser’s address bar:
8 @tahayasin_rezapour
The Structure of PHP
Operators
از این اپراتور ها برای
انجام عملیات ریاضی از این اپراتور ها برای انتساب
استفاده می شود مقادیر به متغیر ها استفاده می شود
9 @tahayasin_rezapour
The Structure of PHP
Operators
از این اپراتور ها برای
این اپراتور ها برای انجام عملیات
مقایسه مقادیر استفاده
منطقی استفاده می شوند
می شود
10 @tahayasin_rezapour
The Structure of PHP
Variable Assignment
➢ to assign a value to a variable is always variable = value
➢ to reassign the value to another variable, it is other_variable = variable
➢ to add the value on the right (in this instance, the value 10) to the variable $x
➢ we could subtract as follows:
Variable incrementing and decrementing
➢ Adding or subtracting 1, You can use one of the following in place of the += and -= operators:
11 @tahayasin_rezapour
The Structure of PHP
String concatenation
➢ string concatenation uses the period (.) to append one string of characters to another.
➢ Assuming that the variable $msgs is set to the value 5, the output from this line of code will be the
following:
➢ you can append one string to another using .=, like this:
12 @tahayasin_rezapour
The Structure of PHP
String types
➢ PHP supports two types of strings that are denoted by the type of quotation mark that you
use. If you wish to assign a literal string, preserving the exact contents, you should use
single quotation marks (apostrophes), like this:
➢ On the other hand, when you want to include the value of a variable inside a string,
you do so by using double-quoted strings
➢ This is called variable substitution.
13 @tahayasin_rezapour
The Structure of PHP
Escaping characters
➢ Sometimes a string needs to contain characters with special meanings that might be
interpreted incorrectly.
➢ To correct this, you can add a backslash directly before the offending quotation mark
to tell PHP to treat the character literally and not to interpret it:
➢ For example, the following double-quoted string will be correctly assigned:
➢ tabs, newlines, and carriage returns
14 @tahayasin_rezapour
The Structure of PHP
Multiline Commands
➢ There are times when you need to output quite a lot of text from PHP, and using several echo (or
print) statements would be time-consuming and messy.
➢ To overcome this, PHP offers two conveniences. The first is just to put multiple lines between
quotes, as in Example:
15 @tahayasin_rezapour
The Structure of PHP
Multiline Commands
➢ PHP also offers a multiline sequence using the <<< operator —commonly referred to
as a here-document or heredoc— as a way of specifying a string literal, preserving the
line breaks and other whitespace (including indentation) in the text.
16 @tahayasin_rezapour
The Structure of PHP
Variable Typing
➢ PHP is a loosely typed language. This means that variables do not have to be declared before they
are used and that PHP always converts variables to the type required by their context when they are
accessed
➢ the numbers 12345 and 67890 are multiplied together, returning a result of 838102050, which is
then placed in the variable $number
substr ( string $string , int $start [, int $length ] ) : string
17 @tahayasin_rezapour
The Structure of PHP
Constants
➢ Constants are similar to variables, holding information to be accessed later, except that they are
what they sound like—constant. In other words, once you have defined one, its value is set for the
remainder of the program and cannot be altered.
➢ For example, you can use a constant to hold the location of your server root
➢ Then, to read the contents of the variable, you just refer to it like a regular variable
➢ whenever you need to run your PHP code on a different server with a different folder
configuration, you have only a single line of code to change.
18 @tahayasin_rezapour
The Structure of PHP
The Difference Between the echo and print Commands
➢ The two commands are quite similar, but print is a function-like construct that takes a single
parameter and has a return value , whereas echo is purely a PHP language construct. Since both
commands are constructs, neither requires parentheses.
➢ By and large, the echo command usually will be a tad faster than print, because it doesn’t set a
return value. On the other hand, because it isn’t implemented like a function, echo cannot be
used as part of a more complex expression, whereas print can.
19 @tahayasin_rezapour
The Structure of PHP
Functions
➢ Functions separate sections of code that perform a particular task.
➢ Placing code into a function not only shortens your program and makes it more
readable but also adds extra functionality, because functions can be passed parameters to make
them perform differently. They can also return values to the calling code.
This function returns a date in the format
Friday May 2nd 2025.
➢ To output today’s date using this function, place the following call in your code:
20 @tahayasin_rezapour
The Structure of PHP
Variable Scope
➢ If you have a very long program, it’s quite possible that you could start to run out of good variable
names, but with PHP you can decide the scope of a variable.
➢ In fact, this is the default scope for PHP variables.
➢ Alternatively, you could inform PHP that a variable is global in scope and thus can be accessed by
every other part of your program.
Local variables
➢ Local variables are variables that are created within, and can be accessed only by, a function. They
are generally temporary variables that are used to store partially processed results prior to the
function’s return.
➢ One set of local variables is the list of arguments to a function.
21 @tahayasin_rezapour
The Structure of PHP
Global variables
➢ There are cases when you need a variable to have global scope, because you want all your code
to be able to access it.
➢ Also, some data may be large and complex, and you don’t want to keep passing it as arguments
to functions.
➢ To access variables from global scope, add the keyword global.
➢ Let’s assume that you have a way of logging your users in to your website and want all your code
to know whether it is interacting with a logged-in user or a guest. One way to do this is to use the
global keyword before a variable, such as $is_logged_in:
➢ Now your login function simply has to set that variable to 1 upon a successful login attempt or 0
upon failure.
22 @tahayasin_rezapour
The Structure of PHP
Static variables
➢ If a function runs many times, it starts with a fresh copy of the variable, and the previous setting has
no effect.
➢ Here’s an interesting case. What if you have a local variable inside a function that you don’t want any
other parts of your code to have access to, but you would also like to keep its value for the next time
the function is called? Why? Perhaps because you want a counter to track how many times a
function is called.
23 @tahayasin_rezapour
The Structure of PHP
Superglobal variables
➢ Starting with PHP 4.1.0, several predefined variables are available. These are known as
superglobal variables, which means that they are provided by the PHP environment but are global
within the program, accessible absolutely everywhere.
24 @tahayasin_rezapour
The Structure of PHP
TRUE or FALSE?
➢ A basic Boolean value can be either TRUE or FALSE. For example, the expression 20 > 9 (20 is
greater than 9) is TRUE, and the expression 5 == 6 (5 is equal to 6) is FALSE.
➢ PHP arbitrarily assigns a numerical value of 1 to TRUE, so 1 is displayed after a: when the example
runs. Even more mysteriously, because b: evaluates to FALSE, it does not show any value. In PHP
the constant FALSE is defined as NULL, another predefined constant that denotes nothing.
25 @tahayasin_rezapour
The Structure of PHP
TRUE or FALSE?
➢ The <br> tags are there to create line breaks
and thus separate the output into two lines in
➢ The output from this code is:
HTML. Here is the output:
➢ PHP arbitrarily assigns a numerical value of 1 to TRUE, so 1 is displayed after a: when the example
runs. Even more mysteriously, because b: evaluates to FALSE, it does not show any value. In PHP the
constant FALSE is defined as NULL, another predefined constant that denotes nothing.
26 @tahayasin_rezapour
The Structure of PHP
Literals and Variables
➢ Example below shows three literals and two variables, all of which return values, albeit of
different types.
27 @tahayasin_rezapour
The Structure of PHP
Operators
28 @tahayasin_rezapour
The Structure of PHP
Associativity
➢ some operators require processing from right to left,
and this direction of processing is called the
operator’s associativity.
➢ For example, let’s take a look at the assignment
operator in Example below, where three variables are
all set to the value 0.
➢ This multiple assignment is possible only if the
rightmost part of the expression is evaluated first and
then processing continues in a right-to-left direction.
29 @tahayasin_rezapour
The Structure of PHP
Logical operators
30 @tahayasin_rezapour
The Structure of PHP
Conditionals
➢ Conditionals alter program flow. They enable you to ask questions about certain things and respond
to the answers you get in different ways.
The if Statement
➢ The contents of the if condition can be any valid PHP expression, including tests for equality,
comparison expressions, tests for 0 and NULL, and even functions (either built-in functions or ones
that you write)
➢ imagine that it is the end of
the month and all your bills
have been paid, so you are
performing some bank
account maintenance.
31 @tahayasin_rezapour
The Structure of PHP
Conditionals
The else Statement
➢ Sometimes when a conditional is not TRUE, you may not want to continue on to the main program
code immediately but might wish to do something else instead. This is where the else statement
comes in.
➢ With an if...else statement, the first conditional
statement is executed if the condi‐ tion is TRUE.
But if it’s FALSE, the second one is executed.
One of the two choices must be executed. Under
no circumstance can both (or neither) be
executed.
32 @tahayasin_rezapour
The Structure of PHP
Conditionals
The elseif Statement
➢ There are also times when you want a number of different
possibilities to occur, based upon a sequence of
conditions .
➢ In the example, an elseif statement has been inserted
between the if and else statements. It checks whether your
bank balance exceeds $200 and, if so, decides that you
can afford to save $100 this month.
33 @tahayasin_rezapour
The Structure of PHP
Conditionals
The switch Statement
➢ The switch statement is useful where one variable, or the result of an expression, can have multiple
values, each of which should trigger a different activity.
➢ For example, consider a PHP-driven menu
system that passes a single string to the main
menu code according to what the user requests.
Let’s say the options are Home, About, News,
Login, and Links, and we set the variable $page
to one of these, according to the user’s input.
➢ If we write the code for this using if...elseif...else,
it might look like Example:
34 @tahayasin_rezapour
The Structure of PHP
Conditionals
The switch Statement
➢ If we use a switch statement, the code might look like Example :
➢ As you can see, $page is mentioned only once at the start of the switch
statement. Thereafter, the case command checks for matches. When
one occurs, the matching conditional statement is executed.
➢ If you wish to break out of the switch statement because a condition
has been fulfilled, use the break command. This command tells PHP to
exit the switch and jump to the following statement.
➢ A typical requirement in switch statements is to fall back on a default
action if none of the case conditions are met.
35 @tahayasin_rezapour
The Structure of PHP
Conditionals
The ? (or ternary) Operator
➢ One way of avoiding the verbosity of if and else statements is to use the more compact ternary
operator, ?, which is unusual in that it takes three operands rather than the typical two.
➢ The ? operator is passed an expression that it must evaluate, along with two statements to execute:
one for when the expression evaluates to TRUE, the other for when it is FALSE.
➢ Example below shows code we might use for writing a warning about the fuel level of a car to its
digital dashboard.
36 @tahayasin_rezapour
The Structure of PHP
Looping while Loops
➢ One of the great things about ➢ As with if statements, you will notice that curly
computers is that they can repeat braces are required to hold the statements inside
calculating tasks quickly and tirelessly. the while statements, unless there’s only one.
Often you may want a program to
repeat the same sequence of code
again and again until something
happens, such as a user inputting a
value or reaching a natural end. PHP’s
loop structures provide the perfect way
to do this.
37 @tahayasin_rezapour
The Structure of PHP
Looping
Do … while Loops
➢ A slight variation to the while loop is the do...while loop, used when you want a block of code to be
executed at least once and made conditional only after that.
➢ Example below shows a modified version of the code for the 12 times table that uses such a loop.
38 @tahayasin_rezapour
The Structure of PHP
Looping
For Loops
➢ The final kind of loop statement, the for loop, is also the most powerful, as it combines the abilities to
set up variables as you enter the loop, test for conditions while iterating loops, and modify variables
after each iteration.
➢ Each for statement takes three
parameters:
• An initialization expression
• A condition expression
• A modification expression
These are separated by semicolons like this: for (expr1 ; expr2 ; expr3).
39 @tahayasin_rezapour
The Structure of PHP
Looping
comparing between for and while loops
➢ The for loop is explicitly designed around a single value that changes on a regular basis.
➢ Usually you have a value that increments, as when you are passed a list of user choices and want to
process each choice in turn. But you can transform the variable any way you like.
➢ A more complex form of the for statement even lets you perform multiple operations in each of the
three parameters:
➢ The key is to distinguish commas from semicolons.
➢ in the previous example, the first and third parameters each contain two statements:
➢ So, when is a while statement more appropriate than a for statement? When your condition doesn’t
depend on a simple, regular change to a variable. For instance, if you want to check for some special
40 input or@tahayasin_rezapour
error and end the loop when it occurs, use a while statement.
The Structure of PHP
Looping
Breaking Out of a Loop
➢ Just as you saw how to break out of a switch statement, you can also break out of a for loop (or any
loop) using the same break command.
The continue Statement
➢ The continue statement is a little like a break statement, except that it instructs PHP to stop
processing the current iteration of the loop and move right to its next iteration. So, instead of breaking
out of the whole loop, PHP exits only the current iteration.
➢ This approach can be useful in cases where you know
there is no point continuing execution within the
current loop and you want to save processor cycles or
prevent an error from occurring by moving right along
to the next iteration of the loop.
41 @tahayasin_rezapour
سواالت
دو نوع تگ رایج که برای قرار دادن توضیح ها در کد phpبکار می روند کدامند؟ .I
چرا عالمت خط زیر در نام متغیرها مثل $current_userمجاز است اما عالمت خط تیره در متغیری مثل $current-userمجاز نیست؟ .II
تفاوت بین ++$jو $j++در چیست؟ .III
تفاوت دستور echoو printرا بیان کنید. .IV
چگونه میتوان یک عالمت نقل قول را مهار کرد؟ .V
دلیل قدرتمند تر بودن حلقه forنسبت به حلقه whileدر چیست؟چگونه دستورهای ifو whileعبارت های شرطی با انواع داده های .VI
مختلف را تفسیر می کنند؟
.VIIیک سیستم منوی مبتنی بر PHPرا در نظر بگیرید که طبق درخواست کاربر ،یک رشته واحد را به کد منوی اصلی ارسال می کند .فرض کنید
گزینهها Login ،News ،About ،Homeو Linksهستند و ما با توجه به ورودی کاربر ،متغیر $pageرا برای مشخص کردن یکی از
این گزینه ها در نظر گرفته ایم ،کد این عمل را یک بار با ساختار if…elseif…elseو یکبار با استفاده از دستور switchبنویسید.
42 @tahayasin_rezapour
سواالت
.VIIIحلقه forشامل چه پارامترهایی است؟توضیح دهید.
خروجی کد زیر را بنویسید. .IX
43 @tahayasin_rezapour