0% found this document useful (0 votes)
2 views22 pages

Unit 1

PHP, created by Rasmus Lerdorf in 1994, is a server-side scripting language used for dynamic web content and database management. It is open-source, easy to learn, and supports various databases and protocols, making it suitable for a wide range of applications. PHP has evolved significantly, with a large community contributing to its development and it is widely used across millions of websites globally.

Uploaded by

saniasingh87807
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)
2 views22 pages

Unit 1

PHP, created by Rasmus Lerdorf in 1994, is a server-side scripting language used for dynamic web content and database management. It is open-source, easy to learn, and supports various databases and protocols, making it suitable for a wide range of applications. PHP has evolved significantly, with a large community contributing to its development and it is widely used across millions of websites globally.

Uploaded by

saniasingh87807
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/ 22

What is PHP?

PHP started out as a small open source project that evolved as more and
more people found out how useful it was. Rasmus Lerdorf unleashed the
first version of PHP way back in 1994.

• PHP is a recursive acronym for "PHP: Hypertext Preprocessor".

• PHP is a server side scripting language that is embedded in HTML. It is


used to manage dynamic content, databases, session tracking, even
build entire e-commerce sites.

• It is integrated with a number of popular databases, including MySQL,


PostgreSQL, Oracle, Sybase, Informix, and Microsoft SQL Server.

• PHP is pleasingly zippy in its execution, especially when compiled as an


Apache module on the Unix side. The MySQL server, once started,
executes even very complex queries with huge result sets in record-
setting time.

• PHP supports a large number of major protocols such as POP3, IMAP,


and LDAP. PHP4 added support for Java and distributed object
architectures (COM and CORBA), making n-tier development a
possibility for the first time.

• PHP is forgiving/easy: PHP language tries to be as forgiving/easy as


possible.

• PHP Syntax is like C-language.

History of php
PHP was conceived sometime in the fall of 1994 by Rasmus Lerdorf. Early
non-released versions were used on his home page to keep track of who was
looking at his online resume. The first version used by others was available
sometime in early 1995 and was known as the Personal Home Page Tools. It
consisted of a very simplistic parser engine that only understood a few
special macros and a number of utilities that were in common use on home
pages back then. A guestbook, a counter and some other stuff. The parser
was rewritten in mid-1995 and named PHP/FI Version 2. The FI came from
another package Rasmus had written which interpreted html form data. He
combined the Personal Home Page tools scripts with the Form Interpreter
and added mSQL support and PHP/FI was born. PHP/FI grew at an amazing
pace and people started contributing code to it.

• It is difficult to give any hard statistics, but it is estimated that by late 1996
PHP/FI was in use on at least 15,000 web sites around the world. By mid-
1997 this number had grown to over 50,000. Mid-1997 also saw a change in
the development of PHP. It changed from being Rasmus' own pet project
that a handful of people had contributed to, to being a much more organized
team effort. The parser was rewritten from scratch by Zeev Suraski and
Andi Gutmans and this new parser formed the basis for PHP Version 3. A
lot of the utility code from PHP/FI was ported over to PHP3 and a lot of it
was completely rewritten.
• Today (end-1999) either PHP/FI or PHP3 ships with a number of
commercial products such as C2's StrongHold web server and RedHat
Linux. A conservative estimate based on an extrapolation from numbers
provided by NetCraft (see also Netcraft Web Server Survey) would be that
PHP is in use on over 1,000,000 sites around the world. To put that in
perspective, that is more sites than run Netscape's flagship Enterprise server
on the Internet.

PHP FEATURES
1. Simple and Easy to Learn

• PHP syntax is straightforward and similar to other programming


languages like C, Java, and Perl.
• It’s beginner-friendly, making it a great choice for new developers.
2. Server-Side Execution

• PHP code runs on the server, generating HTML that is sent to the client’s
browser.
• Ideal for creating dynamic web pages.
3. Cross-Platform

• PHP works on various operating systems, including Windows, Linux,


macOS, and more.
• It supports major web servers like Apache, Nginx, IIS, etc.
4. Embedded in HTML
• PHP can be embedded directly within HTML code, making it easy to mix
server-side logic with front-end design.
5. Wide Database Support

• PHP supports various databases, including MySQL, PostgreSQL, SQLite,


and more.
6. Rich Library Support

• PHP has built-in libraries for tasks like sending emails, file handling,
encryption, image processing, and more.
7. Free and Open Source

• PHP is free to use and has an active community contributing to its


development and support.
8. Error Handling

• PHP provides tools like try-catch blocks to handle errors gracefully.


9. Cheaper Development

