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

Authentication
AuthenticationAuthentication
Authentication
soon
 
ASP.NET Web API
ASP.NET Web APIASP.NET Web API
ASP.NET Web API
habib_786
 
Unix Shell Scripting Basics
Unix Shell Scripting BasicsUnix Shell Scripting Basics
Unix Shell Scripting Basics
Dr.Ravi
 

What's hot (20)

Git Tutorial I
Git Tutorial IGit Tutorial I
Git Tutorial I
 
Authentication
AuthenticationAuthentication
Authentication
 
Архитектура программных систем на Node.js
Архитектура программных систем на Node.jsАрхитектура программных систем на Node.js
Архитектура программных систем на Node.js
 
ASP.NET Web API
ASP.NET Web APIASP.NET Web API
ASP.NET Web API
 
Introducing Async/Await
Introducing Async/AwaitIntroducing Async/Await
Introducing Async/Await
 
Git undo
Git undoGit undo
Git undo
 
types of events in JS
types of events in JS types of events in JS
types of events in JS
 
Git
GitGit
Git
 
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
 
PHP slides
PHP slidesPHP slides
PHP slides
 
Rust
RustRust
Rust
 
점진적인 레거시 웹 애플리케이션 개선 과정
점진적인 레거시 웹 애플리케이션 개선 과정점진적인 레거시 웹 애플리케이션 개선 과정
점진적인 레거시 웹 애플리케이션 개선 과정
 
Avoiding callback hell in Node js using promises
Avoiding callback hell in Node js using promisesAvoiding callback hell in Node js using promises
Avoiding callback hell in Node js using promises
 
Couch db
Couch dbCouch db
Couch db
 
Using gcov and lcov
Using gcov and lcovUsing gcov and lcov
Using gcov and lcov
 
Apache Cordova
Apache CordovaApache Cordova
Apache Cordova
 
Blazor
BlazorBlazor
Blazor
 
Workshop 4: NodeJS. Express Framework & MongoDB.
Workshop 4: NodeJS. Express Framework & MongoDB.Workshop 4: NodeJS. Express Framework & MongoDB.
Workshop 4: NodeJS. Express Framework & MongoDB.
 
Unix Shell Scripting Basics
Unix Shell Scripting BasicsUnix Shell Scripting Basics
Unix Shell Scripting Basics
 
Introduction to PowerShell
Introduction to PowerShellIntroduction to PowerShell
Introduction to PowerShell
 

Similar to Web 8 | Introduction to PHP

2014 database - course 2 - php
2014 database - course 2 - php2014 database - course 2 - php
2014 database - course 2 - php
Hung-yu Lin
 
Good Evils In Perl (Yapc Asia)
Good Evils In Perl (Yapc Asia)Good Evils In Perl (Yapc Asia)
Good Evils In Perl (Yapc Asia)
Kang-min Liu
 

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 Tutorials for Beginners
Php Tutorials for BeginnersPhp Tutorials for Beginners
Php Tutorials for Beginners
 
php AND MYSQL _ppt.pdf
php AND MYSQL _ppt.pdfphp AND MYSQL _ppt.pdf
php AND MYSQL _ppt.pdf
 
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

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 10 | Database Transactions
DBMS 10 | Database TransactionsDBMS 10 | Database Transactions
DBMS 10 | Database Transactions
 
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
 

Recently uploaded

1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
QucHHunhnh
 
Spellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseSpellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please Practise
AnaAcapella
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptx
negromaestrong
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
ZurliaSoop
 

Recently uploaded (20)

Magic bus Group work1and 2 (Team 3).pptx
Magic bus Group work1and 2 (Team 3).pptxMagic bus Group work1and 2 (Team 3).pptx
Magic bus Group work1and 2 (Team 3).pptx
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentation
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdf
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibit
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
Spellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseSpellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please Practise
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptx
 
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptx
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
Food safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfFood safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdf
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.
 
psychiatric nursing HISTORY COLLECTION .docx
psychiatric  nursing HISTORY  COLLECTION  .docxpsychiatric  nursing HISTORY  COLLECTION  .docx
psychiatric nursing HISTORY COLLECTION .docx
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptx
 

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