0% found this document useful (0 votes)
6 views28 pages

PHP 1 Merged

The document provides an overview of PHP programming, detailing its features as a server-side scripting language, including syntax, variable scope, data types, operators, control statements, and string functions. It explains how PHP processes requests from web servers and includes examples of basic PHP code. Additionally, it covers arrays, both indexed and associative, and various string manipulation functions.

Uploaded by

king20001409
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views28 pages

PHP 1 Merged

The document provides an overview of PHP programming, detailing its features as a server-side scripting language, including syntax, variable scope, data types, operators, control statements, and string functions. It explains how PHP processes requests from web servers and includes examples of basic PHP code. Additionally, it covers arrays, both indexed and associative, and various string manipulation functions.

Uploaded by

king20001409
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 28

BASICS OF PHP PROGRAMMING

 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>";
?>

SCOPE OF VARIABLES: GLOBAL SCOPE


 A variable declared outside a function has a GLOBAL SCOPE
<?php
$x = 5; // global scope
function myTest() {
// using x inside this function will generate an error
echo "<p>Variable x inside function is: $x</p>";
}
myTest();
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 stores all global variables in an array called $GLOBALS[index]


 This array is also accessible from within functions and can be used to update global variables
directly
<?php
$x = 5;
$y = 10;
function myTest() {
$GLOBALS['y'] = $GLOBALS['x'] + $GLOBALS['y'];
}
myTest();
echo $y; // outputs 15
?>

PHP ECHO

 Language construct not a function, optional to use parenthesis with it


 Iecho can be used with more than one parameter.
 Unlike print, echo has no return value, also marginally faster
 Can be used to output string, multi line strings, escaping characters, variable, array etc. -
Text string can contain HTML markup also
<?php
$txt1 = "Learn PHP";
$x = 5;
echo "<h2>PHP is Fun!</h2>";

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

 Like echo, Print is a language construct, optional to use parenthesis with it


 Can be used to print text string, multi line strings, escaping characters, variable, array etc.
 Unlike echo, cannot be used with more than one parameter
 Print has a return value of 1, and can be used with expressions
<?php
$txt1 = "Learn PHP";
$x = 5;
print "<h2>PHP is Fun!</h2>";
print " I'm about to " . $txt1 . "<br>";
print "Hello escape \"sequence\" characters";
print $x + 2;
print “Print multiline
using 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:

This condition is TRUE.

 bool is_bool ($var) – function used to check if a variable is boolean


or not
 Similarly, bool is_int ($var), bool is_float ($var), bool is_null ($var)
 is_numeric ($var) - returns true if variable is a number or numeric
string

o Integer – expressed in binary, octal, decimal, or hex notation


<?php
$x = 5985;
var_dump($x);
?>
Output: int(5985)

<?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: Decimal number: 34


Octal number: 163
HexaDecimal number: 69

o Float -A floating-point number is a number with a decimal point. Unlike


integer, it can hold numbers with a fractional or decimal point, including a
negative or positive sign.
<?php
$n1 = 19.34;
$n2 = 54.472;
$sum = $n1 + $n2;
echo "Addition of floating numbers: " .$sum;
?>

Output:

Addition of floating numbers: 73.812

 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:

Bike Model: Royal Enfield

 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

o Resources – storing of a reference to functions and resources external to PHP.


?php
$conn = ftp_connect("127.0.0.1") or die("Could not connect");
echo get_resource_type($conn);
?>

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

String operator example:


<?php
$a = "Hello ";
$b = $a . "World!"; // now $b contains "Hello World!"

$a = "Hello ";
$a .= "World!"; // now $a contains "Hello World!"
?>

PHP CONTROL STATEMENTS


Branching or conditional statements:
 If.. Else.. ElseIf
 Switch
Looping:
 While
 Do-while
 For
 Foreach

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");

foreach ($colors as $value) {


echo "$value <br>";
}
?>
<?php
$age = array(“Sanjoy"=>"35", “Raju"=>"37", "Jolly"=>"43");
foreach($age as $x => $val) {
echo "$x = $val<br>";
}
?>
STRING FUNCTIONS
o strlen()- Returns the length of the string
<?php
echo strlen("Hello!"); // outputs 6
?>

o str_word_count()-Returns the returns the count of words in the string


<?php
echo str_word_count("Hello world!"); // outputs 2
?>

o strrev()- Reverses the string


<?php
echo strrev("Hello!"); //outputs !olleH
?>

o strpos()-Searches for the position of a text within a string


<?php
echo strpos("Hello world!“, “world”); //outputs 6
?>

o str_replace()- Replaces a text within a string


<?php
echo str_replace("world", “June", "Hello world!"); //outputs “Hello June!”
?>

o strcmp()-Compare two strings (case-sensitive)

<?php
echo strcmp("Hello world!","Hello world!");
?>

If this function returns 0, the two strings are equal.

o str_split()-Splits a string into an array


<?php
print_r(str_split("Hello"));
?>

Output:
Array ( [0] => H [1] => e [2] => l [3] => l [4] => o )

o strtolower()-Converts a string to lowercase letters


o strtoupper()-Converts a string to uppercase letters
o substr()-Returns a part of a string
o trim()-Removes whitespace or other characters from both sides of a string
To go through other string functions, go through the following website:
https://www.w3schools.com/php/php_ref_string.asp

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>";
}
?>

Using foreach loop

<?php
$colors = array("red", "green", "blue", "yellow");

foreach ($colors as $value) {


echo "$value <br>";
}
?>
 Associative Arrays: use named keys that are assigned to them
<?php
$age = array(“Sanjoy"=>"35", “Raju"=>"37", "Jolly"=>"43");
foreach($age as $x => $val) {
echo "Key=" . $x . ", Value=" . $val;
echo "<br>";
}
?>

Multidimensional arrays:

 A multidimensional array is an array containing one or more arrays


 A two-dimensional array is an array of arrays (a three-dimensional array is an array of arrays
of arrays)
o For a two-dimensional array, two indices required to select an element
o For a three-dimensional array, three indices required to select an element

$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 )
?>

2. PHP array_sum()-Return the sum of all the values in the array.


<?php
$a=array(5,15,25);
echo array_sum($a); //OUTPUT: 45
?>

3. PHP sort()-Sort the elements of the $cars array in ascending alphabetical order.
<?php
$cars = array("Volvo", "BMW", "Toyota");
sort($cars);

foreach ($cars as $key => $val) {


echo "cars[" . $key . "] = " . $val . "<br>";
}
?>
OUTPUT:
cars[0] = BMW
cars[1] = Toyota
cars[2] = Volvo

4. PHP count()-Return the number of elements in an array.


<?php
$cars=array("Volvo","BMW","Toyota");
echo count($cars); // OUTPUT: 3
?>
5. PHP array_slice()-Start the slice from the third array element, and return the rest of the
elements in the array.
<?php
$a=array("red","green","blue","yellow","brown");
print_r(array_slice($a,2)); //OUTPUT: Array ( [0] => blue [1] => yellow [2] => brown )
?>

6. array_reverse()- Returns an array in the reverse order

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
?>

8. PHP array_values()-Return all the values of an array (not the keys).


<?php
$a=array("Name"=>"Peter","Age"=>"41","Country"=>"USA");
print_r(array_values($a));
?>
Output: Array ( [0] => Peter [1] => 41 [2] => USA )

9. array_push()- Inserts one or more elements to the end of an array


10. array_pop()- Deletes the last element of an array

To go through other array functions, go through the following website:


https://www.w3schools.com/php/php_ref_array.asp

PHP FORM HANDLING


We can create and use forms in PHP. To get form data, we need to use PHP superglobals $_GET and
$_POST.
The form request may be get or post. To retrieve data from get request, we need to use $_GET, for
post request $_POST.

PHP GET FORM


Get request is the default form request. The data passed through get request is visible on the URL
browser so it is not secured. You can send limited amount of data through get request.
Let's see a simple example to receive data from get request in PHP.
File: form1.html
<form action="welcome.php" method="get">
Name: <input type="text" name="name"/>
<input type="submit" value="visit"/>
</form>
File: welcome.php
<?php
$name=$_GET["name"];//receiving name field value in $name variable
echo "Welcome, $name";
?>
PHP POST FORM
Post request is widely used to submit form that have large amount of data such as file upload, image
upload, login form, registration form etc.
The data passed through post request is not visible on the URL browser so it is secured. You can send
large amount of data through post request.
Let's see a simple example to receive data from post request in PHP.
File: form1.html
<form action="login.php" method="post">
<table>
<tr><td>Name:</td><td> <input type="text" name="name"/></td></tr>
<tr><td>Password:</td><td> <input type="password" name="password"/></td></tr>
<tr><td colspan="2"><input type="submit" value="login"/> </td></tr>
</table>
</form>
File: login.php
<?php
$name=$_POST["name"];//receiving name field value in $name variable
$password=$_POST["password"];//receiving password field value in $password variable
echo "Welcome: $name, your password is: $password";
?>
Output:

GET CHECKBOX VALUES IN PHP


<html>
<body>
<form method="post" action="">
<span>What are your favourite colours?</span><br/>
<input type="checkbox" name='colour[]' value="Red"> Red <br/>
<input type="checkbox" name='colour[]' value="Green"> Green <br/>
<input type="checkbox" name='colour[]' value="Blue"> Blue <br/>
<input type="checkbox" name='colour[]' value="Black"> Black <br/>
<br/>
<input type="submit" value="Submit" name="submit">
</form>

<?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.

GET RADIO BUTTON VALUES IN PHP


<form action="" method="post">
<input type="radio" name="radio" value="Radio 1">Radio 1
<input type="radio" name="radio" value="Radio 2">Radio 2
<input type="radio" name="radio" value="Radio 3">Radio 3
<input type="submit" name="submit" value="Get Selected Values" />
</form>
<?php
if (isset($_POST['submit'])) {
if(isset($_POST['radio']))
{
echo "You have selected :".$_POST['radio']; // Displaying Selected Value
}
}
?>

GET VALUES FROM DROPDOWN LIST IN PHP

<form action="#" method="post">


<select name="Color">
<option value="Red">Red</option>
<option value="Green">Green</option>
<option value="Blue">Blue</option>
<option value="Pink">Pink</option>
<option value="Yellow">Yellow</option>
</select>
<input type="submit" name="submit" value="Get Selected Values" />
</form>
<?php
if(isset($_POST['submit'])){
$selected_val = $_POST['Color']; // Storing Selected Value In Variable
echo "You have selected :" .$selected_val; // Displaying Selected Value
}
?>

To get value of multiple select option from select tag, name attribute in HTML <select> tag
should be initialize with an array [ ]:

<form action="#" method="post">


<select name="Color[]" multiple> // Initializing Name With An Array
<option value="Red">Red</option>
<option value="Green">Green</option>
<option value="Blue">Blue</option>
<option value="Pink">Pink</option>
<option value="Yellow">Yellow</option>
</select>
<input type="submit" name="submit" value="Get Selected Values" />
</form>
<?php
if(isset($_POST['submit'])){
// As output of $_POST['Color'] is an array we have to use foreach Loop to display individual value
foreach ($_POST['Color'] as $select)
{
echo "You have selected :" .$select; // Displaying Selected Value
}
}
?>
PHP FILE HANDLING

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);
?>

PHP WRITE TO FILE - FWRITE()

The fwrite() function is used to write to a file.

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.

If we open the "newfile.txt" file it would look like this:

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

PHP Append Text

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 }

Create The HTML Form

Next, create an HTML form that allows users to choose the image file they want to upload:

<!DOCTYPE html>
<html>
<body>

<form action="upload.php" method="post" enctype="multipart/form-data">


Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload Image" name="submit">
</form>

</body>
</html>

Some rules to follow for the HTML form above:

 Make sure that the form uses method="post"


 The form also needs the following attribute: enctype="multipart/form-data". It specifies
which content-type to use when submitting the form

Without the requirements above, the file upload will not work.

Other things to notice:

 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.

Create The Upload File PHP Script

The "upload.php" file contains the code for uploading a file:

<?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;
}
}
?>

PHP script explained:

 $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.

Check if File Already Exists

Now we can add some restrictions.

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:

// Check if file already exists


if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}

Limit File Size

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:

// Check file size


if ($_FILES["fileToUpload"]["size"] > 500000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
Limit File Type

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:

// Allow certain file formats


if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = 0;
}

Complete Upload File PHP Script

The complete "upload.php" file now looks like this:

<?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;
}
}

// Check if file already exists


if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}

// Check file size


if ($_FILES["fileToUpload"]["size"] > 500000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
}

// Allow certain file formats


if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = 0;
}

// Check if $uploadOk is set to 0 by an error


if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
echo "The file ". htmlspecialchars( basename( $_FILES["fileToUpload"]["name"])). " has been
uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
?>
htmlspecialchars — Convert special characters to HTML entities. Example:

& (ampersand) &amp;

" (double quote) &quot;

< (less than) &lt;

> (greater than) &gt;


IMPLEMENTING DATA STRUCTURE

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.

The SplStack class

The SplStack class provides the main functionalities of a stack.

<?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

Definition and Usage

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

hash ( string $algo , string $data [, bool $raw_output = FALSE ] ) : string

Parameters

Sr.No Parameter & Description

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.

Example 1: To generate hash value using md5 Algorithm −

<?php
echo "The hash of Welcome to PHPTutorial is - ". hash('md5', 'Welcome to
PHPTutorial');
?>
Output:

This will produce the following result −

The hash of Welcome to PHPTutorial is - 8ab923b97822bd258bf882e41de6ebff

Example 2

To generate hash value using sha256 Algorithm −

<?php
echo "The hash of Welcome to PHPTutorial is - ". hash('sha256', 'Welcome to
PHPTutorial');
?>

Output:

This will produce the following result −

The hash of Welcome to PHPTutorial is -


a6baf12546b9a5cf6df9e22ae1ae310b8c56be2da2e9fd2c91c94314eb0e5a2e

You might also like