PHP 1 Merged
PHP 1 Merged
PHP stands for PHP: Hypertext Preprocessor (earlier called Personal Home Page)
HTML-embedded, server-side scripting language for web development
o PHP files can contain text, HTML, CSS, JavaScript, and PHP code
o PHP code is executed on the server (processed by a PHP interpreter) & result is returned
to the browser as plain HTML
A powerful tool for making dynamic and interactive Web page
o Open source, easy to learn, interpreted
A widely-used, free, efficient alternative to competitors such as Microsoft's ASP
Platform Independent
o Available for Win/ Linux/ Unix : can be developed in one OS & executed in another
o Compatible with almost all local servers (IIS/Apache etc.)
Latest stable version PHP 7, file extension .php
PHP PROCESSING
When a Web server requests an PHP page (e.g. http://www.xyz.com /index.php ), the following
steps occur:
1. The client (Web browser) locates the Web Server specified by the first part of the URL
(www.xyz.com)
2. Client then requests the Server for the PHP page specified by the second part of the URL
(/index.php )
3. Web server reads the page and processes it
4. After the PHP code has been completely processed by the Web server, the resulting HTML
output is sent back as response to the client
5. Client receives the HTML sent by the server, and renders it for the user
Web server plays a more active role in this case. The server knows that it has to process the
programmatic code before sending the output to the client, by looking at the .PHP extension of
the file.
PHP SYNTAX
<!DOCTYPE html>
<html>
<body>
<?php
echo "Today is " . date("Y/m/d") . "<br>";
?>
</body>
</html>
A PHP script can be placed anywhere in the document
PHP code is surrounded by a <?php and ?>
“echo” used to output text to web document
In PHP, keywords (e.g. if, else, while, echo, etc.), classes, functions, and user-defined
functions are not case-sensitive
ECHO "Today is " . date("Y/m/d") . "<br>"; is same as above
When a PHP page is requested from a Web server, the server fully processes all the code between
the <?php and ?> before sending the output to the client.
PHP VARIABLES
In PHP, a variable starts with the $ sign, followed by the name of the variable
Rules for naming variables in PHP
Must start with a letter or the underscore character
Cannot start with a number
Can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )
Are case-sensitive ($age and $AGE are two different variables)
Unlike other programming languages, PHP has no command for declaring a variable. It is
created the moment you first assign a value to it.
Loosely typed associates a data type to a variable based on its value
SCOPE OF VARIABLES: LOCAL SCOPE
A variable declared within a function has a LOCAL SCOPE and can only be accessed within
that function
One can have local variables with the same name in different functions
o local variables are only recognized by the function in which they are declared.
<?php
function myTest() {
$x = 5; // local scope
echo "<p>Variable x inside function is: $x</p>";
}
myTest();
// using x outside the function will generate an error
echo "<p>Variable x outside function is: $x</p>";
?>
GLOBAL KEYWORD
The global keyword is used to access a global variable from within a function
Use the global keyword before the variables (inside the function)
/* Example to demonstrate use of comments
And global keyword */
<?php
$x = 5;
$y = 10;
function myTest() {
global $x, $y; #global declaration
$y = $x + $y;
}
myTest();
echo $y; // outputs 15
?>
$GLOBALS ARRAY
PHP ECHO
echo "This ", "string ", "was ", "made ", "with multiple parameters.";
echo " I'm about to " . $txt1 . "<br>";
echo "Hello escape \"sequence\" characters"; #output: Hello escape "sequence" characters
echo $x + 2;
echo “Print multiline
using PHP echo
”;
?>
PHP PRINT
DATATYPES IN PHP
Scalar
o String – sequence of characters enclosed in single or double quotes
<?php
$x = "Hello world!";
echo $x;
?>
Output: Hello world
o Boolean – True or False – used for conditional testing.
<?php
if (TRUE)
echo "This condition is TRUE.";
if (FALSE)
echo "This condition is FALSE.";
?>
Output:
<?php
$dec1 = 34;
$oct1 = 0243; #(decimal)2*82+4*8+3=163
$hexa1 = 0x45; #(decimal) 4*16+5=69
echo "Decimal number: " .$dec1. "</br>";
echo "Octal number: " .$oct1. "</br>"; #To use octal notation, precede the number
with a 0 (zero).
echo "HexaDecimal number: " .$hexa1. "</br>"; #To specify a number in
hexadecimal, precede it with 0x.
?>
Output:
Compound
o Array - stores multiple values in one single variable
<?php
$bikes = array ("Royal Enfield", "Yamaha", "KTM");
var_dump($bikes); //the var_dump() function returns the datatype and values
echo "</br>";
echo "Array Element1: $bikes[0] </br>";
echo "Array Element2: $bikes[1] </br>";
echo "Array Element3: $bikes[2] </br>";
?>
Output:
array(3) { [0]=> string(13) "Royal Enfield" [1]=> string(6) "Yamaha" [2]=> string(3) "KTM"
}
Array Element1: Royal Enfield
Array Element2: Yamaha
Array Element3: KTM
o Object – a data type which stores data and information on how to process that
data.
<?php
class bike {
function model() {
$model_name = "Royal Enfield";
echo "Bike Model: " .$model_name;
}
}
$obj = new bike();
$obj -> model();
?>
Output:
Special
o NULL – a variable with no value assigned; variables emptied by assigning NULL value
<?php
$nl = NULL;
echo $nl; //it will not give any output
?>
No output
OPERATORS IN PHP:
Arithmetic : +, -, *, /, % (modulus), **(exponentiation)
Assignment : =, +=, -=, *=, /=, %=
Comparison : ==, ===, != or <>, !==, >, <, <=, >=
< = > new in PH7
Increment/Decrement: ++$x, $x++, --$x, $x—
Logical: and, or, not, xor, &&, ||, !
String : . , .=
Array : + (union), == (equality), === (identity), != or <> (inequality),
!== (non-identity)
Ternary [ ?: ]: $x = expr1 ? expr2 : expr3
$a = "Hello ";
$a .= "World!"; // now $a contains "Hello World!"
?>
If..Else.. ElseIf
<?php
$t = date("H");
if($t < 10){
echo “Have a good morning!";
}
else {
echo "Have a good day!";
}
else {
echo "Have a good night!";
}
?>
Switch
<?php
$color = "red";
switch ($color) {
case "red":
echo "Your favorite color is red!";
break;
case "blue":
echo "Your favorite color is blue!";
break;
case "green":
...
default:
echo "Your favorite color is neither red, blue, nor green!";
}
?>
While - Loops through a block of code as long as the specified condition is true
<?php
$x = 0;
while($x <= 100) {
echo "The number is: $x <br>";
$x+=10;
}
?>
Do-While - Loops through a block of code once, and then repeats the loop as long as the specified
condition is true.
<?php
$x = 0;
do {
echo "The number is: $x <br>";
$x+=10;
} while($x <= 100)
?>
For loop
Loops through a block of code a specified number of times
Used when you know in advance how many times the script should run
<?php
for ($x = 0; $x <= 100; $x++) {
echo "The number is: $x <br>";
}
?>
or,
<?php
for ($x = 0; $x <= 100; $x+=10) {
echo "The number is: $x <br>";
}
?>
ForEach loop
Loops through a block of code for each element in an array
Works only on arrays
Used to loop through each key/value pair in an array
<?php
$colors = array("red", "green", "blue", "yellow");
<?php
echo strcmp("Hello world!","Hello world!");
?>
Output:
Array ( [0] => H [1] => e [2] => l [3] => l [4] => o )
ARRAYS:
Indexed Arrays: index can be assigned automatically (index always starts at 0)
<?php
$cars = array("Volvo", "BMW", "Toyota");
$arrlength = count($cars);
for($x = 0; $x < $arrlength; $x++) {
echo $cars[$x];
echo "<br>";
}
?>
<?php
$colors = array("red", "green", "blue", "yellow");
Multidimensional arrays:
$cars = array
(
array(“Toyota",20,16),
array("BMW",15,12),
array("Land Rover",5,2)
);
<?php
for ($row = 0; $row < 4; $row++) {
echo "<p><b>Row number $row</b></p>";
echo "<ul>";
for ($col = 0; $col < 3; $col++) {
echo "<li>".$cars[$row][$col]."</li>";
}
echo "</ul>";
} }
?>
ARRAY FUNCTIONS
1. PHP array_change_key_case()-Change all keys in an array to uppercase.
<?php
$age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
print_r(array_change_key_case($age,CASE_UPPER)); //OUTPUT: Array ( [PETER] => 35 [BEN]
=> 37 [JOE] => 43 )
?>
3. PHP sort()-Sort the elements of the $cars array in ascending alphabetical order.
<?php
$cars = array("Volvo", "BMW", "Toyota");
sort($cars);
7. PHP array_search()-Search an array for the value "red" and return its key.
<?php
$a=array("a"=>"red","b"=>"green","c"=>"blue");
echo array_search("red",$a); //OUTPUT: a
?>
<?php
if(isset($_POST['submit'])){
if(!empty($_POST['colour'])) {
foreach($_POST['colour'] as $value){
echo "Chosen colour : ".$value.'<br/>';
}
}
?>
</body>
</html>
The foreach() method functions by looping through all checked checkboxes and displaying their
values.
To get value of multiple select option from select tag, name attribute in HTML <select> tag
should be initialize with an array [ ]:
PHP has many functions to work with normal files. Those functions are:
1) fopen() – PHP fopen() function is used to open a file. First parameter of fopen() contains name of
the file which is to be opened and second parameter tells about mode in which file needs to be
opened, e.g.,
<?php
$file = fopen(“demo.txt”,'w');
?>
Files can be opened in any of the following modes :
“w” – Opens a file for write only. If file not exist then new file is created and if file already exists
then contents of file is erased.
“r” – File is opened for read only.
“a” – File is opened for write only. File pointer points to end of file. Existing data in file is
preserved.
“w+” – Opens file for read and write. If file not exist then new file is created and if file already
exists then contents of file is erased.
“r+” – File is opened for read/write.
“a+” – File is opened for write/read. File pointer points to end of file. Existing data in file is
preserved. If file is not there then new file is created.
“x” – New file is created for write only.
2) fread() –– After file is opened using fopen() the contents of data are read using fread(). It takes
two arguments. One is file pointer and another is file size in bytes, e.g.,
<?php
$filename = "demo.txt";
$file = fopen( $filename, 'r' );
$size = filesize( $filename );
$filedata = fread( $file, $size );
?>
3) fwrite() – New file can be created or text can be appended to an existing file using fwrite()
function. Arguments for fwrite() function are file pointer and text that is to written to file. It can
contain optional third argument where length of text to written is specified, e.g.,
<?php
$file = fopen("demo.txt", 'w');
$text = "Hello world\n";
fwrite($file, $text);
?>
4) fclose() – file is closed using fclose() function. Its argument is file which needs to be closed, e.g.,
<?php
$file = fopen("demo.txt", 'r');
//some code to be executed
fclose($file);
?>
5) readfile()- The readfile() function reads a file and writes it to the output buffer.
The readfile() function returns the number of bytes read on success.
<?php
echo readfile("webdictionary.txt");
?>
Webdictionary.txt:
AJAX=Asynchronous avaScript and XML
CSS = Cascading Style Sheets
HTML = Hyper Text Markup Language
PHP = PHP Hypertext Preprocessor
SQL = Structured Query Language
SVG = Scalable Vector Graphics
XML = EXtensible Markup Language
Output:
AJAX = Asynchronous JavaScript and XML CSS = Cascading Style Sheets HTML = Hyper Text Markup
Language PHP = PHP Hypertext Preprocessor SQL = Structured Query Language SVG = Scalable
Vector Graphics XML = EXtensible Markup Language236
6) fgetc()- The fgetc() function is used to read a single character from a file. The example below reads
the "webdictionary.txt" file character by character, until end-of-file is reached:
<?php
$myfile = fopen("webdictionary.txt", "r") or die("Unable to open file!");
// Output one character until end-of-file
while(!feof($myfile)) {
echo fgetc($myfile);
}
fclose($myfile);
?>
The first parameter of fwrite() contains the name of the file to write to and the second parameter is
the string to be written.
The example below writes a couple of names into a new file called "newfile.txt":
Example
<?php
$myfile = fopen("newfile.txt", "w") or die("Unable to open file!");
$txt = "John Doe\n";
fwrite($myfile, $txt);
$txt = "Jane Doe\n";
fwrite($myfile, $txt);
fclose($myfile);
?>
Notice that we wrote to the file "newfile.txt" twice. Each time we wrote to the file we sent the string
$txt that first contained "John Doe" and second contained "Jane Doe". After we finished writing, we
closed the file using the fclose() function.
John Doe
Jane Doe
PHP Overwriting
Now that "newfile.txt" contains some data we can show what happens when we open an existing
file for writing. All the existing data will be ERASED and we start with an empty file.
In the example below we open our existing file "newfile.txt", and write some new data into it:
Example
<?php
$myfile = fopen("newfile.txt", "w") or die("Unable to open file!");
$txt = "Mickey Mouse\n";
fwrite($myfile, $txt);
$txt = "Minnie Mouse\n";
fwrite($myfile, $txt);
fclose($myfile);
?>
If we now open the "newfile.txt" file, both John and Jane have vanished, and only the data we just
wrote is present:
Mickey Mouse
Minnie Mouse
You can append data to a file by using the "a" mode. The "a" mode appends text to the end of the
file, while the "w" mode overrides (and erases) the old content of the file.
In the example below we open our existing file "newfile.txt", and append some text to it:
Example
<?php
$myfile = fopen("newfile.txt", "a") or die("Unable to open file!");
$txt = "Donald Duck\n";
fwrite($myfile, $txt);
$txt = "Goofy Goof\n";
fwrite($myfile, $txt);
fclose($myfile);
?>
If we now open the "newfile.txt" file, we will see that Donald Duck and Goofy Goof is appended to
the end of the file:
Mickey Mouse
Minnie Mouse
Donald Duck
Goofy Goof
PHP FILE UPLOAD
Configure The "php.ini" File
First, ensure that PHP is configured to allow file uploads.
In your "php.ini" file, search for the file_uploads directive, and set it to On:
file_uploads = On
{For Windows, you can find the file in the C:\xampp\php\php.ini -Folder (Windows). Open the
php.ini-developer file in notepad and check if file_uploads = On }
Next, create an HTML form that allows users to choose the image file they want to upload:
<!DOCTYPE html>
<html>
<body>
</body>
</html>
Without the requirements above, the file upload will not work.
The type="file" attribute of the <input> tag shows the input field as a file-select control, with
a "Browse" button next to the input control
The form above sends data to a file called "upload.php", which we will create next.
<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
}
?>
$target_dir = "uploads/" - specifies the directory where the file is going to be placed
$target_file specifies the path of the file to be uploaded
$uploadOk=1 is not used yet (will be used later)
$imageFileType holds the file extension of the file (in lower case)
Next, check if the image file is an actual image or a fake image
Note: You will need to create a new directory called "uploads" in the directory where "upload.php"
file resides. The uploaded files will be saved there.
First, we will check if the file already exists in the "uploads" folder. If it does, an error message is
displayed, and $uploadOk is set to 0:
The file input field in our HTML form above is named "fileToUpload".
Now, we want to check the size of the file. If the file is larger than 500KB, an error message is
displayed, and $uploadOk is set to 0:
The code below only allows users to upload JPG, JPEG, PNG, and GIF files. All other file types gives an
error message before setting $uploadOk to 0:
<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
The Standard PHP Library (SPL) is a collection of interfaces and classes that are meant to solve
common problems.
SPL provides a set of standard data structure, a set of iterators to traverse over objects, a set of
interfaces, a set of standard Exceptions, a number of classes to work with files and it provides a set
of functions.
<?php
//SplStack Mode is LIFO (Last In First Out)
$q = new SplStack();
$q[] = 1;
$q[] = 2;
$q[] = 3;
$q->push(4);
$q->add(4,5);
$q->rewind();
while($q->valid()){
echo $q->current(),"\n";
$q->next();
}
?>
Output:
5
4
3
2
1
HASH
The hash() function returns a hash value for the given data based on the
algorithm like (md5, sha256). The return value is a string with hexits (hexadecimal
values).
Syntax
Parameters
algo
Name of the hashing algorithm. There is a big list of algorithm available with
1 hash, some important ones are md5, sha256, etc.
To get the full list of algorithms supported use the hashing function
hash_algos()
data
2 The data you want the hash to be generated. Please note once the hash is
generated it cannot be reversed.
raw_output
3 By default, the value is false and hence it returns lowercase hexits values. If
the value is true, it will return raw binary data.
Return Values
PHP hash() function returns a string with lowercase hexits. If the raw_output is set to true, it
will return raw binary data.
<?php
echo "The hash of Welcome to PHPTutorial is - ". hash('md5', 'Welcome to
PHPTutorial');
?>
Output:
Example 2
<?php
echo "The hash of Welcome to PHPTutorial is - ". hash('sha256', 'Welcome to
PHPTutorial');
?>
Output: