0% found this document useful (0 votes)
2 views

Introduction to PHP

PHP is a server-side scripting language used for creating dynamic web pages and runs on various operating systems. It features a syntax inspired by C and Perl, supports file operations, form data handling, and database interactions, and allows for variable manipulation and conditional statements. The document also covers PHP's variable naming rules, string handling, and basic operators.

Uploaded by

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

Introduction to PHP

PHP is a server-side scripting language used for creating dynamic web pages and runs on various operating systems. It features a syntax inspired by C and Perl, supports file operations, form data handling, and database interactions, and allows for variable manipulation and conditional statements. The document also covers PHP's variable naming rules, string handling, and basic operators.

Uploaded by

hamdhhhhi0
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 51

INTRODUCTION TO PHP

PHP
 PHP is a server scripting language, and is a
powerful tool for making dynamic and interactive
Web pages quickly
 PHP is a widely-used, and free.

 PHP runs over different operating systems such as

Windows, Linux, Mac Os and Unix.


 PHP scripts are executed on the server, and the

plain HTML result is sent back to the browser.


ABOUT THE PHP LANGUAGE
• Syntax is inspired by C
• Curly braces, semicolons, no signficant
whitespace
• Syntax inspired by perl
• Dollar signs to start variable names,
associative arrays
• Extends HTML to add segments of PHP within an
HTML file.
WHAT CAN PHP DO?
 PHP can generate dynamic page content
 PHP can create, open, read, write, delete, and close

files on the server.


 PHP can collect form data.

 PHP can send and receive cookies.

 PHP can add, delete, modify data in your database.

 PHP can restrict users to access some pages on

your website.
 PHP can encrypt data.
INTRODUCTION
• Documents end with the extension .php

• To trigger the PHP commands, you need <?php


tag.
and they finish only when the closing part ?> is
encountered
Example:
<?php
echo "Hello world";
?>
<h1>Hello from Dr. Chuck's HTML Page</h1>
<p>
<?php
echo "Hi there.\n";
$answer = 6 * 7;
echo "The answer is $answer, what ";
echo "was the question again?\n";
?>
</p>
<p>Yes another paragraph.</p>
KEY WORDS
abstract and array() as break case
catch class clone const continue
declare default do else elseif end
declare endfor endforeach endif
endswitch endwhile extends final for
foreach function global goto if
implements interface instanceof
namespace new or private protected
public static switch $this throw try use
var while http://php.net/manual/en/
xor
reserved.php
VARIABLE NAMES

• Start with a dollar sign ($) followed by a letter or


underscore, followed by any number of letters,
numbers, or underscores
• Case matters

$abc = 12; abc = 12;


$total = 0; $2php = 0;
$largest_so_far = 0; $bad-punc = 0;

http://php.net/manual/en/
language.variables.basics.php
VARIABLE NAMING RULES
• Variable names 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 must comprise more than one word, the
words should be separated 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.
VARIABLE NAME WEIRDNESS

• Things that look like variables but are missing a


dollar sign can be confusing

$x = 2; $x = 2;
$y = x + 5; y = $x + 5;
print $y; print $x;

5
Print $x // 2
Parse error
Parse error: syntax error, unexpected '=' in C:\xampp\htdocs\vtes.php on line 2
EXPRESSIONS
• Completely normal like other languages ( + - /
*)
• More agressive implicit type conversion

<?php
$x = "15" + 27;
echo($x); 42
echo("\n");
?>
ARITHMETIC OPERATORS

• They are used to perform mathematics.


ASSIGNMENT OPERATORS
• These operators are used to assign
values to variables.
• Strings have their own operator, the
period (.), detailed in the section
“String concatenation”
COMPARISON OPERATORS

• Comparison operators are


generally used inside a
construct such as an if
statement in which you
need to compare two
items.
LOGICAL OPERATORS

• For example, you might