• PHP applications are much cheaper than other technologies for


developing dynamic sites or applications due to the proprietary or
license issues.
10. Scalability

• Suitable for small projects to large-scale applications like Facebook


(initially built in PHP).

Characteristics of PHP
1. Server-Side Language

• PHP runs on the server and generates dynamic content for websites.
• Example: It can create personalized web pages based on user input.
2. Open Source

• PHP is free to download, use, and modify.


• It has a large community that contributes to its development.
3. Platform Independent

• PHP works on all major operating systems like Windows, Linux, macOS,
etc.
• Code written in PHP can run anywhere, as long as the server supports it.
4. Embedded in HTML

• PHP code can be written alongside HTML, making it easy to combine


programming logic with web design.
5. Supports Many Databases

• PHP can interact with various databases, like MySQL, PostgreSQL,


Oracle, and SQLite.
• Example: You can use PHP to store and retrieve data from a database.
6. Fast Performance

• PHP scripts execute quickly, even on servers with limited resources.


• This helps build responsive and fast-loading websites.
7. Easy to Learn

• PHP syntax is simple and similar to languages like C and Java.


• Beginners can quickly start writing useful scripts.
8. Flexible and Dynamic

• PHP can handle both simple websites and complex applications.


• It adapts to changing requirements easily.
9. Rich Library of Functions

• PHP has many built-in functions to handle common tasks like:


o File uploads.
o Email sending.
o Image manipulation.

PHP - Environment Setup


In order to develop and run PHP Web pages three vital components need
to be installed on your computer system.

• Web Server − PHP will work with virtually all Web Server software,
including Microsoft's Internet Information Server (IIS) but then most
often used is freely available Apache Server. Download Apache for free
here − https://httpd.apache.org/download.cgi

• Database − PHP will work with virtually all database software, including
Oracle and Sybase but most commonly used is freely available MySQL
database. Download MySQL for free here
− https://www.mysql.com/downloads/

• PHP Parser − In order to process PHP script instructions, a parser must


be installed to generate HTML output that can be sent to the Web
Browser.

PHP Parser Installation


Before you proceed, it is important to make sure that you have
proper environment setup on your machine to develop your web
programs using PHP. Store the following php file in Apache's
htdocs folder.

phpinfo.php
<?php
phpinfo();
?>

Apache Configuration for PHP


Apache uses httpd.conf file for global settings, and the .htaccess file for
per-directory access settings. Older versions of Apache split up httpd.conf
into three files (access.conf, httpd.conf, and srm.conf), and some users
still prefer this arrangement.

Apache server has a very powerful, but slightly complex, configuration


system of its own.

The following section describe settings in httpd.conf that affect PHP directly
and cannot be set elsewhere. If you have standard installation then
httpd.conf will be found at /etc/httpd/conf:

PHP.INI File Configuration


The PHP configuration file, php.ini, is the final and most immediate way to
affect PHP's functionality. The php.ini file is read each time PHP is
initialized. in other words, whenever httpd is restarted for the module
version or with each script execution for the CGI version. If your change
isn.t showing up, remember to stop and restart httpd. If it still isn.t
showing up, use phpinfo() to check the path to php.ini.

The configuration file is well commented and thorough. Keys are case
sensitive, keyword values are not; whitespace, and lines beginning with
semicolons are ignored. Booleans can be represented by 1/0, Yes/No,
On/Off, or True/False. The default values in php.ini-dist will result in a
reasonable PHP installation that can be tweaked later.

Here we are explaining the important settings in php.ini which you may
need for your PHP Parser.

short_open_tag = Off
Short open tags look like this: <? ?>. This option must be set to Off if you
want to use XML functions.

safe_mode = Off
If this is set to On, you probably compiled PHP with the --enable-safe-
mode flag. Safe mode is most relevant to CGI use. See the explanation in
the section "CGI compile-time options". earlier in this chapter.
safe_mode_exec_dir = [DIR]
This option is relevant only if safe mode is on; it can also be set with the
--with-exec-dir flag during the Unix build process. PHP in safe mode only
executes external binaries out of this directory. The default is
/usr/local/bin. This has nothing to do with serving up a normal PHP/HTML
Web page.

safe_mode_allowed_env_vars =
[PHP_]
This option sets which environment variables users can change in safe
mode. The default is only those variables prepended with "PHP_". If this
directive is empty, most variables are alterable.

safe_mode_protected_env_vars =
[LD_LIBRARY_PATH]
This option sets which environment variables users can't change in safe
mode, even if safe_mode_allowed_env_vars is set permissively

