0% found this document useful (0 votes)
75 views36 pages

PHP Unit 1

The document provides an introduction to PHP programming including: 1. PHP is an open-source server-side scripting language used for web development that allows embedding code into HTML. 2. PHP has many advantages such as being easy to learn, open source, portable, fast performance, and having a vast community support. 3. The document discusses what can be done with PHP including dynamically generating pages/files, working with databases, form handling, and restricting unauthorized access.

Uploaded by

Nisarg Trivedi
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)
75 views36 pages

PHP Unit 1

The document provides an introduction to PHP programming including: 1. PHP is an open-source server-side scripting language used for web development that allows embedding code into HTML. 2. PHP has many advantages such as being easy to learn, open source, portable, fast performance, and having a vast community support. 3. The document discusses what can be done with PHP including dynamically generating pages/files, working with databases, form handling, and restricting unauthorized access.

Uploaded by

Nisarg Trivedi
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/ 36

BCA PHP Programming

PHP-Hyper Text Prepocessor

Unit - I
• Introduction to PHP:

• Web-Technologies, Server side technologies, Web -server, Web-


browser,Introduction PHP,

• Future of PHP, Client-side scripting, Server-side scripting, adding


PHP to HTML Syntax and variable, control and function, Passing
information between page

• Variable Function: Get type,set type, isset, unset, strval, floatval,


inval, print_r,String

• Array and Array Function, Date function, String Function.

• Working with Forms: Creating form, Handling form, Validating form

• data,Accessing form data, use of Hidden fields to save State,


Redirecting user, file Upload and Sending Mail on Form Submission.

Introduction to PHP:

What is PHP

• PHP is an open-source, interpreted, and object-oriented scripting


language that can be executed at the server-side. PHP is well suited for
web development. Therefore, it is used to develop web applications (an
application that executes on the server and generates the dynamic
page.).

• PHP stands for Hypertext Preprocessor.

• PHP is an interpreted language, i.e., there is no need for compilation.

• PHP is faster than other scripting languages, for example, ASP and JSP.

• PHP is a server-side scripting language, which is used to manage the


dynamic content of the website.

1
Prepared By:- Prof. Paresh Patel ,MCMSR, Visnagar
BCA PHP Programming

• PHP can be embedded into HTML.

• PHP is an object-oriented language.

• PHP is an open-source scripting language.

• PHP is simple and easy to learn language.

Why use PHP

PHP is a server-side scripting language, which is used to design the dynamic


web applications with MySQL database.

o It handles dynamic content, database as well as session tracking for


the website.
o You can create sessions in PHP.
o It can access cookies variable and also set cookies.
o It helps to encrypt the data and apply validation.
o PHP supports several protocols such as HTTP, POP3, SNMP, LDAP,
IMAP, and many more.
o Using PHP language, you can control the user to access some pages of
your website.
o As PHP is easy to install and set up, this is the main reason why PHP is
the best language to learn.
o PHP can handle the forms, such as - collect the data from users using
forms, save it into the database, and return useful information to the
user. For example - Registration form.

PHP Features

Performance:

PHP script is executed much faster than those scripts which are written in other
languages such as JSP and ASP. PHP uses its own memory, so the server
workload and loading time is automatically reduced, which results in faster
processing speed and better performance.

2
Prepared By:- Prof. Paresh Patel ,MCMSR, Visnagar
BCA PHP Programming

Open Source:

PHP source code and software are freely available on the web. You can develop
all the versions of PHP according to your requirement without paying any cost.
All its components are free to download and use.

Familiarity with syntax:

PHP has easily understandable syntax. Programmers are comfortable coding with
it.

Embedded:

PHP code can be easily embedded within HTML tags and script.

Platform Independent:

PHP is available for WINDOWS, MAC, LINUX & UNIX operating system. A PHP
application developed in one OS can be easily executed in other OS also.

Database Support:

PHP supports all the leading databases such as MySQL, SQLite, ODBC, etc.

Error Reporting -

PHP has predefined error reporting constants to generate an error notice or


warning at runtime. E.g., E_ERROR, E_WARNING, E_STRICT, E_PARSE.

Loosely Typed Language:

PHP allows us to use a variable without declaring its datatype. It will be taken
automatically at the time of execution based on the type of data it contains on
its value.

Web servers Support:

3
Prepared By:- Prof. Paresh Patel ,MCMSR, Visnagar
BCA PHP Programming

PHP is compatible with almost all local servers used today like Apache, Netscape,
Microsoft IIS, etc.