say to yourself, “If the
time is later than 12 PM
and earlier than 2 PM,
then have lunch.” In PHP,
• if ($hour > 12 && $hour < 14) dolunch();
VARIABLE ASSIGNMENT
 The syntax to assign a value to a variable is always:
variable = value
Ex. $x += 10;
 Variable incrementing and decrementing
 Adding or subtracting 1 operation
 Prefix form: ++$x; --$y;
Ex: if (++$x == 10) echo $x;
 This tells PHP to first increment the value of $x and then test whether it has the
value 10 and, if so, output its value.
 Postfix form: ++$x; --$y;
Ex: if ($y−− == 0) echo $y;
 Suppose $y starts out as 0 before the statement is executed. The comparison will
return a TRUE result, but $y will be set to −1 after the comparison is made.
So what will the echo statement display: 0 or −1?
VARIABLE TYPING
 In php, variables do not have to be declared before they are used.
 PHP always converts variables to the type required by their context when they
are accessed.
 you can create a multiple-digit number and extract the nth digit from it, simply
by assuming it to be a string.
<?php
$number = 12345 * 67890; //=838102050
echo substr($number, 3, 1);//(number,position, no.of char)
?>

 $number is a numeric variable.


 But the PHP function substr asks for one character to be returned from $number
 PHP turns $number into a nine-character string.
 so that substr can access it and return the character, which in this case is 1.
CONT.
 The same goes for turning a string into a number
 The variable $pi is set to a string value automatically turned into a
floating-point in the third line by the equation for calculating a circle’s
area
 Example: Automatically converting a string to a number
<?php
$pi = "3.1415927";
$radius = 5;
echo $pi * ($radius * $radius);
?>
OUTPUT
<?php
• echo is a language construct -
$x = "15" + 27;
can be treated like a function
echo $x;
with one parameter. Without
echo("\n");
parenthesis, it accepts echo $x, "\n";
multiple parameters. print $x;
• print is a function - only one print "\n";
print($x);
parameter but parenthesis
are optional so it can look like print("\n");
a language construct ?>
ECHO COMMANDS

• echo command used in a number of different ways to


output text from the server to your browser.
• In some cases, a string literal has been output.
echo “welcome in php”;
• In others, strings have first been concatenated.
$x=7;
echo “the number is = “.$x;
• or variables have been evaluated.
$x=7;
echo “the number is = $x“;
• It was Also shown the output spread over multiple
lines.
THE DIFFERENCE BETWEEN THE
ECHO AND PRINT COMMANDS
 an alternative to echo that you can use: print.
 The two commands are quite similar to each other, but print is an actual
function that takes a single parameter, whereas echo is a PHP language
construct.
 Echo is faster than print in general text output, because is not being a
function—it doesn’t set a return value.
 echo cannot be used as part of a more complex expression, whereas print
can.

Example:
$b=7; $a=1;
$b ? print "TRUE" : print "FALSE";// TRUE
$a>=$b ? print "TRUE" : print "FALSE";// FALSE
CONDITIONAL - IF
• Logical operators ( == != < > <= >= && || ! )
•\ Curly braces
<?php
$ans = 42;
if ( $ans == 42 )
{
print "Hello world!\n";
}
else { Hello World!
print "Wrong
answer\n";
}
WHITESPACE DOES NOT
MATTER
<?php
$ans = 42;
if ( $ans == 42 ) {
print "Hello world!\n";
} else {
print "Wrong answer\n";
}
?>

<?php $ans = 42; if ( $ans == 42 ) { print


"Hello world!\n"; } else { print "Wrong answer\n"; }
?>
WHAT STYLE DO YOU
PREFER?

<?php
$ans = 42;
<?php if ( $ans == 42 )
$ans = 42; {
if ( $ans == 42 ) { print "Hello world!\n";
print "Hello world!\n"; }
} else { else
print "Wrong answer\n"; {
} print "Wrong answer\n";
?> }
?>
Aesthetic
s
ASSOCIATIVE ARRAYS
• Like Python Dictonaries+Lists - but more
powerful
• Can be key => value or simply indexed by
numbers
• Ignore two-dimensional arrays for now...
INTEGER INDICES