disable_functions = [function1,
function2...]
A welcome addition to PHP4 configuration and one perpetuated in PHP5 is
the ability to disable selected functions for security reasons. Previously,
this necessitated hand-editing the C code from which PHP was made.
Filesystem, system, and network functions should probably be the first to
go because allowing the capability to write files and alter the system over
HTTP is never such a safe idea.

max_execution_time = 30
The function set_time_limit() won.t work in safe mode, so this is the main
way to make a script time out in safe mode. In Windows, you have to abort
based on maximum memory consumed rather than time. You can also use
the Apache timeout setting to timeout if you use Apache, but that will apply
to non-PHP files on the site too.
error_reporting = E_ALL &
~E_NOTICE
The default value is E_ALL & ~E_NOTICE, all errors except notices.
Development servers should be set to at least the default; only production
servers should even consider a lesser value

error_prepend_string = [""]
With its bookend, error_append_string, this setting allows you to make error
messages a different color than other text, or what have you.

warn_plus_overloading = Off
This setting issues a warning if the + operator is used with strings, as in a
form value.

variables_order = EGPCS
This configuration setting supersedes gpc_order. Both are now deprecated
along with register_globals. It sets the order of the different variables:
Environment, GET, POST, COOKIE, and SERVER (aka Built-in).You can change
this order around. Variables will be overwritten successively in left-to-right
order, with the rightmost one winning the hand every time. This means if you
left the default setting and happened to use the same name for an
environment variable, a POST variable, and a COOKIE variable, the COOKIE
variable would own that name at the end of the process. In real life, this
doesn't happen much.

register_globals = Off
This setting allows you to decide whether you wish to register EGPCS variables
as global. This is now deprecated, and as of PHP4.2, this flag is set to Off by
default. Use superglobal arrays instead. All the major code listings in this book
use superglobal arrays.

gpc_order = GPC
This setting has been GPC Deprecated.
magic_quotes_gpc = On
This setting escapes quotes in incoming GET/POST/COOKIE data. If you use
a lot of forms which possibly submit to themselves or other forms and display
form values, you may need to set this directive to On or prepare to use
addslashes() on string-type data.

magic_quotes_runtime = Off
This setting escapes quotes in incoming database and text strings. Remember
that SQL adds slashes to single quotes and apostrophes when storing strings
and does not strip them off when returning them. If this setting is Off, you
will need to use stripslashes() when outputting any type of string data from a
SQL database. If magic_quotes_sybase is set to On, this must be Off.

magic_quotes_sybase = Off
This setting escapes single quotes in incoming database and text strings with
Sybase-style single quotes rather than backslashes. If magic_quotes_runtime
is set to On, this must be Off.

auto-prepend-file = [path/to/file]
If a path is specified here, PHP must automatically include() it at the beginning
of every PHP file. Include path restrictions do apply.

auto-append-file = [path/to/file]
If a path is specified here, PHP must automatically include() it at the end of
every PHP file.unless you escape by using the exit() function. Include path
restrictions do apply.

include_path = [DIR]
If you set this value, you will only be allowed to include or require files from
these directories. The include directory is generally under your document
root; this is mandatory if you.re running in safe mode. Set this to . in order
to include files from the same directory your script is in. Multiple directories
are separated by colons: .:/usr/local/apache/htdocs:/usr/local/lib.

doc_root = [DIR]
If you.re using Apache, you.ve already set a document root for this server or
virtual host in httpd.conf. Set this value here if you.re using safe mode or if
you want to enable PHP only on a portion of your site (for example, only in
one subdirectory of your Web root).

file_uploads = [on/off]
Turn on this flag if you will upload files using PHP script.

upload_tmp_dir = [DIR]
Do not uncomment this line unless you understand the implications of HTTP
uploads!

session.save-handler = files
Except in rare circumstances, you will not want to change this setting. So
don't touch it.

ignore_user_abort = [On/Off]
This setting controls what happens if a site visitor clicks the browser.s Stop
button. The default is On, which means that the script continues to run to
completion or timeout. If the setting is changed to Off, the script will abort.
This setting only works in module mode, not CGI.

mysql.default_host = hostname
The default server host to use when connecting to the database server if no
other host is specified.

mysql.default_user = username
The default user name to use when connecting to the database server if no
other name is specified.

mysql.default_password = password
The default password to use when connecting to the database server if no
other password is specified.

Windows IIS Configuration


The fastest and easiest way to install PHP on Internet Information Services

(IIS) is by using the Microsoft® Web Platform Installer (Web PI). Web PI

completely automates setting up IIS, FastCGI, and the latest version of PHP

from the php.net Web site. With Web PI, you can navigate to the "Web
Platform" tab and select "PHP" under "Framework and Runtimes" customize

