You are on page 1of 58

OSP- Open Source Programming

Aim: To create software applications that can be accessed by all the


people over the internet and allow the users to customize the
software based on their requirements.

Objective: On completion of this course you will be able to create


opensource software applications and can publish it over the
internet.

Introduction to OpenSource Programming:

What is Opensource?

In general it is a development model, in which

- A source is shared
- A source is modified
- -a source is redistributed after performing some modifications
- A source is allowed to be modified by anyone

What is OSP?

It is a standard (or) a style of programming based upon opensource


development model.

What is an OSS( Open source software)

- It is the source code along with its compiled version- is


available to the general public without any restriction and
- Also anyone can modify / update the software, that modified
software can also be distributed as opensource.
-It allows free re-distribution of the s/w without royalties (or)
licensing fee to the author
-It requires that source code be distributed with the s/w
-It allows anyone to modify the s/w or derive other s/w from it.
and redistribute the modified s/w under the same terms.
OSI (open source initiative) is a non-profit corporation formed
to educate about the benefits of open source community.
-www.opensource.org
----------------------------------------------------------------------
- Opensource S/w Tools
Linux S/w:
1. Java development kit
2. Easy eclipse for PHP, PERL, Python
3. LAMP server- Linux, Apache, MYSQL,PHP
Windows s/w:
1.JDK
2. Easy eclipse for PHP, perl, python
3. WAMP server- Windows, Apache, MYSQL,PHP

Programming Languages:
PHP
Python
PERL
TCL/TK
Ruby
Zope

Opensource Databases
1. MYSQL- very popular RDBMS (http://www.mysql.com)
2. Postgresql- A popular opensource RDBMS with many
advanced feature(http://www.postgresql.org)
Opensource Webservers
Apache HTTP server for unix and Windows.
PHP compatible with 3 leading webservers Microsoft Internet
Information server and (MIIS)
Netscape Enterprise Server (NES)
ISAPI( Internet server application programming Interface)
Desktop Application:
Open office- An integrated office suite featuring,
wordprocessing, spreadsheet, drawing and presentation
software largely compatable with ms office
(http://www.openoffice.org)
Ximion Evolution: A GUI desktop application for personal email,
calendar and diary having similar look feel with Microsoft
outlook. (http://www.ximion.org)
Mozila- The opensource evolution of the popular netscape web
browser (http://www.mozila.org)
Software Development
GCC (GNU compiler collection/GNU c compiler)- the compiler
for c, c++,fortran, java that comes standard with all the major
OSS operating systems.
( http://gcc.gnu.org)
JBOSS- A popular opensource implementation of J2EE
(http://www.jboss.org)
PERL- A very popular language widely used in scripts to drive
‘live content’ on the www (http://www.perl.org)
PHP- a very popular scripting language for interactive web
development and applications (http://www.php.net)
Python- a popular object oriented scripting language for web
and desktop development (http://www.python.org)
Most of the opensource softwares are released under
GPL(General public License)
Totally 70 opensource licenses are available in OSI website
(http://opensource.org/licenses/alphabetical)
Some of the licenses are,
Academic free license
Adaptive public license
Apache software license
Apple public source license
Boost software license (BSL)
Common public attribution license(CPAL)
IBM public license
MIT license
WWW license
Internet/Intranet services and Applications:
Apache web server- Accounts for over 70% of the webservers
on the internet
BIND name server- Berkeley internet name domain- The
software that provides the DNS (domain name service)
Sendmail (Exchange server)- The most widely used email
transport software on the internet.
Tomcat
JOOMLA
Drupal
Media wiki
IIS
ISAPI
NES
- Opensource S/w operating systems
- Linux
- GNU project
- OPEN BSD
- Free BSD
- Open solaris (unix os from sun microsystems)
OS software sites:
www.fsf.org (free software foundation)
freshmeat.net
sourceforge.net
OSDir.com
Developner.berlieos.de
Individual project sites:
www.apache.org
www.cpan.org
Open source LMS
Moodle
Atutor
Dokeos
OLAT
Mambo

Basics of Web Development:

Developing a website for the Internet(WWW) or an Intranet( private


network)

Client side- static web pages (HTML)

Enables interaction within a web page.

Where scripts are run by the viewing browser, usually in VB script,


java script, HTML & CSS (XML, SGML)

- Services are secure because as no information is sent from the


browser

Serverside- Dynamic web pages (ASP, PHP, JSP…..)


-Completing an activity involves sending information to another
computer( server) across the internet.

- is a webserver technology in which a user’s request is fulfilled by


running a script directly on the web server to generate dynamic web
pages.

- From security point of view, SSS’s are never visible to the browser
as these scripts are executes on the server and emit HTML
corresponding to users input to the page.

-usually used to provide interactive websites that interface to


databases or other data stores.

Primary advantage: the ability to highly customize the response


based on the user’s requirement, access rights or queries into data
stores.

Websphere (IBM proprietary)

ASP (Active server pages) (.asp)

CSP ( ANSI C scripts) (.csp)

Cold fusion markup languages – CFML(.cfm)

Java via Java server pages(.jsp)

Hypertext preprocessor –PHP (.php)

CGI/ PERL –Common Gateway Interface/Practical Extraction and


reporting Language- (.pl)

Python (.py)

---------------------------------------------------------------------
History of Open Source

1970- Unix operating system developed at bell labs and by a diverse


group of contributors outside of bell labs.

Labs AT&T enforces intellectual property rights and closes the code.

1983-Richard tall man founds the fsf (free s/w foundation)

1993- Linus tarvalds releases first version of linux built.

1997- Debian free s/w guidelines released

1998- - netscape releases navigator in source.

These groups were establishing the roots of current oss movement.

Opensource Companies

IBM- uses and develops apache and linux. Created secure mailer and
other s/w on alphaworks

Apple- released core layers of MACOS X server… as an opensource


BSD operating system called DARWIN.

HP- Uses and releases producs running liux

Sun- uses linux

RedHat software- Linux vendor

Active state- develops and sells professional tools for perl, python
and TCL &TK developers.

Merits of Opensource

-They are free (b’coz the greatest thing about OSS is that its free and
available to the general public)

-They are cross- platform and technology neutral.


-Opens source programs must not be dependent on any “individual
technology/style of interface” and must be technology neutral.

(http://opensource.org)

-They must not restrict other software ( this gives s/w developers
maximum control and flexibility)

-They embrace diversity ( a program designed for use in the medical


profession cannot be limited to that field, if someone in another field
wants to take the program and modify it to fit his/her needs)
Introduction to standard in general

A set of criteria (some of which may be mandatory)

Voluntary guidelines and best practices.

Example include, application development, project management, vendor


management, production operation, user support, asset management,
technology evaluation, architecture governance, configuration management,
problem resolution.

Who creates standards?

Officially recognized standard organization.

ISO, ANSI, NEMA, NIST,ITU……

Industry consortia,

IETF, IEEE,W3C, OASIS, Blu-ray disc association

Entities (people, companies or s/w projects)- may publish a specification that is


open and free to use. This is called openstandard.

Companies may license a specification and charge royalties (hefty license fee)
for its use.

This is called a closed standard.

Open Standards
Are software specification which are no-proprietory.

Availability

Maximize end-user choice

Excellence through competition

No Royalty

No Discrimination

What makes a standard “open”?

Available- anyone is allowed to read and implement the standard

No Royalties- free to implement without paying hefty licensing fees or


royalties.

Not controlled by a single vendor

Copy Right and Copy Left Licenses

Software copyright is commonly used by proprietory software companies to


prevent the unauthorized copying of their s/w.

A copy left is a type of copyright license that allows redistributing the work
(with or without changes) on condition that recipients are also granted these
rights.

Copyleft gives the legal right to everyone to used, edit and redistribute
programs or programs’s code.

PHP- Introduction

PHP- was created by Rasmus Lerdorf in 1994.

Stands for Hypertext preprocessor.

Personal homepage

Professional homepage

PHP is an acronym for "PHP: Hypertext Preprocessor"


PHP is a widely-used, open source scripting language

PHP scripts are executed on the server

PHP is free to download and use

PHP is an amazing and popular language!

It is powerful enough to be at the core of the biggest blogging system on the


web (WordPress)!

It is deep enough to run large social networks!

It is also easy enough to be a beginner's first server side language! (like ASP
and JSP)

It is a powerful dynamic language, and used to provide interactive websites.

What is a PHP File?

PHP files can contain text, HTML tags, CSS, JavaScript, and PHP code

PHP code is executed on the server, and the result is returned to the browser
as plain HTML

PHP files have extension ".php"

Why PHP?

Anyone can visit the php website and to download from the official resource:
www.php.net (PHP is free)

It’s opensource, full featured, clearly designed and cross platform (runs on
different platforms)

PHP is compatible with almost all servers used today(apache, IIS,ISAPI,NES)

It supports many protocols such as HTTP, POP,SMTP,IMAP

PHP is easy to learn and runs efficiently on the server side.

What Can PHP Do?


PHP supports many databases (MYSQL, Postgresql,Oracle, Sybase,SQL,etc..)

PHP can generate dynamic page content

PHP can create, open, read, write, delete, and close files on the server

PHP can collect form data

PHP can send and receive cookies

PHP can add, delete, modify data in your database

PHP can be used to control user-access

PHP can encrypt data

With PHP you are not limited to output HTML. You can output images, PDF
files, and even Flash movies. You can also output any text, such as XHTML and
XML.

Why PHP?

PHP runs on various platforms (Windows, Linux, Unix, Mac OS X, etc.)

PHP is compatible with almost all servers used today (Apache, IIS, etc.)

PHP supports a wide range of databases

PHP is free. Download it from the official PHP resource: www.php.net

PHP is easy to learn and runs efficiently on the server side

What's new in PHP 7

PHP 7 is much faster than the previous popular stable release (PHP 5.6)

PHP 7 has improved Error Handling

PHP 7 supports stricter Type Declarations for function arguments

PHP 7 supports new operators (like the spaceship operator: <=>)

BASICS of PHP
PHP Tags:

4 different style of PHP tags

1. standard tag: <?php echo ”order processed” ; ?>

2. short tag: <? ?>

3. Script tag: <script language=’php’> echo “hai”; </script>

4. ASP tag: <% echo “program excuted!”; %>

Configuration- php.ini file

Short_open_tag=on; or enabled;

Asp_tags=enabled;

Php.ini Basics

Testing your installation:

phpinfo() –This function will produce a long list of configuration information.

1. open a text editor and type the following code

2. <?php phpinfo(); ?>

3. Save this file as phpinfo.php and place it in the document root of your
webserver.

D:// Appserv-> wwwroot->PROGRAM (folder)->phpinfo.php

4. Access this file via your web browser and you should see something like…

phpinfo(): large amount of information about current state of php

PHP compilation options and extensions

Php version

Server information and environment

OS version information

Paths
Master and local values of configuration option

HTTP headers

Php license

PHP info() options:

<?php phpinfo(INFO_MODULES); ?>

<?php phpinfo(INFO_VARIABLES); ?>

<?php phpinfo(INFO_LICENCES); ?>

GENERAL –php.ini location, builddate

CREDITS- authors, website team, quality assurance team

ENVIRONMENT- environment variables

CONFIGURATION- php directives

ALL- shows all the above

PHP with HTML

HTML can also be written inside the php section of your web page

PHP can also be written as a standalone program with no html.

Embedding php in html

<html>

<head>

<title> CYBER SHOPPE </title>

<head>

<h1> Barbie doll</h1>

<h2> Order results</h2>


<?php

echo “<p>order processed </p>” ;

?>

</body>

</html>

Comments in php

// This is single line comment

/* This

Is

Multiline

Comment */

# start comment print

Variables in php

- Variables are used for storing values


- -all variables in php start with a $ symbol

<?php

$text= “ Sumangali”;

echo $text;

?>

To concatenate 2 or more variables together using single period.

<?php

$text= “ Sumangali”;

$text1= “ Associateprofessor”;
echo $text.$text1; // SumangaliAssociateprofessor

echo $text. “ “.$text1; // Sumangali Associateprofessor

?>

$varname=value;

Start with a letter or an underscore

Should not contain spaces

Should not start with a digit

Not use any keywords

$my_string

$myString

PHP is a loosely typed language

In php a variable doesn’t need to be declared before being set. PHP


automatically converts the variable to the correct type depending how they
are set.

But, in a strongly typed language you have to declare the type of variable.

Dynamic variable: A variable name which can be set and used


dynamically.

<?php
$a=”hello”;
?>
<?php
$test=”helloworld”;
$a=”test”; //$a represents variable
echo $$a; // $$a represent a variable with the content of $a
?> o/p: helloworld
Datatypes:

Standard 8 datatypes available in php


1. Boolean- T or F (any number other than 0 becomes true)
2. Integer- Whole number without decimal point (41)
3. Float or double- A floating point number (49.0)
4. String- A collection of characters
5. Object- An instances of a programmer defined classes
6. Arrays- A ordered set of keys and values, It can store multiple values
of same datatypes.
7. Resource- References to a 3’rd party resource (Eg. Database)
8. Null- An uninitialized variable.

gettype()- testing the type of a variable


gettype ($variablename);

$t=”five”;
echo gettype ($t); //string
echo “<br>”;
$t=true;
echo gettype ($t);//boolean
echo “<br>”;
$t=array(‘apple’, ‘peach’, ‘banana’,9,9.0);
echo gettype ($t);//array

settype()- changing the type of a variable


settype($variabletochange, ‘newtype’)

<?php

$undecided=3.14;

echo gettype($undecided);//float or double

echo “is $undecided<br>”;//is 3.14

settype($undecided, ‘integer’);
echo gettype($undecided);//integer

echo “is $undecided<br>”;//3

settype($undecided, ‘bool’);

echo gettype($undecided);//boolean

echo “is $undecided<br>”;//1

?>

Changing Typebycasting: produces a copy leaving the original variable


untouched. (note: but to change the type of the existing variable we may use
settype() function)

Eg: $newvar=(datatype)$originalvariable;

<?php

$undecided=3.14;

$holder=(integer)$undecided;

echo gettype($holder);// integer

echo “is $holder <br>”;// 3

echo “original variabletype”;

echo gettype( $undecided);// double

?>

Vardump()- produces the key associated values of the given variable


information. Structured information or dumps information about variable.

<?php

$a=”opensource”;

print_r(vardump($a);

?>
Type=>string

Value=>opensource

Noofcharacters=>10

Size=>

<?php

$b=3.1;

$c=true;

Var_dump($b,$c);

?>

o/p:

Float(3.1)

Bool(true)

Quotes “ Vs ‘

“- double quoted string any variable names are expanded to their values.

‘- single quoted string no variable expansion takes place.

$name=”sona”;

$age=23;

echo ‘$name is $age’; //$name is $age

echo “$name is $age”;// sona is 23

echo ‘string \’s apostraphe’; //string’s apostrophe


echo ‘string with a php variable’. $name;//string with a php variable sona

output method: echo and print() is the common method in outputting the
data. echo doesn’t contain parenthesis, since it is a language construct.

echo “hello”; echo $hits;

print (“hello”); print($hits)

Constants in php: A constant is an identifier(name) for a simple value.

-that value cannot change during the execution of the program

-by default constant is case-sensitive.

-constant identifier are always upper case.

define(“YOUR_CONSTANTNAME”, 40);

define function says whether the constant exists or not.

define(“FOO_BAR”, “something”);

<?php

define(“CONSTANT”, “helloworld”);

$x=10;

echo CONSTANT; // helloworld

echo constant;// prints constant and issue a notice

echo $x; //10


How PHP is PARSED?

You have a file, and in that file you have some HTML and some PHP code.
Assuming a php document with an entension of .php.

1. the web browser requests a document with a .php extension

2. The web server says “hey! Some one wants a php file, which means this is a
file that needs to be parsed, and sends the request on to the PHP parser.

3. The PHP parser finds the requested file and scans it for PHP code

4. when the PHP parser finds PHP code it executes that code and places the
resulting output (if any) into the place in the file formerly occupied by the
code

5. This new output file is sent back to the web server

6. The webserver sends it along to the web browser


7. the web browser displays the output.

Operators and Expressions:

An operator is a symbol or series of symbol , when used in


conjunction with values, performs an action and usually produces a
new value.

An operand is a value in conjunction with an operator. There are


usually 2 or more operands to one operator.

4+5=9.
Expression: Combination of operator and operand that can be used
to produce a new value.

Commonly used operators in PHP:

Assignment : =

$n=”james”;

$num=9;

Arithmetic: +,-,*, /, % 10%3=1

Concatenation: (dot) Treating both operands as strings. Single period

“hello”.”web” // helloweb

Combined assignment : += -= *= /=

$x+=5 is equalent to $x=$x+5

$x=4

$x+=4//8

$x+=4//12

$x-=3//9

Automatically incrementing and decrementing:

++ -- (incremented and decremented by 1)

$x=3;

++$x<4;// 4<4// false

$x=3;

$y=$x++ +3 //6

Comparison :
Takes two operands and returns a Boolean value

<, >, <=, >=, ==, !=, ===, !== ,<> -notequal

$x=4

$x==5 //false

<?php

$x=300;

$y=”300”;

if($x== and != or <>$y)

echo “true”;

else

echo “false”;

?> o/p: true (both values are similar but dissimilar datatype, this
== not consider about the datatype)

<?php

$x=300;

$y=”300”;

if($x===$y)

echo “true”;

else

echo “false”;

?> o/p: false (both values are similar but dissimilar datatype)

$x=”300”;
$y=”300”; //true, both values and datatypes are similar.

Ternary operator: It takes 3 operands: condition, result for true


and result for false.

(condition)?True:False;

<?php

$x=18;

$age=($x<16)?'Eligible':'noteligible';

echo $age; //noteligible (18<16=false)

?>

Logical operator:

Take 2 relational expressions and returns a Boolean value.

&& and -both left and right is true then true 1 1 1

|| or – either left and right is true then true 1 0 1

! not

$a=2; //integer

$b=’2’; //php string

Var_dump($a==$b); //bool (true)

Var_dump($a<>$b); // bool (false)

Var_dump($a===$b); // bool (false)

Var_dump($a!==$b); // bool (true)

PHP date() Function :


date() function returns information according to your local time zone.

Definition and Usage: The date() function formats a local time/date.

Syntax: date(format,timestamp)

Parameter Description

format Required. Specifies how to return the result:

 d - The day of the month (from 01 to 31)


 D - A textual representation of a day (three letters)
 j - The day of the month without leading zeros (1 to 31)
 l (lowercase 'L') - A full textual representation of a day
 N - The ISO-8601 numeric representation of a day (1 for Monday
through 7 for Sunday)
 S - The English ordinal suffix for the day of the month (2 characters
st, nd, rd or th. Works well with j)
 w - A numeric representation of the day (0 for Sunday through 6 for
Saturday)
 z - The day of the year (from 0 through 365)
 W - The ISO-8601 week number of year (weeks starting on Monday)
 F - A full textual representation of a month (January through
December)
 m - A numeric representation of a month (from 01 to 12)
 M - A short textual representation of a month (three letters)
 n - A numeric representation of a month, without leading zeros (1 to
12)
 t - The number of days in the given month
 L - Whether it's a leap year (1 if it is a leap year, 0 otherwise)
 o - The ISO-8601 year number
 Y - A four digit representation of a year
 y - A two digit representation of a year
 a - Lowercase am or pm
 A - Uppercase AM or PM
 B - Swatch Internet time (000 to 999)
 g - 12-hour format of an hour (1 to 12)
 G - 24-hour format of an hour (0 to 23)
 h - 12-hour format of an hour (01 to 12)
 H - 24-hour format of an hour (00 to 23)
 i - Minutes with leading zeros (00 to 59)
 s - Seconds, with leading zeros (00 to 59)
 e - The timezone identifier (Examples: UTC, Atlantic/Azores)
 I (capital i) - Whether the date is in daylights savings time (1 if
Daylight Savings Time, 0 otherwise)
 O - Difference to Greenwich time (GMT) in hours (Example: +0100)
 T - Timezone setting of the PHP machine (Examples: EST, MDT)
 Z - Timezone offset in seconds. The offset west of UTC is negative,
and the offset east of UTC is positive (-43200 to 43200)
 c - The ISO-8601 date (e.g. 2004-02-12T15:19:21+00:00)
 r - The RFC 2822 formatted date (e.g. Thu, 21 Dec 2000 16:01:07
+0200)
 U - The seconds since the Unix Epoch (January 1 1970 00:00:00
GMT)

timestamp Optional.

The getdate() function returns an array that contains date and time information for a Unix
timestamp.

The returning array contains ten elements with relevant information needed when formatting a
date string:

 [seconds] - seconds
 [minutes] - minutes
 [hours] - hours
 [mday] - day of the month
 [wday] - day of the week
 [year] - year
 [yday] - day of the year
 [weekday] - name of the weekday
 [month] - name of the month

<?php

print_r(getdate()); //print_r is the human readable format which represents


key as well as value pairs.

?>

The output of the code above could be:

Array

[seconds] => 45

[minutes] => 52

[hours] => 14

[mday] => 24

[wday] => 2

[mon] => 1
[year] => 2006

[yday] => 23

[weekday] => Tuesday

[month] => January

[0] => 1138110765

<?php
echo("Result with date():<br />");
echo(date("l") . "<br />");
echo(date("l dS \of F Y h:i:s A") . "<br />");
echo("Oct 3,1975 was on a ".date("l", mktime(0,0,0,10,3,1975))."<br />");
echo(date(DATE_RFC822) . "<br />");
echo(date(DATE_ATOM,mktime(0,0,0,10,3,1975)) . "<br /><br />");

echo("Result with gmdate():<br />");


echo(gmdate("l") . "<br />");
echo(gmdate("l dS \of F Y h:i:s A") . "<br />");
echo("Oct 3,1975 was on a ".gmdate("l", mktime(0,0,0,10,3,1975))."<br />");
echo(gmdate(DATE_RFC822) . "<br />");
echo(gmdate(DATE_ATOM,mktime(0,0,0,10,3,1975)) . "<br />");
?>

Result with date():


Tuesday
Tuesday 24th of January 2006 02:41:22 PM
Oct 3,1975 was on a Friday
Tue, 24 Jan 2006 14:41:22 CET
1975-10-03T00:00:00+0100

Result with gmdate():


Tuesday
Tuesday 24th of January 2006 01:41:22 PM
Oct 3,1975 was on a Thursday
Tue, 24 Jan 2006 13:41:22 GMT
1975-10-02T23:00:00+0000
<?php

echo “Today is”. “<br>”;

echo date(“j S F Y g i a”);

echo date(“l j S \of F Y h:i:s A”);

echo date(“D”);

echo date(“l”);

?>

Today is

25th January 2022 8 25 am

Tuesday 25th January of 2022 08:27:08 AM

Tue

Tuesday

http://www.php.net/date

Control statements:

Allow you to execute blocks of code depending on conditions.

Used to perform different actions for different decisions.

2 types:

Switching flow- Evaluate conditions and change their behavior


accordingly
Looping statements- to achieve repetitive tasks, until a condition is
achieved, you may explicitly choose to exit the loop.

Switching flow:

If – evaluate an expression between the parentheses

If-else- execute set of code when condition is true and not true

Alternative : ternary operator

Nested if –more than one condition with multiple decisions

Switch- used to avoid long blocks of is, if-else or elseif… coe

<?php

$d=date(“D”);

if($d==”Fri”)

echo “have a nice weekend”;

else

echo “have a nice day”;

?>

O/p- have a nice day

$d=date(“D”);

if($d==”Mon”)

echo “have a nice week ahead”;


echo “ niceday”;

?>

elseif- one of several condition are true.

If(cond)

//truecode

elseif(cond)

// this also true

else

// false or others
<?php

$mood=”sad”;

if($mood==”happy”)

echo “ya, Im in good mood”;

elseif($mood==”sad”)

echo “Aww, don’t be down”; //op

else

echo “neither happy nor sad”;

?>

Switch: used to avoid long blocks of if, if-else, elseif code

switch(exp)

case label1:
//code to be executed exp=label1;

break;

case label2:

//code to be executed exp=label2;

break;

case label3:

//code to be executed exp=label3;

break;

default:

//code to be executed exp is different from both;

<?php

$x=3;

switch($x)

case 1:

echo ”No1”;

break;

case 2:

echo ”No2”;

break;

default:

echo “no number between 1 and 2”; //op


}

Looping control statements:

while(exp) ---entry controlled loop

//code to be executed;

<?php

$myvar=0;

while($myvar<10)

echo “hello”;

$myvar++;

?>

Op: ten times hello would print

do-while: exit controlled loop

do

//code

while(exp);

<?php

$myvar=10;
do

echo “hello”;

$myvar++;

while($myvar<10);

?> op: it would print one hello.

for(variableinitialization; testexp; inc/dec)

//code

<?php

for($count=1;$count<=12;$count++)

echo “$count times 2 is”. ($count*2). ”<br>”;

1 times 2 is 2

2 times 2 is 4

..

12 times 2 is 24

for(….)
{

for(…)

//code

1 2 3 4………12

2 24

12 144

1 2 3 4 12
2 4
3 6
4

12 144

foreach($arr as $k=>$v)

//code
}

Write a php script to change the web page background color and
display the current date and time in the webpage, based on the date
function using conditional control statements.

Environment Variables or Super global variables or built-in variables

In PHP, you need to declare variables as global and initialize them inside the
function where they are used. A function can contain an unlimited number of
global variables.

• These server-side scripts use environment variables to pass information


stored on a Web server to external programs requesting the
information.
• These variables store information regarding the server, such as access
and logon information.
• The only time these variables are used by the operating system is while
passing information back to the program that had requested the
information.

$_GET –contains any variables provided to a script through a GET method.

$_POST- contains any variables provided to a script through a post method.

Form1.html

<html>

<head>
<body> <h1> this is my first form</h1>

<form action="welcome.php" method="get"> post


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

</html>

Action- used to specify the url of the processing script. The browser knows
where to send the form data after it is entered.

Method- indicates a method or protocol sending data to the target action URL
GET/POST

Input type- input tag tells the form to expect information

Type-type attribute tells the form action to expect text

Name=submit- the submit button tells the form to execute the form action

Form- collection of controls and events

method="get”- this value tells the server how to send the data.

Welcome.php

<?php

echo “my name is:”;

echo $_GET["fname"]; $_POST

echo “my age is:”;

echo $_GET["age"];

?>
o/p:

my name is sumangali

my age is 30

• The PHP built-in $_REQUEST function contains the contents of both


$_GET, $_POST, and $_COOKIE.
• The $_REQUEST function can be used to collect form data sent with both
the GET and POST methods.
• Welcome.php
• <?php
• echo $_REQUEST["fname"];
• <br/>
echo “You are “. $_REQUEST["age"]. “years old” ;
• ?>
$_COOKIE –cookie is a small piece of information, contains any variables
provided to a script through a cookie

$_FILES – file upload

$_SERVER- contains information such as headers, file paths, script location

$_SESSION- any variables that are currently registered in a session

$_REQUEST- any variable provided to a script via any user input mechanism.
(post/get). An array of all user inputs including contents.

Arrays in PHP:

Array is a list variable, no size and no data type limit.

A variable that contains multiple elements indexed by numbers or


strings.
Creating an array:

Values can be assigned to an array in two ways:

array() function or array identifier []

Ex:

$user=array(“balu”, “somu”,”ramu”);

echo $user[1];

echo $user[0];

adding new element

$user[]=”saru”;

Extracting/accessing the array elements

print_r($user);

o/p:

Array

[0] => balu

[1] => somu

[2] => ramu

foreach()- is used to loop through arrays.

Works only on arrays, and will issue an error when you try to use it
on a variable with different data type or uninitialized variable.
Ex.

Numerical index

foreach(array-exp as $value)

stmt

manually assigned with key and value pair

foreach(array-exp as $key=>$value)

stmt

foreach($user as $i)

echo $i;

There are 3 different types of arrays:

1. Numeric array- array with numeric indexed

Ex: stores each element with a numeric id key, and this key is
automatically assigned.

<?php

$name[0]=”banu”;

$name[1]=”pari”;

$name[2]=”sumi”;

echo $name[1]. “and”.$name[2]. “are”.$name[0]. “’s neigbors”;

?>
2. Associative arrays- array with named keys

Where each Id key is associated with a value.

Ex:
$character=array(“name”=>”bala”,”occupation”=>”professor”,”age”
=>40, “specialize”=>”DM”);

$character[“occupation”];

o/p: professor

3. Multidimensional array-arrays containing one or more arrays.

Each element in the main array can also be an array.

And each element in the sub array can be an array and so on.

An array containing one/more array and values are accessed using


multiple indices.

$arrbook= array(“comic”=>array(“title”=>”super”,
“author”=>”jerry”,”pub”=>1967), “science”=>
array(“title”=>”newtonlaw”, “author”=>”newton”,”pub”=>1965))

Single- echo $arrbook[“science”][“title”];

foreach($arrbook as $objkey=>$book)

echo $objkey;

foreach($book as $k=$val)

echo $val;

}
echo “<br>”;

The <select> element is used to create a drop-down list.

The <select> element is most often used in a form, to collect user input.

The name attribute is needed to reference the form data after the form is


submitted (if you omit the name attribute, no data from the drop-down list will
be submitted).

The id attribute is needed to associate the drop-down list with a label.

The <option> tags inside the <select> element define the available options in


the drop-down list.

Always add the <label> tag for best accessibility practices!

<input type=text name=’user’>

<p> select some carbrands: </p>

<select name="cars[]" size=”7” multiple>
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  <option value="mercedes">Mercedes</option>
  <option value="audi">Audi</option>
</select>

cars[] intuitionly look like this $cars= array(“Volvo”,


“saab”,”Mercedes”,”audi”);

<p><input type=”submit” value=”process”> </p>

</form>

Name textbox

Select some carbrands

Selectlist box (combobox)


Button for submit

Multipleselect.php

<?php

echo “<p> welcome <b> $_POST[‘user’] </b> </p>”;

echo “your brand choices are:”;

if( !empty($_POST[‘cars’]))

echo “<ul>” ;

foreach($_POST[‘cars’] as $value)

echo <li>$value”;

echo “</ul>” ;

?>

Work: print no of courses registered in this semester (with course


name), also print the no of electives chosen by you. (only number)

Array related functions:

count() is an alias of sizeof()

array_sum()

array_pop()

array_push()

array_values()

array_count_values()

array_unshift() : This function used to insert element at the beginning


of the array

array_keys : retrieving the keys from the specified array.

array-shift():This function used to delete/remove element at the


beginning of the array
array_values () simply returns an indexed array in which each element
is the corresponding element from array.

The returned array is consecutively indexed starting from 0. All keys


from the original array are ignored.

unset()- to quickly collapse an array that has some elements unset into
a freshly ordered indexed array with no blank entries.

$arr= array(1,2,3,4,5,6);

unset($arr[3]); //removes 4

unset($arr[5]); //removes 6

print_r($arr);

$arr1=array_values($arr)

print_r($arr1)

Array

[0] => 1

[1] => 2

[2] => 3

[4] => 5

<?php

$greet;

if(isset($greet)) // isset() cannot be used on a literal(such as 10, “a string” and


so on.//

echo “$greet is set”;

else

echo “$greet is not set”; //op


>?

$greet= “hi”;

if(isset($greet))

echo “$greet is set”; //op

else

echo “$greet is not set”;

>?
isset()- used to check whether the variable has already been set or
not. If set it returns true else false.

What is PHP_SELF variable?

PHP_SELF is a variable that returns the current script being executed.


This variable returns the name and path of the current file (from the
root folder). You can use this variable in the action field of the
FORM. We will now see some examples. echo $_SERVER['PHP_SELF'];

Using the PHP_SELF variable in the action field of the form

A common use of PHP_SELF variable is in the action field of the <form>


tag. The action field of the FORM instructs where to submit the form
data when the user presses the “submit” button. It is common to have
the same PHP page as the handler for the form as well.

However, if you provide the name of the file in the action field, in
case you happened to rename the file, you need to update the action
field as well; or your forms will stop working.

Combining HTML and PHP in a same page/single form submission

Form name: Numguess.php

<?php
$n=42;

if(!isset($_POST[guess]) // isset() is used to check whether the variable is


currently set

$msg=”Welcome to guessing machine!”;

elseif($_POST[guess]>$n)

$msg=”$_POST[guess] is too big! Try a small number”;

elseif($_POST[guess]<$n)

$msg=”$_POST[guess] is too small! Try a larger number”;

else

{ //must be equivalent

$msg= “well done”;

?>

<html>

<body>

<h1> <?php echo $msg; ?> </h1>

<form action = “<?php echo $_SERVER[‘PHP_SELF’];?>” method = “POST”>

<p> Type your guess here:


<input type= “text” name=”guess”> </p>

<p><input type= “submit” value=”submit your guess”> </p>

</form>

</body>

</html>

$_SERVER[‘PHP_SELF’]- super global variable represents the name of the


current script.

The action tells the script to reload itself.

isset()- mixed variable usage. Returns, true if the variable contains a value.
Otherwise, false.

Welcome to the Guessing machine!

Type your guess here:


50

Submit your guess

50 is too big! Try a smaller number

Output will be printed within the same page (single form submission)

Using PHP_SELF variable you can write more generic code which can be
used on any page and you do not need to edit the action field.
Consider, you have a file called form-action.php and want to load the
same page after the form is submitted. The usual form code will be:

<form method="post" action="form-action.php" >

We can use the PHP_SELF variable instead of “form-action.php”. The code


becomes:

<form name="form1" method="post" action="<?php echo


$_SERVER['PHP_SELF']; ?>" >

The complete code of “form-action.php”

Here is the combined code, that contains both the form and the PHP
script.

<?php

if(isset($_POST['submit']))

$name = $_POST['name'];

echo "User Has submitted the form and entered this name : <b> $name
</b>";

echo "<br>You can use the following form again to enter a new
name.";

?>

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

<input type="text" name="name"><br>


<input type="submit" name="submit" value="Submit Form"><br>

</form>

This PHP code is above the HTML part and will be executed first. The
first line of code is checking if the form is submitted or not. The
name of the submit button is “submit”. When the submit button is
pressed the $_POST['submit'] will be set and the IF condition will
become true. In this case, we are showing the name entered by the user.

If the form is not submitted the IF condition will be FALSE as there


will be no values in $_POST['submit'] and PHP code will not be
executed. In this case, only the form will be shown.

PHP basics-variables, constants, operators, datatypes and related functions,


Control structures, Date function with format codes, arrays-types(array
manipulation functions), strings, form processing, environment/super global
variables, form submission with html (html controls-text box, label, checkbox,
list box, combo box, button, radio etc…), single form submission (HTML and
PHP within same page)

Overview of OSS, criteria, standard- copyright and copy left licenses, merits,
oss technologies, open source development cycle…

30 marks

5 to 10m theory

20 to 25m coding

PHP User defined functions:


A function defined by the user.

Rules:

1. The name of the function starts with function statement and precedes a set
of parentheses

2. The naming rules for functions are similar to the naming rules for variables,
but without $sign.

3. If your function name requires arguments, you must place comma separated
variable names within the parentheses. These variables will be filled by the
values passed to your function.

4. The function code starts afters the { opening curly braces. Insert the function
code, and the function is finished by a ? closing curly brace.

Even if your function doesn’t require arguments you must nevertheless supply
the parentheses.

Defining function:

function some_function_name ($arg1, $arg2)

// function code here

}
Eg: Simple function that writes my name when it is called.

<?php

function writeMyname() //Declaring a function

echo “<h1> Sumangali </h1>”;

echo “VIT Professor”;

writeMyname(); //calling function

?> o/p:Sumangali VIT Professor

<?php

function writeMyname($fname)

echo $fname . “Venkata . <br>”;

echo “my name is:;”

writeMyname(“sumi”) ;

echo “my name is:;”

writeMyname(“sumangali”) ;

?>

<?php

function writeMyname($fname, $punctuation)


{

echo $fname . “Krishna” . $punctuation. “<br>”;

echo “your name is:;”

writeMyname(“sumi”, “!”) ;

echo “That’s right my full name is:;”

writeMyname(“sumangali”, “…”) ;

?>

Function can also be used to return values

<?php

function add($x, $y)

$total=$x+$y;

return $total;

echo “1+15=”. add(1,15);

?> // op: 1+15=16

Scope of variable declared inside a function

Static
Global

Static:

If you want a local variable not to be deleted after the function is executed,
you can declare it as static.

<?php

function sum()

$ans=1;

echo $ans;

$ans++;

Sum(); 1

Sum(); 1

?> //each time call sum() variable $ans is initialized as fresh and the
result of increment statement is lost. Output is 1 2nd time always 1

<?php

function sum()

Static $ans=1;

echo $ans. “<br>”;

$ans++;
}

Sum();

Sum();

?>

Output is 1

Output is 2

Static variable is also local to a function. But it doesn’t lose its value after the
execution over, and can’t be referenced in other functions.

function test1()

Static $x=0;

echo $x;

$x++;

test1();

test1();

test1(); ?>

<?php

$a=1; //global scope

function test()

echo $a; // reference to local scope variable

test();
?>

The above program will not produce any output.

<?php

$a=1; //global scope

$b=2;

function test()

global $a, $b; // reference to global scope variable

$b=$a+$b;

test();

echo $b;

?>

This script will output 3. By declaring $a and $b global within the function. All
references to either variable will refer to the global version.

There is no limit to the number of global variables that can be manipulated by


a function.

<?php

$a=1; //global scope

$b=2;

function test()

global $a, $b, $c; // reference to global scope variable


$c=$a+$b;

test();

echo $c;

?>

<?php

$life=42;

function meaning_of_life()

global $life;

echo “The meaning of life is $life<br>”;

meaning_of_life();

?>

o/p:The meaning of life is 42

1st way : global $var1, $var2, $var3;

2nd way: $_GLOBAL [‘a’]+$_GLOBAL[‘b’]

More about arguments:

1. Passing an argument to a function by value


2. Passing an argument to a function by reference.

By value: When a variable is passed as an argument, a copy of the value will be


passed into the function.

Any changes made to these variables in the body of the function are local to
that function will not impact the original copy.

<?php

function addfive($num)

$num+=5;

$originalnum=10;

addfive($originalnum);

echo $originalnum;

?>

o/p: 10

The addfive() function accepts a single numeric value and adds 5 to it, but it
returns nothing.

We assign a value to a variable $originalnum, and pass this variable to


addfive().

Although we increment $num by 5, this has no effect on the value of the


$originalnum.

Local copies of the values of the variables are made.

When we print $originalnum, We find that its value is still 10.


By ref:

When a variable is passed as an argument, a reference will be passed into the


function.

Any changes made to an argument in these cases will change the value of the
original variable.

You can pass a variable by reference of the original variable, and passing that
reference as the calling argument.

<?php

function addfive(&$num)

$num+=5;

$originalnum=10;

addfive($originalnum);

echo $originalnum;

?>

o/p: 15

File handling in PHP:

File is a place where information or data is stored.

1.opening a file –specified file is opened, if it doesn’t exist, it is


created

2. Manipulating a file- Reading, writing and appending are the general


manipulations performed a file.

3. Closing a file – After finishing the working with the file, we need
to close the file.

file_exists() – parameter is string filename. It returns true/false


<?php

echo file_exists(“filepath…tonu.txt”); o/p:1

?>

<?php

if(file_exists(“pathwithinput.dat”))

echo “file exist”;

else

echo “file not exist”;

?>

Every file being opened for any operations like:

r-read only

w- write only

r+ - read and write

w+ -write and read

a- append

a+ -read and append

x –write only

x+ -read and write

file opening:

fopen() – the argument can be a file or URL, depending on whether it is


local file or remote file.

Syntax: fopen(string filename, string mode)

$fp=fopen(“test.txt”, “r”);

$fp=fopen(“test.txt”, “w”);

$fp=fopen(“test.txt”, “a”);

You might also like