<?php
$stuff = array("Hi", "There");
echo $stuff[1], "\n";
?>

There
INTEGER INDICES
<?php
$stuff = array();
$stuff[] = "Hello";
$stuff[] = "World";

echo $stuff[1], "\n";


?>

World
INTEGER INDICES
<?php
$stuff = array();
$stuff[2] = "Hello";
$stuff[9] = "World";

echo $stuff[9], "\n";


?>

World
KEY / VALUE
<?php
$stuff = array("name" => "Chuck",
"course" => "SI664");
echo $stuff["course"], "\n";
?>

SI664
DUMPING AN ARRAY

• The function print_r() dumps out PHP data - it is


used mostly for debugging
<?php
$stuff = array("name" =>
"Chuck",
"course"
=> "SI664");
print_r($stuff); Array
?> (
[name] => Chuck
[course] => SI664
)
DUMPING AN ARRAY

• The function print_r() dumps out PHP data - it is


used mostly for debugging
<?php
$stuff = array();
$stuff[2] = "Hello";
$stuff[9] = "World";
print_r($stuff);
?> Array
(
[2] => Chuck
[9] => SI664
)
VAR_DUMP .VS. PRINT_R
<?php
$stuff = array("name" => "Chuck",
"course" => "SI664");
var_dump($stuff);
?>
array(2) {
["name"]=>
string(5) "Chuck"
["course"]=>
string(5) "SI664"
}

http://stackoverflow.com/questions/3406171/php-var-d
VAR_DUMP() IS MORE
VERBOSE

<?php
$thing = FALSE;
echo("One\n");
print_r($thing);
echo("Two\n"); One
var_dump($thing); Two
?> bool(false)

http://stackoverflow.com/questions/3406171/php-var-d
LOOPING THROUGH AN
ARRAY
<?php
$stuff = array("name" => "Chuck",
"course" => "SI664");
foreach($stuff as $k => $v ) {
echo "Key=",$k," Val=",$v,"\n";
}
?>

Key=name Val=Chuck
Key=course Val=SI664
VARIABLE NAME WEIRDNESS

• Things that look like variables but are missing a


dollar sign as an array index are
unpredictable....

$x = 5; $x = 5;
$y = array("x" => $y = array("x" =>
"Hello"); "Hello",5=>"newwwww");
print $y[“x”]; print $y[“5”];

Hello newwwww
STRINGS
• String literals can use single quotes or double quotes
• The backslash (\) is used as an "escape" character
• Strings can span multiple lines - the newline is part
of the string
• In double-quoted strings variable values are
expanded

http://php.net/manual/en/
language.types.string.php
Single
<?php
Quote
echo 'this is a simple string';

echo 'You can also have embedded newlines in


strings this way as it is
okay to do';

// Outputs: Arnold once said: "I'll be back"


echo 'Arnold once said: "I\'ll be back"';

// Outputs: This will not expand: \n a newline


echo 'This will not expand: \n a newline';

// Outputs: Variables do not $expand $either


echo 'Variables do not $expand $either';
?>
Double
<?php Quote
echo "this is a simple string\n";

echo "You can also have embedded newlines in


strings this way as it is
okay to do";

// Outputs: This will expand:


// a newline
echo "This will expand: \na newline";

