0% found this document useful (0 votes)
11 views

PHP Unit-1

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

PHP Unit-1

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 25

PHP and MySql :

. Earlier customers are very happy with products to purchase from this
website.
But with more traffic and user base.
Rob Started receiving more complaint to the customer,not related to the
products,but website itself
PHP Useful in many ways:

Origin and History


● PHP was created by Rasmus Lerdorf in 1994 and initially stood
for “Personal Home Page.” Over the years, it evolved into “PHP:
Hypertext Preprocessor.”
● PHP is open-source and has a large community of developers
contributing to its development.

Purpose of using PHP


● PHP is primarily used for server-side web development. It
enables the creation of dynamic web pages by embedding PHP
code within HTML.
● PHP can perform various tasks, including handling form data,
generating dynamic page content, managing databases, and
interacting with servers.
Define PHP?

PHP is an open-source server side scripting language that is embedded


into HTML and used for web development

Syntax

<?php
PHP code goes here
?>

Example:
<html>

<head>
<title>PHP Hello World</title>
</head>

<body>
<?php echo "Hello, World! This is PHP code";
?>
</body>

</html>

Output:
Hello, World! This is PHP code

Features of PHP
● Simple:`Easy to learn language
● Highly flexible:changes can be done without developers
intervention
● Platform Independent: It Runs on every platform.
● Interpreted: It does not need to be complied
● Fast:It loads websites faster
● Open Source:it is free to use and implemented
● Secure:The Php frameworks provide security to websites
● Large PHP Community:since php is a old language it as
grown up to a large community which is very helpful and makes
a language is most stable

PHP Case Sensitivity: In PHP, keywords (e.g. if, else, while, echo,
etc.), classes, functions, and user-defined functions are not
case-sensitive.

<!DOCTYPE html>

<html> -
<body>

<?php

Echo "Hello World!<br>";

echo "Hello World!<br>";


Echo "Hello World!<br>";
?>

</body>

</html>

Output:
Installation and Configuration of php:

Install PHP:

To install PHP, we will suggest you install AMP(Accelerated Mobile Pages) (Apache,
MySQL, PHP) software stack. It is available for all operating systems. There are
many AMP options available in the market that are given below:

AMP is a Google-backed framework for creating fast-loading and


streamlined web pages optimized for mobile devices.

○ WAMP for Windows

○ LAMP for Linux

○ MAMP for Mac

○ SAMP for Solaris

○ FAMP for FreeBSD

○ XAMPP (Cross, Apache, MySQL, PHP, Perl) for Cross Platform: It includes
some other components too such as FileZilla, OpenSSL, Webalizer, Mercury
Mail, etc.

How to install XAMPP server on windows


We will learn how to install the XAMPP server on windows platform step by step.
Follow the below steps and install the XAMPP server on your system.

Step 1: Click on the above link provided to download the XAMPP server according
to your window requirement.
Step 2: After downloading XAMPP, double click on the downloaded file and allow
XAMPP to make changes in your system. A window will pop-up, where you have to
click on the Next button.

Step 3: Here, select the components, which you want to install and click Next

Step 4: Choose a folder where you want to install the XAMPP in your system and
click Next.
Step 5: Click Next and move ahead.

Step 6: XAMPP is ready to install, so click on the Next button and install the XAMPP

Step 7: A finish window will display after successful installation. Click on the Finish
button.
Step 8: XAMPP is ready to use. Start the Apache server and MySQL and run the php
program on the localhost.
Embedding PHP code in your webpage:
Embedding PHP code into a web page allows you to dynamically generate content
based on server-side logic. Here's a basic example of embedding PHP code within an
HTML file

● <?php and ?> are PHP opening and closing tags, respectively.
● Inside the PHP tags, you can write PHP code.
● echo is a PHP function used to output content.
● date("Y-m-d") is a PHP function that returns the current date in the specified
format.
● Variables in PHP start with the dollar sign $.
● You can mix HTML and PHP freely within a PHP file.

When a user visits this web page, the PHP code will be executed on the server-side,
and the resulting HTML (along with any output generated by PHP) will be sent to the
user's browser.

<html>

<body>
<h1> First PHP Webpage </h1>

<?php

Echo “ hello world”;

?>

</body>

</html>

In this example:

​ .PHP code is embedded between <?php and ?> tags.


​ . Within the PHP code, you can write any PHP statements, including variable
declarations, loops, conditionals, function calls, etc.
​ . PHP code can interact with HTML by generating dynamic content, as shown
with the echo statements.
​ . After processing, the server sends the HTML content to the client's browser,
.which renders the page as a combination of static HTML and dynamically
generated content from PHP.

Understanding PHP:
PHP (Hypertext Preprocessor) is a server-side scripting language that is widely used
for web development. It's particularly well-suited for creating dynamic web pages
and
interacting with databases. Here are some key concepts to understand about PHP:

1. Server-side Scripting: Unlike client-side languages like JavaScript, PHP is


executed on the server. This means that PHP code is processed on the web
server before the resulting HTML is sent to the client's browser.
2. Embedding: PHP code can be embedded directly into HTML files, allowing you
to mix PHP and HTML seamlessly. This makes it easy to generate dynamic
content within your web pages.
3. Variables: PHP uses the $ symbol to denote variables. Variables in PHP are
loosely typed, meaning you don't need to declare their type explicitly.
4. Control Structures: PHP supports various control structures such as if-else
statements, loops (for, while, foreach), and switch statements, allowing you to
control the flow of your code.
5. Functions: PHP allows you to define and call functions, which are reusable
blocks of code. PHP comes with many built-in functions, and you can also
create your own custom functions
6. Arrays: PHP supports both indexed arrays and associative arrays. Indexed
arrays are ordered lists of values, while associative arrays are collections of
key-value pairs.

Indexed Array Associative Array

Has numeric keys or indexes Each key has its value

Indexes start with 0 and are Keys are assigned manually and can be
automatically assigned strings too

Example: Example:

$fruits = array(“orange”, $empdetails =


“apple”, banana); array(“Sam”=>1200,
“Mike”=>1201,
“Mac”=>1202);
Here, orange is $fruits[0], apple is
$fruits[1] and banana is $fruits[2]
Here, the individual values can be
accessed as,

$empdetails[“Sam”] = “1200”;

7. Super Globals: PHP provides several predefined arrays called superglobals,


such as $_GET, $_POST, $_SESSION, and $_COOKIE, which allow you to access
data passed from forms, cookies, and sessions.
$_POST : It is a super global variable used to collect data from the HTML

form after submitting it. When form uses method post to transfer data,

the data is not visible in the query string, because of which security levels

are maintained in this method.


$_GET : $_GET is a super global variable used to collect data from the

HTML form after submitting it. When form uses method get to transfer

data, the data is visible in the query string, therefore the values are not

hidden. $_GET super global array variable stores the values that come in

the URL.

8. Database Integration: PHP has built-in functions for interacting with


databases, such as MySQL, PostgreSQL, and SQLite. You can connect to a
database, execute queries, and retrieve data using PHP.
9. Security: PHP has features to help you secure your web applications, such as
input validation, output escaping, and authentication mechanisms.

HTML and White Space:

In HTML, white space refers to spaces, tabs, and line breaks. White space is
generally ignored by web browsers when rendering HTML content. This means that
you can use white space in your HTML code to format and organize it in a way that
makes it more readable for humans without affecting the layout of the rendered
page.

Here are a few key points to understand about white space in HTML:

1. Spaces and Tabs: Whether you use spaces or tabs for indentation in your
HTML code is a matter of personal preference. Browsers will treat both
spaces and tabs as white space and ignore them when rendering the page.

2. Line Breaks: Line breaks in the HTML code are also considered white space
and are generally ignored by browsers. This means that you can use line
breaks to break up long lines of code or to separate different sections of your
HTML document without affecting the layout of the rendered page.

3. Multiple White Spaces: When it comes to multiple consecutive white spaces


(spaces, tabs, or line breaks), browsers collapse them into a single space
when rendering the HTML content. This behavior helps prevent unintentional
gaps or spacing in the rendered page.
Writing Comments in PHP:

In PHP, you can write comments to document your code or temporarily disable
certain sections of code. There are two types of comments in PHP: single-line
comments and multi-line comments.

● Single-Line Comments: Single-line comments begin with “//” and continue


until the end of the line. They are used to add comments on a single line.
<?php
// This is a single-line comment
echo "Hello, world!"; // This is also a single-line comment
?>

● Multi-Line Comments: Multi-line comments start with /* and end with */.
They can span multiple lines and are useful for adding comments that span
several lines.

<?php
echo "Hello, world!";
/* This is a multi-line comment
that spans multiple lines */
?>

Sending Data to the web browser:


To send data to a web browser in PHP, you typically use the “echo” or “print”
statements to output content directly into the HTTP( Hyper Text Transfer Protocol)
response. Here's how you can send various types of data to the web browser:

● Sending HTML Content:


<?php
// Sending HTML content to the browser
echo "<h1>Hello, world!</h1>";
?>

● Sending Text Content:


<?php
// Sending plain text to the browser
echo "Hello, world!";
?>
● Sending Variables:
<?php
// Sending variable content to the browser
$name = "John";
echo "Hello, $name!";
?>
● Sending HTML with PHP Variables:
<?php
// Sending HTML with PHP variables to the browser
$name = "John";
echo "<p>Hello, $name! Welcome to our website.</p>";
?>

● Using print Statement (Similar to echo):

<?php
// Using print statement to send content to the browser
print "Hello, world!";
?>

● Sending JSON Data:


<?php
// Sending JSON data to the browser
$data = array("name" => "John", "age" => 30);
header('Content-Type: application/json');
echo json_encode($data);
?>
● Sending File Content (e.g., an image):
<?php
// Sending image file content to the browser
header('Content-Type: image/jpeg');
readfile('path_to_image.jpg');
?>
Data Types in PHP:
In PHP, like many programming languages, data types determine the nature of the
data stored in variables or returned by functions. Here are the basic data types in
PHP:
Scalar Types:
● Integer: Whole numbers, e.g., 1, 100, -500.
● Float (Floating-Point Numbers): Numbers with a fractional part, e.g., 3.14, -0.5,
2.0.
● String: Sequence of characters, e.g., "Hello", 'World'.
● Boolean: Represents either true or false.
Compound Types:
● Array: Ordered map that stores key-value pairs. Arrays can contain
multiple values under a single name.
● Object: Instances of classes in PHP. Objects have properties and
methods.
Special Types:
● NULL: Represents a variable with no value or a variable explicitly set to null.
● Resource: Represents a reference to an external resource (like a database
connection). It's a special variable type used to hold resource handles.

For example:
// Integer
$age = 30;

// Float
$price = 3.99;

// String
$name = "John";

// Boolean
$is_admin = true;

// Array
$colors = array("red", "green", "blue");
// Object
class Person {
public $name;
public $age;
}

$person = new Person();


$person->name = "Alice";
$person->age = 25;

// NULL
$null_variable = null;

// Resource (e.g., database connection)


$database_connection = mysqli_connect("localhost", "username", "password",
"database");

Keywords IN PHP:

Control Structures:
● if, else, elseif: Used for conditional statements.
● switch, case, break, default: Used for switch statements.
● while, do, for, foreach: Used for loop control.
● continue, break: Used to control loop execution.

Function Declaration and Invocation:


● function: Used to declare functions.
● return: Used to return a value from a function.
● callable: Used for type hinting functions or methods.
● new: Used to create instances of classes.

Class Declaration and Instantiation:


● class: Used to declare classes.
● extends, implements: Used for class inheritance and interface
implementation.
● public, protected, private: Used to declare visibility of class members.
● static: Used to declare static properties and methods.
● final: Used to prevent classes from being extended or methods from being
overridden.
● abstract: Used to declare abstract classes or methods.

Namespace Declaration:
● namespace, use: Used to declare namespaces and import namespaces

Error Handling:
● try, catch, finally: Used for exception handling.
● throw: Used to throw exceptions.
Variable Scope:
● global: Used to access global variables within a function.
● static: Used to declare static variables within a function.
Other:
● echo, print: Used to output data to the browser or console.
● const: Used to declare constants.
● define: Used to define constants.
● unset: Used to unset a variable.
● empty: Used to check if a variable is empty.

Using Variables in PHP:

In PHP, variables are used to store and manipulate data. Variable names in PHP must
start with a dollar sign ($) followed by the name of the variable. Here's how you can
use variables in PHP:

Variable Declaration:You can declare variables in PHP using the following syntax:
$variable_name = value;

Variable Naming Rules:


● Variable names must start with a dollar sign ($), followed by a
letter or underscore, and then followed by any combination of
letters, numbers, or underscores.
● Variable names are case-sensitive

Variable Scope: Variables can have different scopes:


● Global Scope: Variables declared outside functions are global and can
be accessed from anywhere in the script.
● Local Scope: Variables declared inside functions are local and can only
be accessed within the function.

$globalVar = "I am global";

function myFunction() {
$localVar = "I am local";
echo $globalVar; // Accessing global variable inside function
}

myFunction();

Variable Interpolation: You can include variables directly within


double-quoted strings. This is known as variable interpolation.

$name = "John";
echo "Hello, $name!"; // Output: Hello, John!

Variable Concatenation: You can concatenate variables with strings using


the “.” operator.

$firstName = "John";
$lastName = "Doe";
$fullName = $firstName . " " . $lastName;
Variable Output: You can output variables using echo, print, or by including
them within a string.

$name = "John";
echo "Hello, $name!"; // Output: Hello, John!
Constants in PHP:

In PHP, constants are similar to variables, but they hold values that cannot be
changed once they're defined. Constants are particularly useful for storing
configuration settings

Defining Constants: Constants are defined using the “define()” function. It


takes two arguments: the name of the constant and its value.

<?php
define("PI", 3.14);
define("SITE_NAME", "My Website");
?>

Using Constants: Once defined, you can use constants anywhere in your
script without the need for a dollar sign “$”.

<?php
echo PI; // Output: 3.14
echo SITE_NAME; // Output: My Website
?>
Case Sensitivity: By default, constant names are case-sensitive.

define("GREETING", "Hello, world!"); (CAPITAL LETTER)


echo greeting; // This will output nothing because "greeting"(SMALL
LETTER )is not the same as "GREETING".

Constants and Functions: Constants can be used within functions and


classes.

function myFunction()
{
echo PI;
}
myFunction(); // Output: 3.14

Magic Constants: PHP provides a set of predefined constants, known as


magic constants, which change based on their usage. These constants start
and end with two underscores. Examples include ‘__ _FILE__’,’ __ _LINE__’,
‘__ _DIR__ _’, etc.

<?php
echo __FILE__; // Outputs the current file's path
echo __LINE__; // Outputs the current line number
?>

Expressions in PHP:
In PHP, expressions are combinations of values, variables, operators,
and function calls that evaluate to a single value. PHP supports a wide range
of expressions, including arithmetic expressions, comparison expressions,
logical expressions, string expressions, and more.

Here are some common types of expressions in PHP:

● Arithmetic Expressions: These involve arithmetic operations such as


addition, subtraction, multiplication, division, and modulus.

$result = 10 + 5; // Addition

$result = 10 - 5; // Subtraction

$result = 10 * 5; // Multiplication

$result = 10 / 5; // Division

$result = 10 % 3; // Modulus (remainder of division)

● Comparison Expressions: These involve comparison operations that


evaluate to boolean values (true or false).

$result = 10 > 5; // Greater than

$result = 10 < 5; // Less than


$result = 10 == 5; // Equal to

$result = 10 != 5; // Not equal to

$result = 10 >= 5; // Greater than or equal to

$result = 10 <= 5; // Less than or equal to

● Logical Expressions: These involve logical operations such as AND


(&&), OR (||), and NOT (!).

$result = ($x > 0) && ($y < 10); // AND

$result = ($x > 0) || ($y < 10); // OR

$result = !($x > 0); // NOT

● String Expressions: These involve operations on strings such as


concatenation.

$result = "Hello, " . "world!"; // String concatenation

● Function Call Expressions: These involve calling functions and can


include parameters passed to those functions.

$result = strlen("Hello"); // Function call to get string length

Operators in PHP:PHP supports various types of operators, including


arithmetic operators, assignment operators, comparison operators, logical
operators, and more. Here's an overview of the most common operators in PHP:

Arithmetic Operators:
● Addition “+”
● Subtraction “-”
● Multiplication “*”
● Division “/”
● Modulus % (returns the remainder of a division)
Assignment Operators:
● Assignment =
● Addition assignment +=
● Subtraction assignment -=
● Multiplication assignment *=
● Division assignment /=
● Modulus assignment %=
● Concatenation assignment .= (for strings)
● Exponentiation assignment **=
Comparison Operators:
● Equal to ==
● Identical to === (compares both value and type)
● Not equal to != or <>
● Not identical to !==
● Greater than >
● Less than <
● Greater than or equal to >=
● Less than or equal to <=

Logical Operators:

○ AND && or and


○ OR || or or
○ NOT ! or not
○ XOR xor (exclusive OR)

String Operators:

○ Concatenation .
○ Concatenation assignment .= (similar to += for strings)

Increment/Decrement Operators:

○ Increment ++
○ Decrement --

You might also like