link. Alternately, use the instructions that follow as guidance for installing PHP

with Windows® Installer or using a compressed (Zip) file installation.

Open the Php.ini file in a text editor, then uncomment and modify settings as
follows:

• Set fastcgi.impersonate = 1.
FastCGI under IIS supports the ability to impersonate
security tokens of the calling client. This allows IIS to define
the security context that the request runs under.
• Set cgi.fix_pathinfo = 0
The cgi.fix_pathinfo provides PATH_INFO/PATH_TRANS
LATED support for Common Gateway Interface (CGI).
Setting this to 1 will cause PHP CGI to fix its paths to
conform to the specification.
• Set cgi.force_redirect = 0.
• Set open_basedir to point to a folder or network path
where the content of the Web site(s) is located.
• Set extension_dir to point to a location where PHP
extensions reside. For PHP 5.2.X, this is
typically extension_dir = "./ext".
• Set error_log="C:php_errors.log"
This can help with troubleshooting.

Understanding of PHP .htaccess file


.htaccess is short for Hypertext Access, and is a configuration file used by
Apache-based web servers that controls the directory that it "lives" in--as well
as all the subdirectories underneath that directory. Also helps to create
Custom Error Pages for Better SEO.
PHP Variable
The main way to store information in the middle of a PHP program is by
using a variable.

Here are the most important things to know about variables in PHP.

• All variables in PHP are denoted with a leading dollar sign ($).

• The value of a variable is the value of its most recent assignment.

• Variables are assigned with the = operator, with the variable on the left-
hand side and the expression to be evaluated on the right.

• Variables can, but do not need, to be declared before assignment.

• Variables in PHP do not have built-in types - a variable does not know
in advance whether it will be used to store a number or a string of
characters.

• Variables used before they are assigned have default values.

• PHP does a good job of automatically converting types from one to


another when necessary.

• PHP variables are Perl-like.

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 and Local Scope

A variable declared outside a function has a GLOBAL SCOPE and can


only be accessed outside a function:

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


?>

A variable declared within a function has a LOCAL SCOPE and can


only be accessed within that function:
Example:-

<?php
function myTest()

{
$x=5; //localscope
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>";
?>
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):

<?php
$x = 5;
$y = 10;
function myTest() {
global $x, $y;
$y = $x + $y;
}

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

static variables in a PHP


There may be times when a static variable is needed in a PHP function; static
variables maintain their value between function calls and are tidier than using a
global variable because they cannot be modified outside of the function. (If the
function is contained within a class, you may be better using a private or
protected class variable instead of a static variable inside the function).

PHP code example

The PHP code example below shows a function which uses a static variable.
When the function is first called it won't have a value set so it's initialized with
the = 0 bit and then incremented on each subsequent call. Note that it doesn't
need to be an integer; any type should work just fine.

The echo $index line is to show the example working.

function foo() {
static $index = 0;
$index++;
echo "$index\n";
}

Calling foo() multiple times like so:

foo();
foo();
foo();

would echo this:

1
2
3

Variable Naming
Rules for naming a variable is −

• Variable names must begin with a letter or underscore character.

• A variable name can consist of numbers, letters, underscores but you


cannot use characters like + , - , % , ( , ) . & , etc

There is no size limit for variables.

PHP var_dump() Function


The var_dump() function dumps information about one or more variables.
The information holds type and value of the variable(s).

Syntax

var_dump(var1, var2, ...);

Parameter Description

var1, var2, ... Required. Specifies the variable(s) to dump information


from

<?php

//PHP program to demonstrate the working of var_dump function

$x = 25;

//dump integer variable

var_dump ($x);

echo "</br>";
$y = 32.5;

//dump float variable

var_dump ($y);

echo "</br>";

$bvalue = true;

//dump boolean variable

var_dump ($bvalue);

?>

PHP - GET & POST Methods


There are two ways the browser client can send information to the web
server.

• The GET Method

• The POST Method

Before the browser sends the information, it encodes it using a scheme


called URL encoding. In this scheme, name/value pairs are joined with
equal signs and different pairs are separated by the ampersand.
name1=value1&name2=value2&name3=value3

Spaces are removed and replaced with the + character and any other non-
alphanumeric characters are replaced with a hexadecimal values. After the
information is encoded it is sent to the server.

The GET Method


The GET method sends the encoded user information appended to the
page request. The page and the encoded information are separated by
the ?character.
http://www.test.com/index.htm?name1=value1&name2=value2

• The GET method produces a long string that appears in your server logs,
in the browser's Location: box.