// Outputs: Variables do 12
$expand = 12;
echo "Variables do $expand\n";
?>
COMMENTS
<?php
echo 'This is a test'; // This is a c++ style comment
/* This is a multi line comment
yet another line of comment */
echo 'This is yet another test';
echo 'One Final Test'; # This is a shell-
style comment
?>
http://php.net/manual/en/language.basic-
syntax.comments.php
STRING VARIABLES
• The quotation marks indicate that “Fred Smith” is a string of
characters.
$username = "Fred Smith";
• to see what’s in the variable :
echo $username
• Or you can assign it to another variable
$current_user = $username;
STRING CONCATENATION
• String concatenation uses the period (.)
operator to append one string of characters to
another.
Ex: echo "You have " . $msgs . " messages.";
• Assuming that the variable $msgs is set to the
value 5, the output will be:You have 5 messages.
• you can append one string to another using .=
like this:
Ex: $bulletin .= $newsflash;
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 the single quotation
mark (apostrophe), like this:
Ex: $info = 'Preface variables with a $ like this:
$variable';
CONT. STRING TYPES
• In this case, every character within the single-quoted
string is assigned to $info.
• If you had used double quotes, PHP would have attempted
to evaluate $variable as a variable.
• when you want to include the value of a variable inside a
string, you do so by using a double-quoted string:
Ex: echo "There have been $count presidents of
the US";
• this syntax also offers a simpler form of concatenation This
is called variable substitution.
ESCAPING CHARACTERS
• Sometimes a string needs to contain
characters with special meanings that might be
interpreted incorrectly.
• For example, the following line of code will not
work:
$text = 'My sister's car is a Ford'; // Erroneous syntax
• Because the apostrophe encountered in the
word sister’s will tell the PHP parser that the
end of the string has been reached.
• To correct this, you can add a backslash
$text = 'My sister\'s car is a Ford';
CONT. ESCAPING CHARACTERS
 Examples:
$text = "My Mother always said \"Eat your greens\".";
• you can use escape characters to insert various special
characters into strings, such as tabs, newlines, and
carriage returns.
• These are represented by \t, \n, and \r.
$heading = "Date\tName\tPayment";
• These special backslash-preceded characters work only in
double-quoted strings.
• In single-quoted strings, the preceding string would be
displayed with the ugly \t sequences instead of tabs.
• Within single-quoted strings, only the escaped
apostrophe(\') and the escaped backslash itself (\\) are
recognized as escaped characters.
MULTIPLE-LINE COMMANDS
• There are times when you need to output quite a lot of
text from PHP
• using several echo (or print) statements would be time-
consuming
• To overcome this, PHP offers two conveniences:
• The first is just to put multiple lines between quotes
<?php
$author = "Alfred E Newman";
echo "This is a Headline
This is the first line.
This is the second.
Written by $author.";
?>
CONT.
• Variables can also be assigned, as:
<?php
$author = "Alfred E Newman";
$text = "This is a Headline
This is the first line.
This is the second.
Written by $author.";
?>
• Second alternative multiline echo statement, PHP offers a
multiline sequence using the <<< operator.
• commonly referred to as here-document or heredoc for
short.
CONT.
• This is a way of specifying a string literal, preserving the line breaks
and other whitespace (including indentation) in the text.
<?php
$author = "Alfred E Newman";
echo <<<_END
This is a Headline
This is the first line.
This is the second.
- Written by $author.
END;
?>
• this code tell PHP to output everything between the two _END tags as
if it were a double-quoted string.
• This means it’s possible,for a developer to write entire sections of
HTML directly into PHP code and then just replace specific dynamic
parts with PHP variables.
CONT. _END
 enclosing _END tag must appear right at the start of a
new line
 and must be the only thing on that line, no comment and
no spaces are allowed.
• Once you have closed a multiline block, you are free to
use the same tag name again.
• Remember: using the <<<_END..._END; heredoc
construct, you don’t have to add \n line-feed characters to
send a line feed—just press Return and start a new line.
• Also, unlike either a double-quote- or single-quote
delimited string, you are free to use all the single and
double quotes you like within a heredoc, without escaping
them by preceding them with a backslash (\).
CONT.
• Example: shows how to use the same syntax to assign multiple
lines to a variable.
<?php
$author = "Alfred E Newman";
$out = <<<_END
This is a Headline
This is the first line.
This is the second.
- Written by $author.
_END;
?>
• The variable $out will then be populated with the contents
between the two tags.
• If you were appending rather than assigning, you also could
have used .= in place of = to append the string to $out.
SUMMARY
• This is a sprint through the language features of
PHP

You might also like