SlideShare a Scribd company logo
1 of 8
Mohammad Imam Hossain, Lecturer, dept. of CSE, UIU. Email: imambuet11@gmail.com
Introduction to PHP (Hypertext Preprocessor)
PHP Tags:
When PHP parses a file, it looks for opening and closing tags, which are <?php and ?> which tell PHP to start and stop
interpreting the code between them. Parsing in this manner allows PHP to be embedded in all sorts of different
documents, as everything outside of a pair of opening and closing tags is ignored by the PHP parser.
<p>This is going to be ignored by PHP and displayed by the browser.</p>
<?php echo 'While this is going to be parsed.'; ?>
<p>This will also be ignored by PHP and displayed by the browser.</p>
For outputting large blocks of text, dropping out of PHP parsing mode is generally more efficient than sending all of the
text through echo or print.
<?php if ($expression == true){ ?>
This will show if the expression is true.
<?php } else { ?>
Otherwise this will show.
<?php } ?>
PHP Comments:
<?php
echo 'This is a test'; // This is a one-line 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 one-line shell-style comment
?>
PHP Datatypes:
Boolean (TRUE/FALSE) – case insensitive
False – FALSE, 0, -0, 0.0, -0.0, “”, “0”, array with zero elements, NULL (including unset variables)
True – Every other value including NAN
Integer
<?php
$a = 1234; // decimal number
$a = -123; // a negative number
$a = 0123; // octal number (equivalent to 83 decimal)
$a = 0x1A; // hexadecimal number (equivalent to 26 decimal)
$a = 0b11111111; // binary number (equivalent to 255 decimal)
?>
0 = False, Null
1 = True
Mohammad Imam Hossain, Lecturer, dept. of CSE, UIU. Email: imambuet11@gmail.com
Floating Point Numbers
<?php
$a = 1.234;
$b = 1.2e3;
$c = 7E-10;
?>
Strings (Single quoted/ Double quoted)
<?php
echo 'this is a simple string';
// Outputs: Arnold once said: "I'll be back"
echo 'Arnold once said: "I'll be back"';
// Outputs: You deleted C:*.*?
echo 'You deleted C:*.*?';
// 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';
?>
<?php
$juice = "apple";
echo "He drank some $juice juice.";
?>
<?php
$str = 'abc';
var_dump($str[1]);
var_dump(isset($str[1]));
?>
. (DOT) – to concat strings
“1” – True
“” – False/ Null
Array
<?php
$array = array(
"foo" => "bar",
"bar" => "foo",
);
$array1 = array("foo", "bar", "hello", "world");
var_dump($array1);
?>
Mohammad Imam Hossain, Lecturer, dept. of CSE, UIU. Email: imambuet11@gmail.com
<?php
$array = array(
"foo" => "bar",
42 => 24,
"multi" => array(
"dimensional" => array(
"array" => "foo"
)
)
);
var_dump($array["foo"]);
var_dump($array[42]);
var_dump($array["multi"]["dimensional"]["array"]);
?>
<?php
$arr = array(5 => 1, 12 => 2);
$arr[13] = 56; // This is the same as $arr[13] = 56;
// at this point of the script
$arr["x"] = 42; // This adds a new element to
// the array with key "x"
unset($arr[5]); // This removes the element from the array
unset($arr); // This deletes the whole array
?>
PHP Variables:
Variables in PHP are represented by a dollar sign followed by the name of the variable. The variable name is case-
sensitive.
<?php
$a = 1; /* global scope */
function test()
{
echo $a; /* reference to local scope variable */
}
test();
?>
<?php
$a = 1;
$b = 2;
function Sum()
{
$GLOBALS['b'] = $GLOBALS['a'] + $GLOBALS['b'];
}
Sum();
echo $b;
?>
Mohammad Imam Hossain, Lecturer, dept. of CSE, UIU. Email: imambuet11@gmail.com
Predefined Variables:
$GLOBALS – References all variables available in global scope
<?php
function test() {
$foo = "local variable";
echo '$foo in global scope: ' . $GLOBALS["foo"] . "n";
echo '$foo in current scope: ' . $foo . "n";
}
$foo = "Example content";
test();
?>
$_SERVER – server and execution environment information
<?php
$indicesServer = array(
'PHP_SELF',
'SERVER_ADDR',
'SERVER_NAME',
'SERVER_PROTOCOL',
'REQUEST_METHOD',
'REQUEST_TIME',
'QUERY_STRING',
'DOCUMENT_ROOT',
'HTTPS',
'REMOTE_ADDR',
'REMOTE_HOST',
'REMOTE_PORT',
'REMOTE_USER',
'SERVER_PORT',
'SCRIPT_NAME',
'REQUEST_URI') ;
echo '<table style=”width:100%;”>' ;
foreach ($indicesServer as $arg) {
if (isset($_SERVER[$arg])) {
echo '<tr><td>'.$arg.'</td><td>' . $_SERVER[$arg] . '</td></tr>' ;
}
else {
echo '<tr><td>'.$arg.'</td><td>-</td></tr>' ;
}
}
echo '</table>' ;
?>
$_GET – an associative array of variables passed to the current script via the URL parameters
$_POST – an associative array of variables passed to the current script via the HTTP POST method when using
application/x-www-form-urlencoded or, multipart/form-data as the HTTP
$_FILES – an associative array of items uploaded to the current script via the HTTP POST method
$_REQUEST -- An associative array that by default contains the contents of $_GET, $_POST and $_COOKIE.
$_SESSION -- An associative array containing session variables available to the current script.
$_COOKIE -- An associative array of variables passed to the current script via HTTP Cookies.
Mohammad Imam Hossain, Lecturer, dept. of CSE, UIU. Email: imambuet11@gmail.com
Operators and Operator Precedence:
visit here  https://www.php.net/manual/en/language.operators.php
Control Structures:
if-elseif-else statement
<?php
if ($a > $b) {
echo "a is bigger than b";
} elseif ($a == $b) {
echo "a is equal to b";
} else {
echo "a is smaller than b";
}
?>
while loop
<?php
$i = 1;
while ($i <= 10) {
echo $i++; /* the printed value would be
$i before the increment
(post-increment) */
}
?>
do-while loop
<?php
$i = 0;
do {
echo $i;
} while ($i > 0);
?>
for loop
<?php
for ($i = 1; $i <= 10; $i++) {
echo $i;
}
?>
foreach loop
<?php
$a = array(1, 2, 3, 17);
$i = 0;
foreach ($a as $v) {
echo "$a[$i] => $v.n";
$i++;
}
$a = array(
"one" => 1,
"two" => 2,
Mohammad Imam Hossain, Lecturer, dept. of CSE, UIU. Email: imambuet11@gmail.com
"three" => 3,
"seventeen" => 17
);
foreach ($a as $k => $v) {
echo "$a[$k] => $v.n";
}
//multi-dimensional array
$a = array();
$a[0][0] = "a";
$a[0][1] = "b";
$a[1][0] = "y";
$a[1][1] = "z";
foreach ($a as $v1) {
foreach ($v1 as $v2) {
echo "$v2n";
}
}
?>
break, continue, switch, return
similar as before
include/require
The include/require statement includes and evaluates the specified file. The include construct will emit a warning if it
cannot find a file; this is different behavior from require, which will emit a fatal error.
within vars.php file
<?php
$color = 'green';
$fruit = 'apple';
?>
within test.php file
<?php
echo "A $color $fruit"; // A
include 'vars.php';
echo "A $color $fruit"; // A green apple
?>
include_once / require_once
The include_once statement includes and evaluates the specified file during the execution of the script. This is a
behavior similar to the include statement, with the only difference being that if the code from a file has already been
included, it will not be included again, and include_once returns TRUE. As the name suggests, the file will be included
just once.
<?php
var_dump(include_once 'fakefile.ext'); // bool(false)
var_dump(include_once 'fakefile.ext'); // bool(true)
?>
Mohammad Imam Hossain, Lecturer, dept. of CSE, UIU. Email: imambuet11@gmail.com
Functions:
<?php
$makefoo = true;
/* We can't call foo() from here
since it doesn't exist yet,
but we can call bar() */
bar();
if ($makefoo) {
function foo()
{
echo "I don't exist until program execution reaches me.n";
}
}
/* Now we can safely call foo()
since $makefoo evaluated to true */
if ($makefoo) foo();
function bar()
{
echo "I exist immediately upon program start.n";
}
?>
<?php
function foo()
{
function bar()
{
echo "I don't exist until foo() is called.n";
}
}
/* We can't call bar() yet
since it doesn't exist. */
foo();
/* Now we can call bar(),
foo()'s processing has
made it accessible. */
bar();
?>
///anonymous functions in PHP
<?php
$greet = function($name)
{
printf("Hello %srn", $name);
};
$greet('World');
$greet('PHP');
?>
Mohammad Imam Hossain, Lecturer, dept. of CSE, UIU. Email: imambuet11@gmail.com
Some Functions:
Variable Handling
Functions
empty($var) -- Determine whether a variable is empty i.e. it doesn’t exist or value equals FALSE.
isset($var) -- Determine if a variable is declared and value is different than NULL
unset($var) -- Unset a given variable or, destroys a variable
print_r ($var) -- Prints human-readable information about a variable
var_dump($var) -- Dumps information about a variable
Array Functions count($a) -- Count all elements in an array
array_key_exists('first', $search_array) -- Checks if the given key or index exists in the array
array_keys($array) -- Return all the keys of an array
array_values($array) -- Return all the values of an array
array_push($stack, "apple", "raspberry") -- Push one or more elements onto the end of array
array_pop($stack) -- Pop the element off the end of array
array_unshift($queue, "apple", "raspberry") -- Prepend one or more elements to the beginning
of an array
array_shift($stack) -- Shift an element off the beginning of array
array_search('green', $array) -- Searches the array for a given value and returns the first
corresponding key if successful
array_slice($input, 0, 3) -- Extract a slice of the array
array_splice($input, -1, 1, array("black", "maroon")) -- Remove a portion of the array and
replace it with something else
sort($array), rsort($array), ksort($array), krsort($array)
String Functions strlen(‘abcd’) -- Get string length
echo "Hello World" -- Output one or more strings
explode(" ", $pizza) -- split a string by a string
implode(",", $array) -- Join array elements with a string
htmlentities("A 'quote' is <b>bold</b>") -- Convert all applicable characters to HTML entities
html_entity_decode(“I'll &quot;walk&quot; the &lt;b&gt;dog&lt;/b&gt”) -- Convert HTML
entities to their corresponding characters
htmlspecialchars($str) — Convert special characters to HTML entities
htmlspecialchars_decode($encodedstr) — Convert special HTML entities back to characters
md5($password) – calculate the md5 hashing of user string
sha1($password) – calculate the sha1 hashing of user string
parse_str($str,$output_array) -- Parses the string into variables
example:
$str = "first=value&arr[]=foo+bar&arr[]=baz";
// Recommended
parse_str($str, $output);
echo $output['first']; // value
echo $output['arr'][0]; // foo bar
echo $output['arr'][1]; // baz

More Related Content

What's hot

Prevent merging columns in excel output using rtf template
Prevent merging columns in excel output using rtf templatePrevent merging columns in excel output using rtf template
Prevent merging columns in excel output using rtf templateFeras Ahmad
 
Difference Between HTML and HTML5
Difference Between HTML and HTML5Difference Between HTML and HTML5
Difference Between HTML and HTML5Bapu Graphics India
 
javaScript.ppt
javaScript.pptjavaScript.ppt
javaScript.pptsentayehu
 
Linux Basic Commands
Linux Basic CommandsLinux Basic Commands
Linux Basic CommandsHanan Nmr
 
Course 102: Lecture 14: Users and Permissions
Course 102: Lecture 14: Users and PermissionsCourse 102: Lecture 14: Users and Permissions
Course 102: Lecture 14: Users and PermissionsAhmed El-Arabawy
 
JavaScript guide 2020 Learn JavaScript
JavaScript guide 2020 Learn JavaScriptJavaScript guide 2020 Learn JavaScript
JavaScript guide 2020 Learn JavaScriptLaurence Svekis ✔
 
RESTful services on IBM Domino/XWork
RESTful services on IBM Domino/XWorkRESTful services on IBM Domino/XWork
RESTful services on IBM Domino/XWorkJohn Dalsgaard
 
Bash shell scripting
Bash shell scriptingBash shell scripting
Bash shell scriptingVIKAS TIWARI
 
Kotlin coroutines 톺아보기
Kotlin coroutines 톺아보기Kotlin coroutines 톺아보기
Kotlin coroutines 톺아보기Taewoo Kim
 
Triggers and order of execution1
Triggers and order of execution1Triggers and order of execution1
Triggers and order of execution1Prabhakar Sharma
 
Domino OSGi Development
Domino OSGi DevelopmentDomino OSGi Development
Domino OSGi DevelopmentPaul Fiore
 
JavaScript - Chapter 9 - TypeConversion and Regular Expressions
 JavaScript - Chapter 9 - TypeConversion and Regular Expressions  JavaScript - Chapter 9 - TypeConversion and Regular Expressions
JavaScript - Chapter 9 - TypeConversion and Regular Expressions WebStackAcademy
 
15 practical grep command examples in linux
15 practical grep command examples in linux15 practical grep command examples in linux
15 practical grep command examples in linuxTeja Bheemanapally
 

What's hot (20)

Prevent merging columns in excel output using rtf template
Prevent merging columns in excel output using rtf templatePrevent merging columns in excel output using rtf template
Prevent merging columns in excel output using rtf template
 
Difference Between HTML and HTML5
Difference Between HTML and HTML5Difference Between HTML and HTML5
Difference Between HTML and HTML5
 
Loops in java script
Loops in java scriptLoops in java script
Loops in java script
 
Vi editor in linux
Vi editor in linuxVi editor in linux
Vi editor in linux
 
javaScript.ppt
javaScript.pptjavaScript.ppt
javaScript.ppt
 
Linux Basic Commands
Linux Basic CommandsLinux Basic Commands
Linux Basic Commands
 
Course 102: Lecture 14: Users and Permissions
Course 102: Lecture 14: Users and PermissionsCourse 102: Lecture 14: Users and Permissions
Course 102: Lecture 14: Users and Permissions
 
JavaScript guide 2020 Learn JavaScript
JavaScript guide 2020 Learn JavaScriptJavaScript guide 2020 Learn JavaScript
JavaScript guide 2020 Learn JavaScript
 
RESTful services on IBM Domino/XWork
RESTful services on IBM Domino/XWorkRESTful services on IBM Domino/XWork
RESTful services on IBM Domino/XWork
 
Modern JS with ES6
Modern JS with ES6Modern JS with ES6
Modern JS with ES6
 
Git101
Git101Git101
Git101
 
Grep
GrepGrep
Grep
 
CQL - Cassandra commands Notes
CQL - Cassandra commands NotesCQL - Cassandra commands Notes
CQL - Cassandra commands Notes
 
Bash shell scripting
Bash shell scriptingBash shell scripting
Bash shell scripting
 
Kotlin coroutines 톺아보기
Kotlin coroutines 톺아보기Kotlin coroutines 톺아보기
Kotlin coroutines 톺아보기
 
Triggers and order of execution1
Triggers and order of execution1Triggers and order of execution1
Triggers and order of execution1
 
Domino OSGi Development
Domino OSGi DevelopmentDomino OSGi Development
Domino OSGi Development
 
Bootstrap 4 ppt
Bootstrap 4 pptBootstrap 4 ppt
Bootstrap 4 ppt
 
JavaScript - Chapter 9 - TypeConversion and Regular Expressions
 JavaScript - Chapter 9 - TypeConversion and Regular Expressions  JavaScript - Chapter 9 - TypeConversion and Regular Expressions
JavaScript - Chapter 9 - TypeConversion and Regular Expressions
 
15 practical grep command examples in linux
15 practical grep command examples in linux15 practical grep command examples in linux
15 practical grep command examples in linux
 

Similar to Web 8 | Introduction to PHP

Similar to Web 8 | Introduction to PHP (20)

Introduction to php
Introduction to phpIntroduction to php
Introduction to php
 
php programming.pptx
php programming.pptxphp programming.pptx
php programming.pptx
 
2014 database - course 2 - php
2014 database - course 2 - php2014 database - course 2 - php
2014 database - course 2 - php
 
Php Lecture Notes
Php Lecture NotesPhp Lecture Notes
Php Lecture Notes
 
PHP PPT FILE
PHP PPT FILEPHP PPT FILE
PHP PPT FILE
 
Php mysql
Php mysqlPhp mysql
Php mysql
 
php AND MYSQL _ppt.pdf
php AND MYSQL _ppt.pdfphp AND MYSQL _ppt.pdf
php AND MYSQL _ppt.pdf
 
Php Tutorials for Beginners
Php Tutorials for BeginnersPhp Tutorials for Beginners
Php Tutorials for Beginners
 
My cool new Slideshow!
My cool new Slideshow!My cool new Slideshow!
My cool new Slideshow!
 
slidesharenew1
slidesharenew1slidesharenew1
slidesharenew1
 
Introduction to PHP
Introduction to PHPIntroduction to PHP
Introduction to PHP
 
Introduction to PHP
Introduction to PHPIntroduction to PHP
Introduction to PHP
 
Introduction in php part 2
Introduction in php part 2Introduction in php part 2
Introduction in php part 2
 
Good Evils In Perl (Yapc Asia)
Good Evils In Perl (Yapc Asia)Good Evils In Perl (Yapc Asia)
Good Evils In Perl (Yapc Asia)
 
[PL] Jak nie zostać "programistą" PHP?
[PL] Jak nie zostać "programistą" PHP?[PL] Jak nie zostać "programistą" PHP?
[PL] Jak nie zostać "programistą" PHP?
 
Intro to PHP
Intro to PHPIntro to PHP
Intro to PHP
 
07 Introduction to PHP #burningkeyboards
07 Introduction to PHP #burningkeyboards07 Introduction to PHP #burningkeyboards
07 Introduction to PHP #burningkeyboards
 
My shell
My shellMy shell
My shell
 
Mike King - Storytelling by Numbers MKTFEST 2014
Mike King - Storytelling by Numbers MKTFEST 2014Mike King - Storytelling by Numbers MKTFEST 2014
Mike King - Storytelling by Numbers MKTFEST 2014
 
Storytelling By Numbers
Storytelling By NumbersStorytelling By Numbers
Storytelling By Numbers
 

More from Mohammad Imam Hossain

DS & Algo 4 - Graph and Shortest Path Search
DS & Algo 4 - Graph and Shortest Path SearchDS & Algo 4 - Graph and Shortest Path Search
DS & Algo 4 - Graph and Shortest Path SearchMohammad Imam Hossain
 
DS & Algo 1 - C++ and STL Introduction
DS & Algo 1 - C++ and STL IntroductionDS & Algo 1 - C++ and STL Introduction
DS & Algo 1 - C++ and STL IntroductionMohammad Imam Hossain
 
DBMS 3 | ER Diagram to Relational Schema
DBMS 3 | ER Diagram to Relational SchemaDBMS 3 | ER Diagram to Relational Schema
DBMS 3 | ER Diagram to Relational SchemaMohammad Imam Hossain
 
DBMS 5 | MySQL Practice List - HR Schema
DBMS 5 | MySQL Practice List - HR SchemaDBMS 5 | MySQL Practice List - HR Schema
DBMS 5 | MySQL Practice List - HR SchemaMohammad Imam Hossain
 
TOC 8 | Derivation, Parse Tree & Ambiguity Check
TOC 8 | Derivation, Parse Tree & Ambiguity CheckTOC 8 | Derivation, Parse Tree & Ambiguity Check
TOC 8 | Derivation, Parse Tree & Ambiguity CheckMohammad Imam Hossain
 

More from Mohammad Imam Hossain (20)

DS & Algo 6 - Offline Assignment 6
DS & Algo 6 - Offline Assignment 6DS & Algo 6 - Offline Assignment 6
DS & Algo 6 - Offline Assignment 6
 
DS & Algo 6 - Dynamic Programming
DS & Algo 6 - Dynamic ProgrammingDS & Algo 6 - Dynamic Programming
DS & Algo 6 - Dynamic Programming
 
DS & Algo 5 - Disjoint Set and MST
DS & Algo 5 - Disjoint Set and MSTDS & Algo 5 - Disjoint Set and MST
DS & Algo 5 - Disjoint Set and MST
 
DS & Algo 4 - Graph and Shortest Path Search
DS & Algo 4 - Graph and Shortest Path SearchDS & Algo 4 - Graph and Shortest Path Search
DS & Algo 4 - Graph and Shortest Path Search
 
DS & Algo 3 - Offline Assignment 3
DS & Algo 3 - Offline Assignment 3DS & Algo 3 - Offline Assignment 3
DS & Algo 3 - Offline Assignment 3
 
DS & Algo 3 - Divide and Conquer
DS & Algo 3 - Divide and ConquerDS & Algo 3 - Divide and Conquer
DS & Algo 3 - Divide and Conquer
 
DS & Algo 2 - Offline Assignment 2
DS & Algo 2 - Offline Assignment 2DS & Algo 2 - Offline Assignment 2
DS & Algo 2 - Offline Assignment 2
 
DS & Algo 2 - Recursion
DS & Algo 2 - RecursionDS & Algo 2 - Recursion
DS & Algo 2 - Recursion
 
DS & Algo 1 - Offline Assignment 1
DS & Algo 1 - Offline Assignment 1DS & Algo 1 - Offline Assignment 1
DS & Algo 1 - Offline Assignment 1
 
DS & Algo 1 - C++ and STL Introduction
DS & Algo 1 - C++ and STL IntroductionDS & Algo 1 - C++ and STL Introduction
DS & Algo 1 - C++ and STL Introduction
 
DBMS 1 | Introduction to DBMS
DBMS 1 | Introduction to DBMSDBMS 1 | Introduction to DBMS
DBMS 1 | Introduction to DBMS
 
DBMS 3 | ER Diagram to Relational Schema
DBMS 3 | ER Diagram to Relational SchemaDBMS 3 | ER Diagram to Relational Schema
DBMS 3 | ER Diagram to Relational Schema
 
DBMS 2 | Entity Relationship Model
DBMS 2 | Entity Relationship ModelDBMS 2 | Entity Relationship Model
DBMS 2 | Entity Relationship Model
 
DBMS 7 | Relational Query Language
DBMS 7 | Relational Query LanguageDBMS 7 | Relational Query Language
DBMS 7 | Relational Query Language
 
DBMS 4 | MySQL - DDL & DML Commands
DBMS 4 | MySQL - DDL & DML CommandsDBMS 4 | MySQL - DDL & DML Commands
DBMS 4 | MySQL - DDL & DML Commands
 
DBMS 5 | MySQL Practice List - HR Schema
DBMS 5 | MySQL Practice List - HR SchemaDBMS 5 | MySQL Practice List - HR Schema
DBMS 5 | MySQL Practice List - HR Schema
 
TOC 10 | Turing Machine
TOC 10 | Turing MachineTOC 10 | Turing Machine
TOC 10 | Turing Machine
 
TOC 9 | Pushdown Automata
TOC 9 | Pushdown AutomataTOC 9 | Pushdown Automata
TOC 9 | Pushdown Automata
 
TOC 8 | Derivation, Parse Tree & Ambiguity Check
TOC 8 | Derivation, Parse Tree & Ambiguity CheckTOC 8 | Derivation, Parse Tree & Ambiguity Check
TOC 8 | Derivation, Parse Tree & Ambiguity Check
 
TOC 7 | CFG in Chomsky Normal Form
TOC 7 | CFG in Chomsky Normal FormTOC 7 | CFG in Chomsky Normal Form
TOC 7 | CFG in Chomsky Normal Form
 

Recently uploaded

Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxGaneshChakor2
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application ) Sakshi Ghasle
 
Concept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfConcept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfUmakantAnnand
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppCeline George
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfchloefrazer622
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxmanuelaromero2013
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991RKavithamani
 
Science 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsScience 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsKarinaGenton
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesFatimaKhan178732
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon AUnboundStockton
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxOH TEIK BIN
 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting DataJhengPantaleon
 

Recently uploaded (20)

Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptx
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application )
 
Concept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfConcept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.Compdf
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website App
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdf
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptx
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
 
Science 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsScience 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its Characteristics
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and Actinides
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon A
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
 

Web 8 | Introduction to PHP

  • 1. Mohammad Imam Hossain, Lecturer, dept. of CSE, UIU. Email: imambuet11@gmail.com Introduction to PHP (Hypertext Preprocessor) PHP Tags: When PHP parses a file, it looks for opening and closing tags, which are <?php and ?> which tell PHP to start and stop interpreting the code between them. Parsing in this manner allows PHP to be embedded in all sorts of different documents, as everything outside of a pair of opening and closing tags is ignored by the PHP parser. <p>This is going to be ignored by PHP and displayed by the browser.</p> <?php echo 'While this is going to be parsed.'; ?> <p>This will also be ignored by PHP and displayed by the browser.</p> For outputting large blocks of text, dropping out of PHP parsing mode is generally more efficient than sending all of the text through echo or print. <?php if ($expression == true){ ?> This will show if the expression is true. <?php } else { ?> Otherwise this will show. <?php } ?> PHP Comments: <?php echo 'This is a test'; // This is a one-line 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 one-line shell-style comment ?> PHP Datatypes: Boolean (TRUE/FALSE) – case insensitive False – FALSE, 0, -0, 0.0, -0.0, “”, “0”, array with zero elements, NULL (including unset variables) True – Every other value including NAN Integer <?php $a = 1234; // decimal number $a = -123; // a negative number $a = 0123; // octal number (equivalent to 83 decimal) $a = 0x1A; // hexadecimal number (equivalent to 26 decimal) $a = 0b11111111; // binary number (equivalent to 255 decimal) ?> 0 = False, Null 1 = True
  • 2. Mohammad Imam Hossain, Lecturer, dept. of CSE, UIU. Email: imambuet11@gmail.com Floating Point Numbers <?php $a = 1.234; $b = 1.2e3; $c = 7E-10; ?> Strings (Single quoted/ Double quoted) <?php echo 'this is a simple string'; // Outputs: Arnold once said: "I'll be back" echo 'Arnold once said: "I'll be back"'; // Outputs: You deleted C:*.*? echo 'You deleted C:*.*?'; // 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'; ?> <?php $juice = "apple"; echo "He drank some $juice juice."; ?> <?php $str = 'abc'; var_dump($str[1]); var_dump(isset($str[1])); ?> . (DOT) – to concat strings “1” – True “” – False/ Null Array <?php $array = array( "foo" => "bar", "bar" => "foo", ); $array1 = array("foo", "bar", "hello", "world"); var_dump($array1); ?>
  • 3. Mohammad Imam Hossain, Lecturer, dept. of CSE, UIU. Email: imambuet11@gmail.com <?php $array = array( "foo" => "bar", 42 => 24, "multi" => array( "dimensional" => array( "array" => "foo" ) ) ); var_dump($array["foo"]); var_dump($array[42]); var_dump($array["multi"]["dimensional"]["array"]); ?> <?php $arr = array(5 => 1, 12 => 2); $arr[13] = 56; // This is the same as $arr[13] = 56; // at this point of the script $arr["x"] = 42; // This adds a new element to // the array with key "x" unset($arr[5]); // This removes the element from the array unset($arr); // This deletes the whole array ?> PHP Variables: Variables in PHP are represented by a dollar sign followed by the name of the variable. The variable name is case- sensitive. <?php $a = 1; /* global scope */ function test() { echo $a; /* reference to local scope variable */ } test(); ?> <?php $a = 1; $b = 2; function Sum() { $GLOBALS['b'] = $GLOBALS['a'] + $GLOBALS['b']; } Sum(); echo $b; ?>
  • 4. Mohammad Imam Hossain, Lecturer, dept. of CSE, UIU. Email: imambuet11@gmail.com Predefined Variables: $GLOBALS – References all variables available in global scope <?php function test() { $foo = "local variable"; echo '$foo in global scope: ' . $GLOBALS["foo"] . "n"; echo '$foo in current scope: ' . $foo . "n"; } $foo = "Example content"; test(); ?> $_SERVER – server and execution environment information <?php $indicesServer = array( 'PHP_SELF', 'SERVER_ADDR', 'SERVER_NAME', 'SERVER_PROTOCOL', 'REQUEST_METHOD', 'REQUEST_TIME', 'QUERY_STRING', 'DOCUMENT_ROOT', 'HTTPS', 'REMOTE_ADDR', 'REMOTE_HOST', 'REMOTE_PORT', 'REMOTE_USER', 'SERVER_PORT', 'SCRIPT_NAME', 'REQUEST_URI') ; echo '<table style=”width:100%;”>' ; foreach ($indicesServer as $arg) { if (isset($_SERVER[$arg])) { echo '<tr><td>'.$arg.'</td><td>' . $_SERVER[$arg] . '</td></tr>' ; } else { echo '<tr><td>'.$arg.'</td><td>-</td></tr>' ; } } echo '</table>' ; ?> $_GET – an associative array of variables passed to the current script via the URL parameters $_POST – an associative array of variables passed to the current script via the HTTP POST method when using application/x-www-form-urlencoded or, multipart/form-data as the HTTP $_FILES – an associative array of items uploaded to the current script via the HTTP POST method $_REQUEST -- An associative array that by default contains the contents of $_GET, $_POST and $_COOKIE. $_SESSION -- An associative array containing session variables available to the current script. $_COOKIE -- An associative array of variables passed to the current script via HTTP Cookies.
  • 5. Mohammad Imam Hossain, Lecturer, dept. of CSE, UIU. Email: imambuet11@gmail.com Operators and Operator Precedence: visit here  https://www.php.net/manual/en/language.operators.php Control Structures: if-elseif-else statement <?php if ($a > $b) { echo "a is bigger than b"; } elseif ($a == $b) { echo "a is equal to b"; } else { echo "a is smaller than b"; } ?> while loop <?php $i = 1; while ($i <= 10) { echo $i++; /* the printed value would be $i before the increment (post-increment) */ } ?> do-while loop <?php $i = 0; do { echo $i; } while ($i > 0); ?> for loop <?php for ($i = 1; $i <= 10; $i++) { echo $i; } ?> foreach loop <?php $a = array(1, 2, 3, 17); $i = 0; foreach ($a as $v) { echo "$a[$i] => $v.n"; $i++; } $a = array( "one" => 1, "two" => 2,
  • 6. Mohammad Imam Hossain, Lecturer, dept. of CSE, UIU. Email: imambuet11@gmail.com "three" => 3, "seventeen" => 17 ); foreach ($a as $k => $v) { echo "$a[$k] => $v.n"; } //multi-dimensional array $a = array(); $a[0][0] = "a"; $a[0][1] = "b"; $a[1][0] = "y"; $a[1][1] = "z"; foreach ($a as $v1) { foreach ($v1 as $v2) { echo "$v2n"; } } ?> break, continue, switch, return similar as before include/require The include/require statement includes and evaluates the specified file. The include construct will emit a warning if it cannot find a file; this is different behavior from require, which will emit a fatal error. within vars.php file <?php $color = 'green'; $fruit = 'apple'; ?> within test.php file <?php echo "A $color $fruit"; // A include 'vars.php'; echo "A $color $fruit"; // A green apple ?> include_once / require_once The include_once statement includes and evaluates the specified file during the execution of the script. This is a behavior similar to the include statement, with the only difference being that if the code from a file has already been included, it will not be included again, and include_once returns TRUE. As the name suggests, the file will be included just once. <?php var_dump(include_once 'fakefile.ext'); // bool(false) var_dump(include_once 'fakefile.ext'); // bool(true) ?>
  • 7. Mohammad Imam Hossain, Lecturer, dept. of CSE, UIU. Email: imambuet11@gmail.com Functions: <?php $makefoo = true; /* We can't call foo() from here since it doesn't exist yet, but we can call bar() */ bar(); if ($makefoo) { function foo() { echo "I don't exist until program execution reaches me.n"; } } /* Now we can safely call foo() since $makefoo evaluated to true */ if ($makefoo) foo(); function bar() { echo "I exist immediately upon program start.n"; } ?> <?php function foo() { function bar() { echo "I don't exist until foo() is called.n"; } } /* We can't call bar() yet since it doesn't exist. */ foo(); /* Now we can call bar(), foo()'s processing has made it accessible. */ bar(); ?> ///anonymous functions in PHP <?php $greet = function($name) { printf("Hello %srn", $name); }; $greet('World'); $greet('PHP'); ?>
  • 8. Mohammad Imam Hossain, Lecturer, dept. of CSE, UIU. Email: imambuet11@gmail.com Some Functions: Variable Handling Functions empty($var) -- Determine whether a variable is empty i.e. it doesn’t exist or value equals FALSE. isset($var) -- Determine if a variable is declared and value is different than NULL unset($var) -- Unset a given variable or, destroys a variable print_r ($var) -- Prints human-readable information about a variable var_dump($var) -- Dumps information about a variable Array Functions count($a) -- Count all elements in an array array_key_exists('first', $search_array) -- Checks if the given key or index exists in the array array_keys($array) -- Return all the keys of an array array_values($array) -- Return all the values of an array array_push($stack, "apple", "raspberry") -- Push one or more elements onto the end of array array_pop($stack) -- Pop the element off the end of array array_unshift($queue, "apple", "raspberry") -- Prepend one or more elements to the beginning of an array array_shift($stack) -- Shift an element off the beginning of array array_search('green', $array) -- Searches the array for a given value and returns the first corresponding key if successful array_slice($input, 0, 3) -- Extract a slice of the array array_splice($input, -1, 1, array("black", "maroon")) -- Remove a portion of the array and replace it with something else sort($array), rsort($array), ksort($array), krsort($array) String Functions strlen(‘abcd’) -- Get string length echo "Hello World" -- Output one or more strings explode(" ", $pizza) -- split a string by a string implode(",", $array) -- Join array elements with a string htmlentities("A 'quote' is <b>bold</b>") -- Convert all applicable characters to HTML entities html_entity_decode(“I'll &quot;walk&quot; the &lt;b&gt;dog&lt;/b&gt”) -- Convert HTML entities to their corresponding characters htmlspecialchars($str) — Convert special characters to HTML entities htmlspecialchars_decode($encodedstr) — Convert special HTML entities back to characters md5($password) – calculate the md5 hashing of user string sha1($password) – calculate the sha1 hashing of user string parse_str($str,$output_array) -- Parses the string into variables example: $str = "first=value&arr[]=foo+bar&arr[]=baz"; // Recommended parse_str($str, $output); echo $output['first']; // value echo $output['arr'][0]; // foo bar echo $output['arr'][1]; // baz