Security:

PHP is a secure language to develop the website. It consists of multiple layers of


security to prevent threads and malicious attacks.

Control:

Different programming languages require long script or code, whereas PHP can
do the same work in a few lines of code. It has maximum control over the
websites like you can make changes easily whenever you want.

What You Can Do with PHP


There are lot more things you can do with PHP.

• You can generate pages and files dynamically.

• You can create, open, read, write and close files on the server.

• You can collect data from a web form such as user information,
email, phone no, etc.

• You can send emails to the users of your website.

• You can send and receive cookies to track the visitor of your website.

• You can store, delete, and modify information in your database.

• You can restrict unauthorized access to your website.

• You can encrypt data for safe transmission over internet.

Advantages of PHP over Other Languages

4
Prepared By:- Prof. Paresh Patel ,MCMSR, Visnagar
BCA PHP Programming

If you're familiar with other server-side languages like ASP.NET or Java, you
might be wondering what makes PHP so special. There are several
advantages why one should choose PHP.

• Easy to learn: PHP is easy to learn and use. For beginner


programmers who just started out in web development, PHP is often
considered as the preferable choice of language to learn.

• Open source: PHP is an open-source project. It is developed and


maintained by a worldwide community of developers who make its source
code freely available to download and use.

• Portability: PHP runs on various platforms such as Microsoft


Windows, Linux, Mac OS, etc. and it is compatible with almost all servers
used today such Apache, IIS, etc.

• Fast Performance: Scripts written in PHP usually execute or runs


faster than those written in other scripting languages like ASP, Ruby,
Python, Java, etc.

• Vast Community: Since PHP is supported by the worldwide


community, finding help or documentation related to PHP online is
extremely easy.

File: first.php

1. <!DOCTYPE>
2. <html>
3. <body>
4. <?php
echo "<h2>Hello First PHP</h2>";
5. ?>
6. </body>
7. </html>

5
Prepared By:- Prof. Paresh Patel ,MCMSR, Visnagar
BCA PHP Programming

Output:

Hello First PHP

Web Technology
You probably know that computers don't communicate with each other the way that people
do. Instead, computers require codes, or directions. These binary codes and commands
allow computers to process needed information. Every second, billions upon billions of ones
and zeros are processed in order to provide you with the information you need.
So what does that have to do with your ability to post your latest pictures online? Everything.
The methods by which computers communicate with each other through the use of markup
languages and multimedia packages is known as web technology.

Client-Side Scripting
Generally refers to computer programs on the web that are executed by the user's web
browser, instead of on a web server, enabling web pages to be scripted. Client-side scripts
do not require additional software on the server but instead utilize the user's web browser to
understand the scripting language in which it is written.

Example-javascript,vbscript

JavaScript
JavaScript is a scripting language that is used along with HTML and CSS as the three core
components of the World Wide Web. JavaScript has first-class functions and is used in most
websites. JavaScript does not have any I/O which means that it has to be embedded in the
host environment. JavaScript is also used in PDF documents, game development, and
desktop and mobile applications. JavaScript is most commonly used to make DHTML by
adding client-side behavior to HTML pages.

Server-Side Scripting
Server-side scripting is a technique used in web development that involves using scripts on a
web server which produce a unique response for each user's request to the website.

Example-php,jsp

Web Browser

6
Prepared By:- Prof. Paresh Patel ,MCMSR, Visnagar
BCA PHP Programming

• Web Browser is a software which is used to browse and display pages


available over internet.
• A web browser sends request to server for web based documents and
services.
• Web browser sends an HTTP Request and gets a HTTP Response.
• Web browser has no processing model.
• Web browsers stores user data in cookies in local machine.
• Web Browser is installed on user's machine.
• Example- Google Chrome,Opera,mozila firefox,UC browser

Web Server

• Web server is a software which provides these documents when


requested by web browsers.
• Web server sees and approves those requests made by web browsers
and sends the document in response.
• Web server receives HTTP Request and sends a HTTP Response.
• Web server follows three major processing models: process based, thread
based or hybrid.
• Web server provide an area to store the website.
• Web server can be installed any where but it need to be on a network or
on local computer.
• Example- Apache Server

Add PHP in HTML Syntax