• The GET method is restricted to send upto 1024 characters only.

• Never use GET method if you have password or other sensitive


information to be sent to the server.

• GET can't be used to send binary data, like images or word documents,
to the server.

• The data sent by GET method can be accessed using QUERY_STRING


environment variable.

• The PHP provides $_GET associative array to access all the sent
information using GET method.

The POST Method


The POST method transfers information via HTTP headers. The information
is encoded as described in case of GET method and put into a header called
QUERY_STRING.

• The POST method does not have any restriction on data size to be sent.

• The POST method can be used to send ASCII as well as binary data.

• The data sent by POST method goes through HTTP header so security
depends on HTTP protocol. By using Secure HTTP you can make sure
that your information is secure.

• The PHP provides $_POST associative array to access all the sent
information using POST method.

PHP – Operator
What is Operator?

Simple answer can be given using expression 4 + 5 is equal to 9. Here 4


and 5 are called operands and + is called operator. PHP language supports
following type of operators.

• Arithmetic Operators
• Comparison Operators

• Logical (or Relational) Operators

• Assignment Operators

• Conditional (or ternary) Operators

Lets have a look on all operators one by one.

Arithmetic Operators
There are following arithmetic operators supported by PHP language −

Assume variable A holds 10 and variable B holds 20 then –


Operator Description E0xample

+ Adds two operands A + B will give 30


A - B will give 10
- subtracts two
operands
A * B will give 200
* Multiply two
operands
B / A will give 2
/ Divide two
operands
A / B will give 0(zero)
% Return reminder
A++ will give 11
++ Increments
operand
A—will give 9
-- Decrements
Operand

Comparison Operators
There are following comparison operators supported by PHP language

Assume variable A holds 10 and variable B holds 20 then

Operator Description Example


== Checks if the value of two operands are (A == B) is not true.
equal or not, if yes then condition
becomes true.

!= Checks if the value of two operands are (A != B) is true.


equal or not, if values are not equal then
condition becomes true.

> Checks if the value of left operand is (A > B) is not true.


greater than the value of right operand,
if yes then condition becomes true.

< Checks if the value of left operand is (A < B) is true.


less than the value of right operand, if
yes then condition becomes true.

>= Checks if the value of left operand is (A >= B) is not true.


greater than or equal to the value of
right operand, if yes then condition
becomes true.

<= Checks if the value of left operand is (A <= B) is true.


less than or equal to the value of right
operand, if yes then condition becomes
true.

Logical Operators
There are following logical operators supported by PHP language

Assume variable A holds 10 and variable B holds 20 then

Operator Description Example

and Called Logical AND operator. If both the (A and B) is true.


operands are true then condition becomes
true.
or Called Logical OR Operator. If any of the two (A or B) is true.
operands are non zero then condition becomes
true.

&& Called Logical AND operator. If both the (A && B) is true.


operands are non zero then condition becomes
true.

|| Called Logical OR Operator. If any of the two (A || B) is true.


operands are non zero then condition becomes
true.

! Called Logical NOT Operator. Use to reverses !(A && B) is false.


the logical state of its operand. If a condition
is true then Logical NOT operator will make
false.

Assignment Operators
There are following assignment operators supported by PHP language

Operator Description Example

= Simple assignment operator, Assigns C = A + B will assign


values from right side operands to left value of A + B into C
side operand

+= Add AND assignment operator, It adds C += A is equivalent to C


right operand to the left operand and =C+A
assign the result to left operand

-= Subtract AND assignment operator, It C -= A is equivalent to C


subtracts right operand from the left =C-A
operand and assign the result to left
operand

*= Multiply AND assignment operator, It C *= A is equivalent to C


multiplies right operand with the left =C*A
operand and assign the result to left
operand

/= Divide AND assignment operator, It C /= A is equivalent to C


divides left operand with the right =C/A
operand and assign the result to left
operand

%= Modulus AND assignment operator, It C %= A is equivalent to C


takes modulus using two operands and =C%A
assign the result to left operand

Comments in PHP
A comment in PHP code is a line that is not executed as a part of the
program. Its only purpose is to be read by someone who is looking at the
code.

Comments can be used to:

• Let others understand your code


• Remind yourself of what you did - Most programmers have
experienced coming back to their own work a year or two later and
having to re-figure out what they did. Comments can remind you of
what you were thinking when you wrote the code
• Leave out some parts of your code

PHP supports several ways of commenting:

Example

Syntax for comments in PHP code:


// This is a single-line comment

# This is also a single-line comment

/* This is a

multi-line comment */

• PHP Data Types : https://www.javatpoint.com/php-data-types

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy