Php Full Notes
Php Full Notes
UNIT - 1
Introduction To PHP
1. Define PHP?
PHP Hypertext Pre-processor is a server scripting language, and a powerful tool for making
dynamic and interactive Web pages.
Advantages of PHP -
· It is open source.
· Free to download
2. Define MySQL?
MySQL is a Relational Database Management System (RDBMS) that uses Structured Query
Language (SQL). It is also free and open source.
www.ourcreativeinfo.in
PHP
PHP Syntax:
<?php
//statements;
?>
Explaination -
<!DOCTYPE html>
<html>
<body>
<?php
?>
</body>
</html>
Variables in PHP are identifiers prefixed with a dollar sign ($). A variable may hold a value of any
type.
www.ourcreativeinfo.in
PHP
You can reference the value of a variable whose name is stored in another variable.
For example:
$foo = 'bar';
$$foo = 'baz';
1. local -
A variable declared in a function is local to that function. That is, it is visible only to code
in that function (including nested function definitions); it is not accessible outside the
function.
2. global -
· That is, they can be accessed from any part of the program.
· However, by default, they are not available inside functions. To allow a function to access
a global variable, you can use the global keyword inside the function to declare the
variable within the function
3. static -
A static variable retains its value between calls to a function but is visible only within
that function. You declare a variable static with the static keyword.
Each time the function is called, that variable will still have the information it contained
from the last time the function was called.
www.ourcreativeinfo.in
PHP
<html>
<body>
<?php
static $x=45;
echo $x;
echo "<br/>";
$x++;
myFunction();
myFunction();
myFunction();
myFunction();
myFunction();
?>
<body>
<html>
· Four are scalar (single-value) types: integers, floating-point numbers, strings, and
Booleans.
www.ourcreativeinfo.in
PHP
1. Integer -
Example:
<html>
<body>
<?php
$x = 5985;
var_dump($x);
?>
</body>
</html>
Output: int(5985)
2. Floating-Point Numbers -
Floating-point numbers (often referred to as real numbers) represent numeric values with decimal digits.
Ex - 6.73, 13.144
//Write example
3. Strings -
A string is a sequence of characters of arbitrary length. String literals are delimited by either single or
double quotes:
//Write example
www.ourcreativeinfo.in
PHP
4. Booleans -
A Boolean value represents a "truth value "it says whether something is true or not.
//Write example
5. Arrays -
· An array holds a group of values, which you can identify by position (a number, with zero being
the first position) or some identifying name (a string), called an associative:
//Write example
5. Object -
· An object is a data type which stores data and information on how to process that data.
· First we must declare a class of object. For this, we use the class keyword. A class is a structure
that can contain properties and methods:
For example -
<html>
<body>
<?php
class Car {
function Car() {
$this->model = "VW";
// create an object
www.ourcreativeinfo.in
PHP
echo $herbie->model;
?>
</body>
</html>
6. NULL Value -
· Null is a special data type which can have only one value: NULL.
· A variable of data type NULL is a variable that has no value assigned to it.
//Write example
7. Resource -
· The special resource type is not an actual data type. It is the storing of a reference to functions
and resources external to PHP.
· Their main benefit is that they take care of memory management by themselves. When the last
reference to a resource value goes away, the extension that created the resource is called to free
any memory, close any connection, etc
Example:
<?php
$fp=fopen("test.txt","w");
var_dump($fp);
?>
Output -
www.ourcreativeinfo.in
PHP
Unlike other programming languages, where a variable’s data type must be explicitly defined by
the programmer, PHP automatically determines a variable’s data type from the content it holds.
And if the variable’s content changes over the duration of a script, the language will
automatically set the variable to the appropriate new data type.
A constant is an identifier (name) for a simple value. The value cannot be changed during the
script.
A valid constant name starts with a letter or underscore (no $ sign before the constant name).
Syntax -
Parameters:
Example:
<?php
echo greeting;
www.ourcreativeinfo.in
PHP
?>
11. Define Operators ? List and explain the types of operators in PHP
· Comparison operators - ==, >, <, >=, <=, !=, ===(identical), !==(Not identical)
· String operators -
. Operator -
Example - $txt1.$txt2
.= Operator -
· Array operators -
<html>
<body>
<?php
www.ourcreativeinfo.in
PHP
var_dump($x == $y);
var_dump($x != $y);
?>
</body>
</html>
<html>
<body>
<form method="post">
</form>
<?php
if(isset($_POST['submit'])) {
$number1 = $_POST['number1'];
$number2 = $_POST['number2'];
$sum = $number1+$number2;
?>
www.ourcreativeinfo.in
PHP
</body>
</html>
UNIT - 2
Conditionals And Looping’s
LIKE MOST PROGRAMMING LANGUAGES, PHP ALSO ALLOWS YOU TO WRITE CODE THAT
PERFORM DIFFERENT ACTIONS BASED ON THE RESULTS OF A LOGICAL OR COMPARATIVE TEST
CONDITIONS AT RUN TIME.
· The If statement
Syntax -
www.ourcreativeinfo.in
PHP
if(Condition){
//statements
If-else statement is slightly different from if statement. It exutes one block of code if the
specified condition is true and another block of code if the condition is fase.
Syntax -
if(condition){
//Statements
} else{
//Statements
The nested if statement contains the If bloc inside another if block. The inner if
statement executes only when specified condition in outer if statement is true.
Syntax -
If(condition){
//Statements
if(condition){
//Nested if statements
www.ourcreativeinfo.in
PHP
The if-else statement lets you define actions for two eventualities: A true condition and a false
conditon. In Reality, however your program may have more than just these two simple
outcomes to content with.
For these situation, PHP offers two constructs that alow the programmer to account for multiple
possibilities.
The if-elseif-else statement lets you chain together multiple if-else statements. Thus allowing the
programmer to define actions for than just two possible outcomes.
Syntax -
if(condition) //Statements
if else(condition) //Statements
else //Statements
//Write example
· Switch-case statements -
PHP Switch statement is used to execute one statement from multiple condition. It works like
PHP if-else-if statements.
Syntax -
switch(Expression){
case value:
// Code
break;
default:
www.ourcreativeinfo.in
PHP
LOOPS ARE USED TO EXECUTE THE SAME BLOCK OF CODE AGAIN AND AGAIN, AS LONG AS A
CERTAIN CONDITION IS TRUE.
1) WHILE -
SYNTAX
CODE TO BE EXECUTED;
2) DO...WHILE -
LOOPS THROUGH A BLOCK OF CODE ONCE, AND THEN REPEATS THE LOOP AS LONG AS THE
SPECIFIED CONDITION IS TRUE.
SYNTAX
DO {
CODE TO BE EXECUTED;
3) FOR -
SYNTAX
www.ourcreativeinfo.in
PHP
4) FOREACH -
SYNTAX
CODE TO BE EXECUTED;
EXAMPLE -
<?PHP
?>
SYNTAX
EXAMPLE
<?PHP
www.ourcreativeinfo.in
PHP
?>
SYNTAX
EXAMPLE
<?PHP
?>
SYNTAX
EXAMPLE
<?PHP
?>
www.ourcreativeinfo.in
PHP
SYNTAX
EXAMPLE
<?PHP
?>
SYNTAX
EXAMPLE
<?PHP
?>
SYNTAX
EXAMPLE
www.ourcreativeinfo.in
PHP
<?PHP
?>
www.ourcreativeinfo.in
PHP
UNIT - 3
Working With Arrays
Array variables are “special,” because they can hold more than one value at a time. This makes
them particularly useful for storing related values.
Syntax -
<?php
?>
The count() function is used to return the length (the number of elements) of an array
Example
<?php
echo count($cars);
?>
Indexed arrays are Arrays with a numeric index. There are two ways to create indexed
arrays:
1. The index can be assigned automatically (index always starts at 0), like this:
www.ourcreativeinfo.in
PHP
www.ourcreativeinfo.in
PHP
$cars[0] = "Volvo";
$cars[1] = "BMW";
$cars[2] = "Toyota";
Example -
<html>
<body>
<?php
echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2] . ".";
?>
</body>
</html>
Associative arrays are arrays that use named keys that you assign to them.
or:
$age['Peter'] = "35";
$age['Ben'] = "37";
$age['Joe'] = "43";
Example
<?php
www.ourcreativeinfo.in
PHP
?>
We can store the data from the table above in a two-dimensional array, like this:
$cars = array (
array("Volvo",22,18),
array("BMW",15,13),
array("Saab",5,2),
array("Land Rover",17,15)
);
Example -
<html>
<body>
<?php
$cars = array (
array("Volvo",22,18),
array("BMW",15,13),
array("Saab",5,2),
array("Land Rover",17,15)
www.ourcreativeinfo.in
PHP
);
?>
</body>
</html>
4. Explain how to process arrays with loops and iterations with different types of arrays?
To loop through and print all the values of an indexed array, you could use a for loop, like
this:
Example
<html>
<body>
<?php
$arrlength = count($cars);
echo $cars[$x];
echo "<br>";
?>
www.ourcreativeinfo.in
PHP
</body>
</html>
<?php
// define array
$cities = array(
);
?>
We can also put a for loop inside another for loop to get the elements of the $cars array (we still
have to point to the two indices):
Example -
<html>
<body>
www.ourcreativeinfo.in
PHP
<?php
$cars = array (
array("Volvo",22,18),
array("BMW",15,13),
array("Saab",5,2),
array("Land Rover",17,15)
);
echo "<ul>";
echo $cars[$row][$col];
?>
</body>
</html>
Alternatively, you may prefer to use an ArrayIterator which provides a ready-made, extensible
tool to loop over array elements.
www.ourcreativeinfo.in
PHP
<?php
$cities = array(
);
while($iterator->valid())
$iterator->next();
?>
Arrays are particularly potent when used in combination with form elements that support more
than one value, such as multiple-selection list boxes or grouped checkboxes.
Example -
www.ourcreativeinfo.in
PHP
<option value="Aerosmith">Aerosmith</option>
</select>
<p>
</form>
<?php
foreach($_POST['artists'] as $a) {
?>
Notice the 'name' attribute of the <select> element, which is named artists[].
This tells PHP that, when the form is submitted, all the selected values from the list should be converted
into elements of an array. The name of the array will be $_POST['artists’], and it will look something like
this:
Array (
1. explode() -
This function, which accepts two arguments—the separator and the source string—and returns
www.ourcreativeinfo.in
PHP
an array.
Here’s an example:
<?php
// define string
$str = 'tinker,tailor,soldier,spy';
print_r($arr);
?>
2. implode() -
It’s also possible to reverse the process, joining the elements of an array into a single string
using user-supplied “glue.” The PHP function for this is named implode().
Example -
<?php
// define array
print_r($str);
?>
3. range() -
www.ourcreativeinfo.in
PHP
This function accepts two end points and returns an array containing all the numbers between
those end points.
Example -
<?php
// define array
$arr = range(1,1000);
print_r($arr);
?>
The min() function returns the minimum number in the array and the max() function returns the
maximum number in the array. Note that these functions only accepts array of numbers.
<?php
// define array
?>
5. sort() -
//write example
www.ourcreativeinfo.in
PHP
1. array_slice() -
PHP allows you to slice an array into smaller parts with the array_slice() function.
Syntax -
2. array_shift() -
Syntax -
array_shift(array_name);
3. array_pop() -
Syntax -
array_pop(array_name);
4. array_push() -
Syntax -
array_push(array_name, "element");
5. array_unshift() -
Syntax -
array_unshift(array_name, "element");
www.ourcreativeinfo.in
PHP
6. shuffle() -
Syntax -
shuffle(array_name);
7. array_reverse() -
Syntax -
array_reverse(array_name);
8. in_array() -
The in_array() function looks through an array for a specified value and returns true if found.
Syntax -
9. array_merge() -
PHP lets you merge one array into another with its array_merge() function, which accepts one or
more array variables
Syntax -
array_merge(array_1, array_2,..... );
1. checkdate() -
Example -
<?php
www.ourcreativeinfo.in
PHP
} else{
2. strtotime() -
3. gmdate() -
The date() function formats a local date and time, and returns the formatted date string.
Syntax -
date(format, timestamp)
Example -
<?php
?>
www.ourcreativeinfo.in
PHP
UNIT - 4
Using Functions And Classes
1. Define functions?
In PHP, a function is a block of code that can be called by a PHP script to perform a task.
www.ourcreativeinfo.in
PHP
· The function body, which contains the processing code to turn inputs into outputs
Example :
function myMessage() {
User can assign default values to any or all of these arguments; these default values are used in
the event the function invocation is missing some arguments.
Here’s an example, which generates an e-mail address from supplied username and domain
arguments; if the domain argument is missing, a default domain is automatically assigned.
<?php
// function invocation
// function invocation
?>
www.ourcreativeinfo.in
PHP
A PHP function definition normally has a fixed argument list, where the number of arguments is
known in advance.
However, PHP also lets you define functions with so-called variable-length argument lists, where
the number of arguments can change with each invocation of the function.
<?php
function calcAverage() {
$args = func_get_args();
$count = func_num_args();
$sum = array_sum($args);
return $avg;
// function invocation
// with 3 arguments
echo calcAverage(3,6,9);
// function invocation
// with 8 arguments
echo calcAverage(100,200,100,300,50,150,250,50);
?>
A recursive function is a function that calls itself repeatedly until a condition is satisfied.
Example -
www.ourcreativeinfo.in
PHP
<?php
function display($number) {
if($number<=5){
display($number+1);
display(1);
?>
Syntax -
class class_name{
//code
Example -
<?php
// class definition
class Automobile {
// properties
public $color;
public $model;
// methods
www.ourcreativeinfo.in
PHP
echo 'Accelerating...';
echo 'Turning...';
// instantiate object
$car->color = 'red';
$car->model= 'Ford';
$car->accelerate();
$car->turn();
?>
Constructor -
It is a special type of method that is created whenever a new instance of a class is created.
Syntax -
www.ourcreativeinfo.in
PHP
construct() {
//Statements
Destructor -
In PHP, a destructor is a method that's automatically called when an object is no longer needed
or referenced, or when the script is stopped or exited.
Syntax -
destruct() {
//Statements
8. Define polymorphism?
It is defined as the ability of objects of different classes to respond differently based on the
same message
Function overloading or method overloading is a feature that permits making creating several
methods with a similar name that works differently from one another in the type of the input
parameters it accepts as arguments
class SampleClass {
$count = count($arguments);
if ($function_name == 'add') {
if ($count == 2) {
www.ourcreativeinfo.in
PHP
return array_sum($arguments);
} else if ($count == 3) {
This is a magic method that PHP calls when it tries to execute a method of a class and it doesn't
find it. This magic keyword takes in two arguments: a function name and other arguments to be
passed into the function.
Syntax -
Abstraction in object-oriented programming (OOP) refers to the concept of hiding the complex
implementation details of an object and exposing only the essential features or functionalities.
Encapsulation refers to the binding data and methods into single unit.
Inheritance is the ability to acquire properties and behaviour of parent class into child class.
Example -
<?php
class Animal {
www.ourcreativeinfo.in
PHP
public $name;
$this->name = $name;
$obj.bark();
?>
www.ourcreativeinfo.in
PHP
UNIT - 5
Introduction To Laravel Framework
1. Define Laravel?
Laravel is an open-source PHP framework, which is robust and easy to understand. It follows a
model-view-controller design pattern. Laravel reuses the existing components of different
frameworks which helps in creating a web application.
Advantages -
· The web application becomes more scalable, owing to the Laravel framework.
· Considerable time is saved in designing the web application, since Laravel reuses the
components from other framework in developing web application.
· It includes namespaces and interfaces, thus helps to organize and manage resources.
2. Define Composer?
3. Define Artisan?
Command line interface used in Laravel is called Artisan. It includes a set of commands which
assists in building a web application.
www.ourcreativeinfo.in
PHP
Modularity
Laravel provides 20 built in libraries and modules which helps in enhancement of the
application.
Testability
Laravel includes features and helpers which helps in testing through various test cases.
Routing
Laravel provides a flexible approach to the user to define routes in the web application.
Configuration Management
A web application designed in Laravel will be running on different environments, which
means that there will be a constant change in its configuration.
Schema Builder
Schema Builder maintains the database definitions and schema in PHP code.
Authentication
Laravel eases designing authentication as it includes features such as register, forgot
password and send password reminders.
E-mail
Laravel includes a mail class which helps in sending mail with rich content and
attachments from the web application.
www.ourcreativeinfo.in
PHP
Step 1 − Visit the following URL and download composer to install it on your system.
https://getcomposer.org/download/
Step 2 − After the Composer is installed, check the installation by typing the Composer
command in the command prompt
Step 3 − Create a new directory anywhere in your system for your new Laravel project.
After that, move to path where you have created the new directory and type the
following command there to install Laravel.
composer create-project laravel/laravel –-prefer-dist
Step 4 − The above command will install Laravel in the current directory. Start the
Laravel service by executing the following command.
php artisan serve
Step 6 − Copy the URL underlined in gray in the above screenshot and open that URL in
the browser. If you see the following screen, it implies Laravel has been installed
successfully.
www.ourcreativeinfo.in
PHP
1. App
It is the application folder and includes the entire source code of the project. . The app
folder comprises various sub folders as explained below −
Console
Console includes the artisan commands necessary for Laravel. It includes a directory
named Commands, where all the commands are declared with the appropriate
signature. The file Kernal.php calls the commands declared in Inspire.php
www.ourcreativeinfo.in
PHP
Events
Exceptions
Http
The Http folder has sub-folders for controllers, middleware and application requests.
2. Bootstrap
This folder encloses all the application bootstrap scripts. It contains a sub-folder
namely cache, which includes all the files associated for caching a web application.
3. Config
The config folder includes various configurations and associated parameters required for the
smooth functioning of a Laravel application.
4. Database
As the name suggests, this directory includes various parameters for database
functionalities. It includes three sub-directories as given below −
· Seeds − This contains the classes used for unit testing database.
· Migrations − This folder helps in queries for migrating the database used in the web
application.
· Factories − This folder is used to generate large number of data records.
www.ourcreativeinfo.in
PHP
5. Public
It is the root folder which helps in initializing the Laravel application. It includes the
following files and folders −
6. Resources
Resources directory contains the files which enhances your web application.
The sub-folders included in this directory and their purpose is explained below −
· assets − The assets folder include files such as LESS and SCSS, that are required for
styling the web application.
· lang − This folder includes configuration for localization or internalization.
· views − Views are the HTML files or templates which interact with end users and
play a primary role in MVC architecture.
7. Storage
This is the folder that stores all the logs and necessary files which are needed frequently
when a Laravel project is running. The sub-folders included in this directory and their
purpose is given below −
· app − This folder contains the files that are called in succession.
· framework − It contains sessions, cache and views which are called frequently.
· Logs − All exceptions and error logs are tracked in this sub folder.
8. Tests
www.ourcreativeinfo.in
PHP
All the unit test cases are included in this directory. The naming convention for naming test
case classes is camel_case and follows the convention as per the functionality of the class.
9. Vendor
Laravel is completely based on Composer dependencies, for example to install Laravel setup
or to include third party libraries, etc.
Environment variables are those which provide a list of web services to your web application.
Sometimes you may need to update some configuration values or perform maintenance
on your website.
and
9. Define Routing?
In PHP, routing is a mechanism that determines which controllers and actions to execute based
on a requested URL.
www.ourcreativeinfo.in
PHP
1. Basic Routing
All the application routes are registered within the app/routes.php file. This file tells
Laravel for the URIs it should respond to and the associated controller will give it a
particular call.
<?php
Route::get('/', function () {
return view('welcome');
});
2. Route Parameters
Sometimes in the web application, you may need to capture the parameters passed with
the URL. For this, you should modify the code in routes.php file.
Example -
Route::get('ID/{id}',function($id) {
echo 'ID: '.$id;
});
3. Named Routes
Named routes allow a convenient way of creating routes. The chaining of routes can be
specified using name method onto the route definition.
The following code shows an example for creating named routes with controller −
Route::get('user/profile', 'UserController@showProfile')->name('profile');
www.ourcreativeinfo.in
PHP
www.ourcreativeinfo.in