When building a complex page, at some point you will be faced with the need to
combine PHP and HTML to achieve your needed results. At first point, this can
seem complicated, since PHP and HTML are two separate languages, but this is
not the case. PHP is designed to interact with HTML and PHP scripts can be
included in an HTML page without a problem.
In an HTML page, PHP code is enclosed within special PHP tags. When a visitor
opens the page, the server processes the PHP code and then sends the output
(not the PHP code itself) to the visitor's browser. Actually it is quite simple to
integrate HTML and PHP. A PHP script can be treated as an HTML page, with
bits of PHP inserted here and there. Anything in a PHP script that is not
contained within <?php ?> tags is ignored by the PHP compiler and passed
directly to the web browser. If you look at the example below you can see what a
full PHP script might look like:
<head></head>
<body class="page_bg">

7
Prepared By:- Prof. Paresh Patel ,MCMSR, Visnagar
BCA PHP Programming
Hello, today is <?php echo date('l, F jS, Y'); ?>.
</body>
</html>

More advanced techniques:

<html>
<head></head>
<body>
<ul>
<?php for($i=1;$i<=5;$i++){ ?>
<li>Menu Item <?php echo $i; ?></li>
<?php } ?>
</ul>
</body>
</html>

PHP in HTML using short_open_tag


If you want to shorten your code as much as possible, you can go for the
short_tags option. This will save you from typing <?php at the beginning of the
code, shortening it to just <?. In order to enable this, you should update the
php.ini file and turn the "short_tags" setting from "Off" to "On". While on most
servers this setting is already turned on, it's always best to check beforehand. A
problem that can occur if using short tags is a conflict with the XML usage. For
XML, the <? syntax will start a processing function. To avoid this problem, the
alternative <?= tag can be used.

<html>
<head></head>
<body class="page_bg">
Hello, today is <?=date('l, F jS, Y'); ?>.
</body>
</html>

HTML in PHP using echo

<?php
echo "<html>";
echo "<head></head>";
echo "<body class=\"page_bg\">";
echo "Hello, today is ";
echo date('l, F jS, Y'); //other php code here echo "</body>";
echo "</html>";
?>

8
Prepared By:- Prof. Paresh Patel ,MCMSR, Visnagar
BCA PHP Programming

PHP Variables
Variables are "containers" for storing information.

Creating (Declaring) PHP Variables

In PHP, a variable starts with the $ sign, followed by the name of the
variable:

Example
<?php
$txt = "Hello world!";
$x = 5;
$y = 10.5;
?>

After the execution of the statements above, the variable $txt will
hold the value Hello world!, the variable $x will hold the value 5, and the
variable$y will hold the value 10.5.

Rules for PHP variables:

• A variable starts with the $ sign, followed by the name of the


variable
• A variable name must start with a letter or the underscore
character
• A variable name cannot start with a number
• A variable name can only contain alpha-numeric characters and
underscores (A-z, 0-9, and _ )
• Variable names are case-sensitive ($age and $AGE are two different
variables)

Remember that PHP variable names are case-sensitive!

Output Variables

The PHP echo statement is often used to output data to the screen.

The following example will show how to output text and a variable:

Example

9
Prepared By:- Prof. Paresh Patel ,MCMSR, Visnagar
BCA PHP Programming

<?php
$txt = "W3Schools.com";
echo "I love $txt!";
?>

PHP Variables Scope

In PHP, variables can be declared anywhere in the script.

The scope of a variable is the part of the script where the variable can be
referenced/used.

PHP has three different variable scopes:

• local
• global
• static

Global Scope

A variable declared outside a function has a GLOBAL SCOPE and can only
be accessed outside a function:

Example

Variable with 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>";


?>

10
Prepared By:- Prof. Paresh Patel ,MCMSR, Visnagar
BCA PHP Programming

PHP The global Keyword

The global keyword is used to access a global variable from within a


function.

To do this, use the global keyword before the variables (inside the
function):

Example
<?php
$x = 5;
$y = 10;

function myTest() {
global $x, $y;
$y = $x + $y;
}

myTest();
echo $y; // outputs 15
?>

PHP also stores all global variables in an array called $GLOBALS[index].


Theindex holds the name of the variable. This array is also accessible from
within functions and can be used to update global variables directly.

The example above can be rewritten like this:

Example
<?php
$x = 5;
$y = 10;

function myTest() {
$GLOBALS['y'] = $GLOBALS['x'] + $GLOBALS['y'];
}

myTest();

11
Prepared By:- Prof. Paresh Patel ,MCMSR, Visnagar
BCA PHP Programming

echo $y; // outputs 15


?>

LOCAL SCOPE

A variable declared within a function has a LOCAL SCOPE and can only
be accessed within that function:

Example

Variable with local scope:

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

PHP The static Keyword

Normally, when a function is completed/executed, all of its variables are


deleted. However, sometimes we want a local variable NOT to be deleted.
We need it for a further job.

To do this, use the static keyword when you first declare the variable:

Example
<?php
function myTest() {
static $x = 0;
echo $x;
$x++;
}

12
Prepared By:- Prof. Paresh Patel ,MCMSR, Visnagar
BCA PHP Programming

myTest();
myTest();
myTest();
?>

13
Prepared By:- Prof. Paresh Patel ,MCMSR, Visnagar
BCA PHP Programming

PHP - Functions

A function is a piece of code which takes one more input in the form of parameter
and does some processing and returns a value.

There are two parts which should be clear to you −

• Creating a PHP Function


• Calling a PHP Function

Creating PHP Function

creating a function its name should start with keyword function and all the PHP
code should be put inside { and } braces as shown in the following example
below – Syntax

function name_of_function()

Php code;

<?php
/* Defining a PHP Function */
function writeMessage() {
echo "You are really a nice person, Have a nice
time!";
}

/* Calling a PHP Function */


writeMessage();
?>

PHP Functions with Parameters

PHP gives you option to pass your parameters inside a function. You can pass
as many as parameters your like. These parameters work like variables inside
your function. Following example takes two integer parameters and add them
together and then print them.

14
Prepared By:- Prof. Paresh Patel ,MCMSR, Visnagar
BCA PHP Programming

<?php
function addFunction($num1, $num2) {
$sum = $num1 + $num2;
echo "Sum of the two numbers is : $sum";
}

addFunction(10, 20);
?>

This will display following result −


Sum of the two numbers is : 30

Passing Arguments by Reference

It is possible to pass arguments to functions by reference. This means that a


reference to the variable is manipulated by the function rather than a copy of the
variable's value.

Any changes made to an argument in these cases will change the value of the
original variable. You can pass an argument by reference by adding an
ampersand to the variable name in either the function call or the function
definition.
<?php
function addFive($num) {
$num += 5;
}

function addSix(&$num) {
$num += 6;
}

$orignum = 10;
addFive( $orignum );

echo "Original Value is $orignum<br />";

addSix( $orignum );
echo "Original Value is $orignum<br />";
?>

This will display following result −


Original Value is 10
Original Value is 16

PHP Functions returning value


15
Prepared By:- Prof. Paresh Patel ,MCMSR, Visnagar
BCA PHP Programming

A function can return a value using the return statement in conjunction with a
value or object. return stops the execution of the function and sends the value
back to the calling code.

You can return more than one value from a function using return array(1,2,3,4).

Following example takes two integer parameters and add them together and
then returns their sum to the calling program. Note thatreturn keyword is used
to return a value from a function.
<?php
function addFunction($num1, $num2) {
$sum = $num1 + $num2;
return $sum;
}
$return_value = addFunction(10, 20);

echo "Returned value from the function :


$return_value";
?>

This will display following result −


Returned value from the function : 30

Setting Default Values for Function Parameter

You can set a parameter to have a default value if the function's caller doesn't
pass it.

Following function prints NULL in case use does not pass any value to this
function.
?php
function printMe($param = NULL) {
print $param;
}

printMe("This is test");
printMe();
?>

This will produce following result −


This is test

16
Prepared By:- Prof. Paresh Patel ,MCMSR, Visnagar
BCA PHP Programming

Dynamic / VariableFunction Calls

It is possible to assign function names as strings to variables and then treat


these variables exactly as you would the function name itself. Following
example depicts this behaviour.
<?php
function sayHello() {
echo "Hello<br />";
}

$function_holder = "sayHello";
$function_holder();
?>

This will display following result −


Hello

Flow control in PHP

PHP if statement

The if statement has the following general form:

if (expression)
statement

The if keyword is used to check if an expression is true. If it is true, a


statement is then executed. The statement can be a single statement or a
compound statement. A compound statement consists of multiple
statements enclosed by curly brackets.
<?php

$num = 31;

if ($num > 0) {
echo "\$num variable is positive\n";
echo "\$num variable equals to $num\n";
}

17
Prepared By:- Prof. Paresh Patel ,MCMSR, Visnagar
BCA PHP Programming

If-else statement
<?php

$sex = "female";

if ($sex == "male") {
echo "It is a boy\n";
} else {
echo "It is a girl\n";
}

If-elseif statement example

<?php

echo "Enter a number: ";

$a = intval(fgets(STDIN));

if ($a < 0) {
printf("%d is a negative number\n", $a);
} elseif ($a == 0) {
printf("%d is a zero\n", $a);
} elseif ($a > 0) {
printf("%d is a positive number\n", $a);
}

We read a value from the user using the fgets() function. The value is
tested if it is a negative number or positive or if it equals to zero.

PHP switch statement

The switch statement is a selection control flow statement. It allows the


value of a variable or expression to control the flow of program execution
via a multiway branch. It creates multiple branches in a simpler way than
using the if, elseif statements.

The switch statement works with two other keywords: case and break.
The case keyword is used to test a label against a value from the round
brackets. If the label equals to the value, the statement following the case is
executed. The break keyword is used to jump out of the switchstatement.

18
Prepared By:- Prof. Paresh Patel ,MCMSR, Visnagar
BCA PHP Programming

There is an optional default statement. If none of the labels equals the


value, the default statement is executed.

domains.php
<?php

$domain = 'sk';

switch ($domain) {

case 'us':
echo "United States\n";
break;
case 'de':
echo "Germany\n";
break;
case 'sk':
echo "Slovakia\n";
break;
case 'hu':
echo "Hungary\n";
break;
default:
echo "Unknown\n";
break;
}

PHP while loop

The while is a control flow statement that allows code to be executed


repeatedly based on a given boolean condition.

This is the general form of the while loop:

while (expression):
statement

The while loop executes the statement when the expression is evaluated to
true. The statement is a simple statement terminated by a semicolon or a
compound statement enclosed in curly brackets.

whilestm.php
<?php

19
Prepared By:- Prof. Paresh Patel ,MCMSR, Visnagar
BCA PHP Programming

$i = 0;

while ($i < 5) {


echo "PHP language\n";
$i++;
}

PHP for keyword

The for loop does the same thing as the while loop. Only it puts all three
phases, initialization, testing and updating into one place, between the
round brackets. It is mainly used when the number of iteration is know
before entering the loop.

Let's have an example with the for loop.

forloop.php
<?php

$days = [ "Monday", "Tuesday", "Wednesday", "Thursday", "Friday",


"Saturday", "Sunday" ];

$len = count($days);

for ($i = 0; $i < $len; $i++) {


echo $days[$i], "\n";
}

PHP foreach statement

The foreach construct simplifies traversing over collections of data. It has


no explicit counter. The foreach statement goes through the array one by
one and the current value is copied to a variable defined in the construct.
In PHP, we can use it to traverse over an array.

foreachstm.php
<?php

$planets = [ "Mercury", "Venus", "Earth", "Mars", "Jupiter",


"Saturn", "Uranus", "Neptune" ];

foreach ($planets as $item) {


echo "$item ";

20
Prepared By:- Prof. Paresh Patel ,MCMSR, Visnagar
BCA PHP Programming

echo "\n";
?>

There is another syntax of the foreach statement. It is used with maps.

foreachstm2.php
<?php

$benelux = [ 'be' => 'Belgium',


'lu' => 'Luxembourgh',
'nl' => 'Netherlands' ];

foreach ($benelux as $key => $value) {


echo "$key is $value\n";
}

PHP break, continue statements

The break statement is used to terminate the loop. The continue statement is
used to skip a part of the loop and continue with the next iteration of the
loop.

testbreak.php
<?php

while (true) {

$val = rand(1, 30);


echo $val, " ";
if ($val == 22) break;
}

echo "\n";

We define an endless while loop. There is only one way to jump out of a
such loop—using thebreak statement. We choose a random value from 1 to
30 and print it. If the value equals to 22, we finish the endless while loop.
$ php testbreak.php
6 11 13 5 5 21 9 1 21 22

We might get something like this.

21
Prepared By:- Prof. Paresh Patel ,MCMSR, Visnagar
BCA PHP Programming

In the following example, we print a list of numbers that cannot be divided


by 2 without a remainder.

testcontinue.php
<?php

$num = 0;

while ($num < 1000) {

$num++;
if (($num % 2) == 0) continue;

echo "$num ";

echo "\n";

We iterate through numbers 1..999 with the while loop.

if (($num % 2) == 0) continue;

If the expression $num % 2 returns 0, the number in question can be divided


by 2. The continuestatement is executed and the rest of the cycle is skipped.
In our case, the last statement of the loop is skipped and the number is not
printed to the console. The next iteration is started.

Passing Information between Pages

Forms can be used to pass values to different sites. Forms can submit
the data to a processing script running at a different URL in different server.
These are some of the way of transferring data variables between pages.

PHP Global Variables - Superglobals

Some predefined variables in PHP are "superglobals", which means that


they are always accessible, regardless of scope - and you can access

22
Prepared By:- Prof. Paresh Patel ,MCMSR, Visnagar
BCA PHP Programming

them from any function, class or file without having to do anything


special.

The PHP superglobal variables are:

• $GLOBALS
• $_SERVER
• $_REQUEST
• $_POST
• $_GET
• $_FILES
• $_ENV
• $_COOKIE
• $_SESSION

PHP $GLOBALS

$GLOBALS is a PHP super global variable which is used to access global


variables from anywhere in the PHP script (also from within functions or
methods).

PHP stores all global variables in an array called $GLOBALS[index].


The indexholds the name of the variable.

The example below shows how to use the super global variable
$GLOBALS:

<?php
$x = 75;
$y = 25;

function addition() {
$GLOBALS['z'] = $GLOBALS['x'] + $GLOBALS['y'];
}

addition();
echo $z;
?>

23
Prepared By:- Prof. Paresh Patel ,MCMSR, Visnagar
BCA PHP Programming

PHP $_SERVER

$_SERVER is a PHP super global variable which holds information about


headers, paths, and script locations.

The example below shows how to use some of the elements in


$_SERVER:

PHP $_REQUEST

PHP $_REQUEST is a PHP super global variable which is used to collect


data after submitting an HTML form.

<html>
<body>

<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">


Name: <input type="text" name="fname">
<input type="submit">
</form>

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// collect value of input field
$name = $_REQUEST['fname'];
if (empty($name)) {
echo "Name is empty";
} else {
echo $name;
}
}
?>

</body>
</html>

PHP $_POST

PHP $_POST is a PHP super global variable which is used to collect form
data after submitting an HTML form with method="post". $_POST is also
widely used to pass variables.

24
Prepared By:- Prof. Paresh Patel ,MCMSR, Visnagar
BCA PHP Programming

<html>
<body>

<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">


Name: <input type="text" name="fname">
<input type="submit">
</form>

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// collect value of input field
$name = $_POST['fname'];
if (empty($name)) {
echo "Name is empty";
} else {
echo $name;
}
}
?>

</body>
</html>

PHP $_GET

PHP $_GET is a PHP super global variable which is used to collect form
data after submitting an HTML form with method="get".

$_GET can also collect data sent in the URL.

Assume we have an HTML page that contains a hyperlink with


parameters:

<html>
<body>

<a href="test_get.php?subject=PHP&web=W3schools.com">Test $GET</a>

</body>
</html>

25
Prepared By:- Prof. Paresh Patel ,MCMSR, Visnagar
BCA PHP Programming

<html>
<body>

<?php
echo "Study " . $_GET['subject'] . " at " . $_GET['web'];
?>

</body>
</html>

settype — Set the type of a variable to specify type


settype ( mixed &$var , string $type ) : bool

example
<?php
$foo = "5bar"; // string
$bar = true; // boolean

settype($foo, "integer"); // $foo is now 5 (integer)


settype($bar, "string"); // $bar is now "1" (string)
?>

gettype — Get the type of a variable


gettype ( mixed $value ) : string

<?php

$data = array(1, 1., NULL, new stdClass, 'foo');

foreach ($data as $value) {


echo gettype($value), "\n";
}

?>

Output
integer
double
NULL
object
string

is_array — Finds whether a variable is an array

Returns true if value is an array, false otherwise.

26
Prepared By:- Prof. Paresh Patel ,MCMSR, Visnagar
BCA PHP Programming
<?php
$yes = array('this', 'is', 'an array');

echo is_array($yes) ? 'Array' : 'not an Array';


echo "\n";

$no = 'this is a string';

echo is_array($no) ? 'Array' : 'not an Array';


?>

Output
Array
not an Array

• is_float() - Finds whether the type of a variable is float


• is_int() - Find whether the type of a variable is integer
• is_string() - Find whether the type of a variable is string
• is_object() - Finds whether a variable is an object

intval — Get the integer value of a variable

intval ( mixed $value , int $base = 10 ) : int

Returns the int value of value, using the specified base for the conversion (the
default is base 10). intval() should not be used on objects, as doing so will emit
an E_NOTICE level error and return 1.

The integer value of value on success, or 0 on failure. Empty arrays return 0,


non-empty arrays return 1.

<?php
echo intval(42); // 42
echo intval(4.2); // 4
?>

strval — Get string value of a variable

strval ( mixed $value ) : string

<?php
echo strval(42);?> output “42”

27
Prepared By:- Prof. Paresh Patel ,MCMSR, Visnagar
BCA PHP Programming

floatval — Get float value of a variable

floatval ( mixed $value ) : float

Return Values

The float value of the given variable. Empty arrays return 0, non-empty arrays
return 1.

Strings will most likely return 0

<?php
$var = '122.34343The';
$float_value_of_var = floatval($var);
echo $float_value_of_var; // 122.34343
?>

<?php
$var = 'The122.34343';
$float_value_of_var = floatval($var);
echo $float_value_of_var; // 0
?>

isset() Function
Check whether a variable is empty. Also check whether the variable is
set/declared:
isset(variable, ....);
<?php
$a = 0;
// True because $a is set
if (isset($a)) {
echo "Variable 'a' is set.<br>";
}

$b = null;
// False because $b is NULL
if (isset($b)) {
echo "Variable 'b' is set.";
}
?>

28
Prepared By:- Prof. Paresh Patel ,MCMSR, Visnagar
BCA PHP Programming

unset() Function

The unset() function unsets a variable.

Syntax:-unset(variable, ....);
<?php
$a = "Hello world!";
echo "The value of variable 'a' before unset: " . $a . "<br>";
unset($a);
echo "The value of variable 'a' after unset: " . $a;
?>

print_r() Function
The print_r() function prints the information about array/variable in a
more human-readable way.

Syntax:-print_r(variable, return);

<?php
$a = array("red", "green", "blue");
print_r($a);

echo "<br>";

$b = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");


print_r($b);
?>

Output:-
Array ( [0] => red [1] => green [2] => blue )
Array ( [Peter] => 35 [Ben] => 37 [Joe] => 43 )

PHP Date/Time Functions


checkdate();-checkdate(month, day, year)

Check if several dates are valid Gregorian dates: return true or false
<?php
var_dump(checkdate(12,31,-400));
echo "<br>";
var_dump(checkdate(2,29,2003));
echo "<br>";
var_dump(checkdate(2,29,2004));
?>

29
Prepared By:- Prof. Paresh Patel ,MCMSR, Visnagar
BCA PHP Programming

getdate(timestamp)
The getdate() function returns date/time information of a
timestamp or the current local date/time.

date(format, timestamp)

The date() function formats a local date and time, and returns the
formatted date string.

<?php
// Prints the day
echo date("l") . "<br>";

// Prints the day, date, month, year, time, AM or PM


echo date("l jS \of F Y h:i:s A");
?>

Output
Saturday
Saturday 30th of January 2021 05:11:07 AM

strtotime(time, now);

The strtotime() function parses an English textual datetime into a Unix


timestamp (the number of seconds since January 1 1970 00:00:00 GMT).

Note: If the year is specified in a two-digit format, values between 0-69


are mapped to 2000-2069 and values between 70-100 are mapped to
1970-2000.

Note: Be aware of dates in the m/d/y or d-m-y formats; if the separator


is a slash (/), then the American m/d/y is assumed. If the separator is a
dash (-) or a dot (.), then the European d-m-y format is assumed. To
avoid potential errors, you should YYYY-MM-DD dates or
date_create_from_format() when possible.

<?php
echo(strtotime("now") . "<br>");
echo(strtotime("3 October 2005") . "<br>");
echo(strtotime("+5 hours") . "<br>");
?>

30
Prepared By:- Prof. Paresh Patel ,MCMSR, Visnagar
BCA PHP Programming

date_format(object, format)

The date_format() function returns a date formatted according to the


specified format.

<?php
$date=date_create("2013-03-15");
echo date_format($date,"d/m/Y H:i:s");
?>
Output
15/03/2013 00:00:00

PHP String Functions


PHP string functions are used to manipulate string values.

We are now going to look at some of the commonly used string


functions in PHP

Function Description Example Output


strtolower Used to convert all echo strtolower( outputs benjamin
string characters to 'Benjamin');
lower case letters
strtoupper Used to convert all echo outputs GEORGE W
string characters to strtoupper('george w BUSH
upper case letters bush');
strlen The string length echo strlen('united 24
function is used to states of america');
count the number
of character in a
string. Spaces in
between
characters are also
counted
explode Used to convert $settings = Array ( [0] =>
strings into an explode(';', host=localhost [1] =>
array variable "host=localhost; db=sales [2] =>
db=sales; uid=root; uid=root [3] =>
pwd=demo"); pwd=demo )
print_r($settings);

31
Prepared By:- Prof. Paresh Patel ,MCMSR, Visnagar
BCA PHP Programming

Function Description Example Output


substr Used to return part $my_var = 'This is a This is a re...
of the string. It really long sentence
accepts three (3) that I wish to cut
basic parameters. short';echo
The first one is the substr($my_var,0,
string to be 12).'...';
shortened, the
second parameter
is the position of
the starting point,
and the third
parameter is the
number of
characters to be
returned.
str_replace Used to locate and echo str_replace that laptop is very
replace specified ('the', 'that', 'the expensive
string values in a laptop is very
given string. The expensive');
function accepts
three arguments.
The first argument
is the text to be
replaced, the
second argument
is the replacement
text and the third
argument is the
text that is
analyzed.
strpos Used to locate the echo strpos('PHP 4
and return the Programing','Pro');
position of a
character(s) within
a string. This
function accepts
two arguments
sha1 Used to calculate echo 5baa61e4c 9b93f3f0
the SHA-1 hash of sha1('password'); 682250b6cf8331b

32
Prepared By:- Prof. Paresh Patel ,MCMSR, Visnagar
BCA PHP Programming

Function Description Example Output


a string value 7ee68fd8
md5 Used to calculate echo 9f961034ee 4de758
the md5 hash of a md5('password'); baf4de09ceeb1a75
string value
str_word_count Used to count the echo str_word_count 12
number of words in ('This is a really long
a string. sentence that I wish
to cut short');
ucfirst Make the first echo Outputs Respect
character of a ucfirst('respect');
string value upper
case
lcfirst Make the first echo Outputs rESPECT
character of a lcfirst('RESPECT');
string value lower
case

PHP Arrays
An array is used to store multiple values, generally of same type, in a single
variable.
n such case, PHP arrays are used. Arrays can store multiple values together in
a single variable and we can traverse all the values stored in the array using the
foreach ad other loop statement.

Creating an Array
We can create an array in PHP using the array() function.

Syntax:
<?php
/*
a simple array with car names
*/
$$cars= array("Maruti", "Hundai", "Tata");

?>

33
Prepared By:- Prof. Paresh Patel ,MCMSR, Visnagar
BCA PHP Programming

In PHP there are 3 types of array:

1. Indexed Array: These are arrays with numeric index.


2. Associative Array: These are arrays which have a named key as index,
the key can be numeric or text.
3. Multidimensional Array: These are arrays which contain one or more
arrays.

To access the data stored in an array, we can either use the index numbers or
we can use a foreach loop to traverse the array elements.
<?php
/*
access array element using index
*/
$$cars= array("Maruti", "Hundai", "Tata");

echo $cars[0];
//or

?>

Using foreach statement

<?php
/*
access array element using foreach
*/
$$cars= array("Maruti", "Hundai", "Tata");

foreach($cars as $val)
{
echo $val.”<br>”;
}
//
?>

34
Prepared By:- Prof. Paresh Patel ,MCMSR, Visnagar
BCA PHP Programming

Using for loop statement

<?php

$$cars= array("Maruti", "Hundai", "Tata");


// find size of the array
$size = count($cars);

// using the for loop


for($i = 0; $i < $size; $i++)
{
echo $cars[$i], "\n";
}

?>

PHP Associative Arrays


An associative array is similar to an indexed array, but rather than storing data
sequentially with numeric index, every value can be assigned with a user-
designed key of string type.

Creating an Associative Array


Just like indexed array, there are two different ways of creating an associative
array in PHP, they are,

Syntax for the 1st way to create associative array:

<?php

/*

1st - direct array initialization

*/

$cars = array("suv"=>"maruti", "sports"=>"Hundai",


"hatback"=>"Tata");

?>

35
Prepared By:- Prof. Paresh Patel ,MCMSR, Visnagar
BCA PHP Programming

and the syntax for the 2nd way to create associative array is:

<?php

/*

2nd - distributed array initialization

*/

$cars["hatch"] = "Swift";

$suzuki["utility"] = "Ertiga";

$suzuki["suv"] = "maruti";

?>

36
Prepared By:- Prof. Paresh Patel ,MCMSR, Visnagar

You might also like