Sei sulla pagina 1di 29

Department of Computer Science & Engineering

LAB MANUAL
Session 2013-2014

Subject Name

: - Open Source Software Technology


Lab

Subject Code

: - ICS-653

Branch

: - CSE/IT

Year

: - 3rd

Semester

: - 6th

INTEGRAL UNIVERSITY LUCKNOW


Dasauli, Kursi Road, PO Basha-226026

List of Lab Exercises


Week 1

Experiment No.

Name of the Experiments

Page No.

Objective

Overview of FOSS & Basic Command interface on Linux

2
Week-2
1
2

1
Objective

Usage of Basic Linux Commands, File Utilities Commands


Learning Administrative Commands

3
Week-3
1
2
3

3
Objective

4
5

4
Week-4

6
Objective

1
2

Week-5
1
2

Objective

3
Week-6
1
2

11
Objective

10

12

13

Week-7
1
2

Objective

Week-8
1
2

Objective

14

Dept of CSE /IT

15

Vi Editor & its Modes, Introduction of Basic administrative


commands
Usage of Basic Network Related Commands
Learning Shell Scripting
A Script to check for a file existence in the file system
A Script to execute different command to demonstrate Switch
cases statement
A Script to handle command line argument and other Special
symbols
Learn how to Compile, Debug & Execute C, C++ & Java
Programming Code without IDEs
Create a sample C program for demonstrating the use of
control statements then compile and execute the code
Create a sample C++ class based program for demonstrating
the use of Object oriented Design Patterns, then compile and
execute the code
Creating a sample java Program for demonstrating the use of
control statements then compile and execute the code
Learning Basics of LAMP Server
Installation And Configuration of LAMP Server on Linux
(Ubuntu)
Creating simple Database in MySql Server performing queries
Learning A Deep Dive in MySql
MySql Administrator: Monitoring the Server and User
Administration
MySql Admin, Backup and restore, User Account Rights
Management
Basics of PHP Web Programming
A PHP code to demonstrate the usage of Variable, String,
Array and Control Structure
Some Deep Dive in PHP Programming
A PHP Program to implement customized functions, Form
Handling Strategies
2

ICS-251

5
6
7
8-9
10
11
12

13
14
15
16

17
18
19
20
21
22

23
24

25-26
27

A PHP Program to demonstrate the use of PHP mail ()


Function
Learning Database Connectivity between PHP and MySql

Week-9
1
2

Objective

Week-10

Objective

A Sample Project to create a website for University Utilities

Allotment of already discussed Project like Database


management Systems

16

Dept of CSE /IT

Create a login Control for a web page to demonstrate the use


of Connectivity and Basic retrieval of data from database

ICS-251

28
29

Overview of FOSS
The Open Source Initiative (OSI) is a California public benefit corporation, with 501(c)3 tax-exempt status,
founded in 1998. Open source software is software that can be freely used, changed, and shared (in modified
or unmodified form) by anyone. Open source software is made by many people, and distributed under
licenses that comply with the Open Source Definition.
The Open Source Initiative (OSI) is a global non-profit that supports and promotes the
open source movement. Among other things, we maintain the Open Source Definition,
and a list of licenses that comply with that definition

The Open Source Definition


Open source doesn't just mean access to the source code. The distribution terms of opensource software must comply with the following criteria:

1. Free Redistribution
The license shall not restrict any party from selling or giving away the software as a
component of an aggregate software distribution containing programs from several
different sources. The license shall not require a royalty or other fee for such sale.

2. Source Code
The program must include source code, and must allow distribution in source code as
well as compiled form. Where some form of a product is not distributed with source code,
there must be a well-publicized means of obtaining the source code for no more than a
reasonable reproduction cost preferably, downloading via the Internet without charge. The
source code must be the preferred form in which a programmer would modify the
program. Deliberately obfuscated source code is not allowed. Intermediate forms such as
the output of a preprocessor or translator are not allowed.

Dept of CSE /IT

ICS-251

3. Derived Works
The license must allow modifications and derived works, and must allow them to be
distributed under the same terms as the license of the original software.

4. Integrity of the Author's Source Code


The license may restrict source-code from being distributed in modified form only if the
license allows the distribution of "patch files" with the source code for the purpose of
modifying the program at build time. The license must explicitly permit distribution of
software built from modified source code. The license may require derived works to carry
a different name or version number from the original software.

5. No Discrimination Against Persons or Groups


The license must not discriminate against any person or group of persons.

6. No Discrimination Against Fields of Endeavor


The license must not restrict anyone from making use of the program in a specific field of
endeavor. For example, it may not restrict the program from being used in a business, or
from being used for genetic research.

7. Distribution of License
The rights attached to the program must apply to all to whom the program is redistributed
without the need for execution of an additional license by those parties.

8. License Must Not Be Specific to a Product


The rights attached to the program must not depend on the program's being part of a
particular software distribution. If the program is extracted from that distribution and used
Dept of CSE /IT

ICS-251

or distributed within the terms of the program's license, all parties to whom the program
is redistributed should have the same rights as those that are granted in conjunction with
the original software distribution.

9. License Must Not Restrict Other Software


The license must not place restrictions on other software that is distributed along with the
licensed software. For example, the license must not insist that all other programs
distributed on the same medium must be open-source software.

10. License Must Be Technology-Neutral


No provision of the license may be predicated on any individual technology or style of
interface.

Basic Commands in Linux


Command Syntax
Commands can be run by themselves, or you can pass in additional arguments to make them do
different things. Typical command syntax can look something like this:
command [-argument] [-argument] [--argument] [file]

Examples: ls List files in current directory

ls -l Lists files in long format


ls -l --color As above, with colourized output
cat filename Show contents of a file
cat -n filename Show contents of a file, with line numbers

Dept of CSE /IT

ICS-251

Experiment No 1
Usage of Basic Linux Commands, File Utilities Commands

OBJECTIVE

Learn how to execute commands in shell of Ubuntu

After completing this experiment you will be able to:


Student should able to use basic syntax structure of Commands.
Understand how to use commands in a shell
How to get help for Commands

Requirements
Tools / Apparatus: Unix/Linux Operating System, Bash Shell

Screen Shots

Dept of CSE /IT

ICS-251

Exercise:
Q1. What is a syntax structure of Commands?
Q2. How to see your login details?
Q3. How to change date and time of your Linux/Unix/Ubuntu

For Further Reading Student May Refer to the following Books


1

Linux In depth By Yashwant Kanetkar

Dept of CSE /IT

ICS-251

Learning Administrative Commands


The Linux System Administrator's Guide, describes the system administration aspects
of using Linux. It is intended for people who know next to nothing about system
administration, but who have already mastered at least the basics of normal usage.
This manual doesn't tell you how to install Linux; that is described in the Installation
and Getting Started document. See below for more information
about Linux manuals. System administration covers all the things that you have to do
to keep a computer system in usable order. It includes things like backing up files (and
restoring them if necessary), installing new programs, creating accounts for users
(and deleting them when no longer needed), making certain that the filesystem is not
corrupted, and so on. If a computer were, say, a house, system administration would
be called maintenance, and would include cleaning, fixing broken windows, and other
such things. The structure of this manual is such that many of the chapters should be
usable independently, so if you need information about backups, for example, you can
read just that chapter. However, this manual is first and foremost a tutorial and can be
read sequentially or as a whole.

Experiment No 2
Vi Editor & its Modes, Introduction of Basic administrative commands
OBJECTIVE

Learning the working of Vi Editor and switching between different three different modes.
Should be ready to run and configure administrative commands

Requirements
Tools / Apparatus: Unix/Linux/Windows Operating System, Bash Shell with root login privileges. i.e .
root user name and Password

Exercise:
1. What are the three modes in Vi Editor? How to switch from one mode to another
2. How to take back up of the required data from file system?
2. How to make a close look on Conf files using administrative commands?

Learning Shell Scripts


Dept of CSE /IT

ICS-251

A shell is an environment in which we can run our commands, programs, and shell scripts. There
are different flavors of shells, just as there are different flavors of
operating systems. Each flavor of shell has its own set of recognized commands and functions.
This book works with the Bourne, Bash, and Korn shells. Shells are located in either the /usr/bin/
directory or the /bin/ directory, depending on the UNIX flavor and specific version. The prompt,
$, which is called command prompt, is issued by the shell. While the prompt is displayed, you
can type a command. The shell reads your input after you press Enter. It determines the command
you want executed by looking at the first word of your input. A word is an unbroken set of
characters. Spaces and tabs separate words. Following is a simple example of date command
which displays current date and time:

Dept of CSE /IT

10

ICS-251

Experiment No 3
Learning Shell Scripting
Objective:
Identify the problem statement for which Shell scripting is created.

Student should be able to create shell script to demonstrate the usage of control statements
and usage of special symbols

How to use command line argument in Shell script

Requirements
Tools / Apparatus: Unix/Linux/Windows Operating System, Gedit Text Editor, Bash Shell with root
login credentials

Exercise:
1. Student will be well versed with shell scripting for installation and configuration of softwares.
2. How to use and manage control statement in shell script
3. Demonstrate the use of effective use of command line Argument in shell scripting.

Learn how to Compile, Debug & Execute C, C++ &


Java Programming Code without IDEs
Experiment No 4
Objective

To write program in different programming Languages. Such as C, C++, Java Proagramming


Proper usage of man and gdb tool for effective usage of coding strategies in C, C plus plus,
Java Programming

Dept of CSE /IT

11

ICS-251

Requirements
Tools / Apparatus: Unix/Linux/Windows Operating System, Gedit Text Editor, Compilers and
interpreters of all languages (C, C++, Java)

Exercise:
1. Create a sample C program for demonstrating the use of control statements then compile and execute the
code
Soln
#include<stdio.h> //let us assume file name for this code is democ.c
int main()
{
printf("hello world !");
}
To Compile Your Code $cc democ.cc -o democ.exe // -o option will create object file with given file
name as democ.exe
to Execute Your Code $./democ.exe //use of './' is must before executing your democ.exe file
Note: User can use manual of cc for detailed options of compiling and debuging modes as (man cc)
ii
Create a sample C++ class based program for demonstrating the use of Object oriented
Design Patterns, then compile and execute the code
#include<stdio> //let us assume file name for this code is democplusplus.cpp
#include<iostream>
using namespace std;
class A
{
private:
int a;
public:
void getData()
{
cout<<"ENTER DATA ? "<<endl;
}
void setData()
{
a=25;
//set the default value of a to 25
}
void dispData()
{
cout<<"Your Data is "<<a<<endl;
}
};
int main()
{
printf("hello world ! I N C + + \n\n\n" );
A obj;
Dept of CSE /IT

12

ICS-251

obj.setData();
obj.getData();
obj.dispData();
}
To Compile Your Code $gcc democplusplus.cpp -o democplusplus.exe // -o option will create object
file with given file name as democlusplus.exe
to Execute Your Code $./democplusplus.exe //use of ./is must before executing your
democplusplus.exe file
Note: User can use manual of gcc for detailed options of compiling and debuging modes ($ man gcc)
iii
Creating a sample java Program for demonstrating the use of contol statements then compile and
execute the code
class A
{
private static int a;
public static void getData()
{
cout<<"ENTER DATA ? "<<endl;
}
static void setData()
{
a=25;
//set the default value of a to 25
}
static void dispData()
{
cout<<"Your Data is "<<a<<endl;
}
};
public static void main(String as[])
{
printf("hello world ! I N J A V A \n\n\n" );
A obj=new A();
obj.setData();
obj.getData();
obj.dispData();
}
To Compile Your Code $javac demojava.java // @ the time of compiling filename is given as paramter
to javac (java compiler)
to Execute Your Code $java A // @ the time of interpreting bytecode file class name is given
Note: User can use manual of gcc for detailed options of compiling and debuging modes ($ man gcc)

Dept of CSE /IT

13

ICS-251

Learning Basics of LAMP Server

LAMPisanacronymforawebservicessolutionstackconsistingofLinux,theApache
HTTPServer,theMySQLorMariaDBdatabaseengines,andthePHPorPerl,or
Pythonprogramminglanguage.Allcomponentsarefreeandopensourcesoftware,and
thecombinationissuitableforbuildingdynamicwebpages.Thecombinationofthe
softwareincludedinaLAMPstackmayvary,forexampletheApachewebservercan
bereplacedbysomeotherwebserversoftware.Althoughtheoriginalauthorsofthese
programsdidnotdesignthemtoworkasacomponentoftheLAMPstack,the
developmentphilosophyandtoolsetsaresharedandweredevelopedinclose
conjunction.Thesoftwarecombinationhasbecomepopularbecauseitisentirelyfree
andopensourcesoftware,whichmeansthateachcomponentcanbeadaptedtothe
underlyinghardwareandcustomizedtomeetthespecificationasexactlyaspossible,
withoutovertvendorlockin.Thecompletesoftwarestackisalsofreeofcost,
maximizingtheavailablebudgetfortailoringthehardwareandsoftware.Duetothe
natureoffreeandopensourcesoftwareandtheubiquityofitscomponents,each
componentoftheLAMPstackhasbeentestedforperformanceandsecurity.Atthe
sametime,continuingdevelopmentandanabundanceofexperienceddevelopers
permitnewfeaturesandcustommodificationforspecificapplications.Thecomponents
oftheLAMPstackarepresentinthesoftwarerepositoriesofmostLinuxdistributions,
providingasimplewaytoinstall,setupandoperateaLAMPstackoutofthebox.The
websiteofasmallcompanyistypicallynotsubjecttohightrafficandisnotproneto
frequentattacks,andcanthereforebeadministeredwithminimalresources.
TheLAMPbundlecanbeandofteniscombinedwithmanyotherfreeandopensource
softwarepackagessuchas,forexample:

netsniffngforsecuritytestingandhardening
Snort,anintrusiondetection(IDS)andintrusionpreventionsystem(IPS)
RRDtoolfordiagrams
Nagios,CollectdorCacti,formonitoring.

Dept of CSE /IT

14

ICS-251

Experiment No 5
Installation And Configuration of LAMP Server on Linux (Ubuntu)
Objective:

How to Install and configure LAMP Stack on Ubuntu


Configuring PhpMyAdmin for MySql.

Requirements
Tools / Apparatus: Unix/Linux/Windows Operating System, Gedit Text Editor, LAMP STACK
from Internet

Exercise:
1. WAP to check whether the character entered is in uppercase letter, lowercase letter, a digit or a
special symbol.

LearningInstallingLAMPOnUbuntu
InthisguideIwillshowyouhowtoinstallaLAMPsystem.LAMPstandsforLinux,Apache,MySQL,
PHP.TheguideisintendedtohelpthosewhohaveverylittleknowlegdeofusingLinux.
InstallApache
TostartoffwewillinstallApache.
1.OpenuptheTerminal(Applications>Accessories>Terminal).
2.Copy/PastethefollowinglineofcodeintoTerminalandthenpressenter:
sudoaptgetinstallapache2
3.TheTerminalwillthenaskyouforyou'repassword,typeitandthenpressenter.
TestingApache
TomakesureeverythinginstalledcorrectlywewillnowtestApachetoensureitisworkingproperly.
1.Openupanywebbrowserandthenenterthefollowingintothewebaddress:
http://localhost/
Youshouldseeafolderentitledapache2default/.Openitandyouwillseeamessagesaying"Itworks!",
congratstoyou!
InstallPHP
InthispartwewillinstallPHP5.
Step1.AgainopenuptheTerminal(Applications>Accessories>Terminal).
Step2.Copy/PastethefollowinglineintoTerminalandpressenter:
sudoaptgetinstallphp5libapache2modphp5
Dept of CSE /IT

15

ICS-251

Step3.InorderforPHPtoworkandbecompatiblewithApachewemustrestartit.Typethefollowingcode
inTerminaltodothis:
sudo/etc/init.d/apache2restart
TestPHP
ToensuretherearenoissueswithPHPlet'sgiveitaquicktestrun.
Step1.Intheterminalcopy/pastethefollowingline:
sudogedit/var/www/testphp.php
Thiswillopenupafilecalledphptest.php.
Step2.Copy/Pastethislineintothephptestfile:
<?phpphpinfo();?>
Step3.Saveandclosethefile.
Step4.Nowopenyou'rewebbrowserandtypethefollowingintothewebaddress:
http://localhost/testphp.php
Thepageshouldlooklikethis:
CongratsyouhavenowinstalledbothApacheandPHP!

InstallMySQL
TofinishthisguideupwewillinstallMySQL.(NoteOutofApacheandPHP,MySQListhemostdifficult
tosetup.Iwillprovidesomegreatresourcesforanyonehavingtroubleattheendofthisguide.)
Step1.OnceagainopenuptheamazingTerminalandthencopy/pastethisline:
sudoaptgetinstallmysqlserver
Step2(optional).Inorderforothercomputersonyournetworktoviewtheserveryouhavecreated,you
mustfirsteditthe"BindAddress".BeginbyopeningupTerminaltoeditthemy.cnffile.
gksudogedit/etc/mysql/my.cnf
Changetheline
bindaddress=127.0.0.1
Andchangethe127.0.0.1toyourIPaddress.
Step3.Thisiswherethingsmaystarttogettricky.BeginbytypingthefollowingintoTerminal:
mysqluroot
Followingthatcopy/pastethisline:
mysql>SETPASSWORDFOR'root'@'localhost'=PASSWORD('yourpassword');
(Makesuretochangeyourpasswordtoapasswordofyourchoice.)
Step4.WearenowgoingtoinstallaprogramcalledphpMyAdminwhichisaneasytooltoedityour
databases.Copy/pastethefollowinglineintoTerminal:
sudoaptgetinstalllibapache2modauthmysqlphp5mysqlphpmyadmin
AfterthatisinstalledournexttaskistogetPHPtoworkwithMySQL.Todothiswewillneedtoopena
fileentitledphp.ini.Toopenittypethefollowing:
gksudogedit/etc/php5/apache2/php.ini
Nowwearegoingtohavetouncommentthefollowinglinebytakingoutthesemicolon(;).
Changethisline:
;extension=mysql.so
Tolooklikethis:
extension=mysql.so
NowjustrestartApacheandyouareallset!
sudo/etc/init.d/apache2restart
WithThisWeareallsettostartOurLAMPProject
OtherWebLinksforfurtherHelp
Dept of CSE /IT

16

ICS-251

https://www.digitalocean.com/community/tutorials/howtoinstalllinuxapachemysqlphplamp
stackonubuntu1404h

ttps://help.ubuntu.com/community/ApacheMySQLPHP

Dept of CSE /IT

17

ICS-251

Learning A Deep Dive in MySql


MySQLofficially,butalsocalled"MySequel"is(asofMarch2014)theworld'ssecondmost[a]
widelyusedopensourcerelationaldatabasemanagementsystem(RDBMS).Itisnamedafterco
founderMichaelWidenius'sdaughter,My.TheSQLphrasestandsforStructuredQueryLanguage.
[6]
TheMySQLdevelopmentprojecthasmadeitssourcecodeavailableunderthetermsoftheGNU
GeneralPublicLicense,aswellasunderavarietyofproprietaryagreements.MySQLwasowned
andsponsoredbyasingleforprofitfirm,theSwedishcompanyMySQLAB,nowownedbyOracle
Corporation.
MySQLisapopularchoiceofdatabaseforuseinwebapplications,andisacentralcomponentof
thewidelyusedLAMPopensourcewebapplicationsoftwarestack(andother'AMP'stacks).LAMP
isanacronymfor"Linux,Apache,MySQL,Perl/PHP/Python."Freesoftwareopensourceprojects
thatrequireafullfeatureddatabasemanagementsystemoftenuseMySQL.
Forcommercialuse,severalpaideditionsareavailable,andofferadditionalfunctionality.
ApplicationswhichuseMySQLdatabasesinclude:TYPO3,MODx,Joomla,WordPress,phpBB,
MyBB,Drupalandothersoftware.MySQLisalsousedinmanyhighprofile,largescalewebsites,
includingWikipedia

Dept of CSE /IT

18

ICS-251

Experiment No 6
Objective

Learning about Configuration of MySql Server Instance .

Creating DML DDL Querries in Database.

Accesing User Roles Management In MySql

Requirements
Tools / Apparatus: Unix/Linux/Windows Operating System, Gedit Text Editor, MySql Server and
Client instance

Exercise:
1. WAP to design database in MySql
2. Allot Roles and Permission to newly added user.
3. How to monitor the server.

Dept of CSE /IT

19

ICS-251

Basics of PHP Web Programming


PHPisaserversidescriptinglanguagedesignedforwebdevelopmentbutalsoused
asageneralpurposeprogramminglanguage.AsofJanuary2013,PHPwas
installedonmorethan240millionwebsites(39%ofthosesampled)and2.1million
webservers.[4]OriginallycreatedbyRasmusLerdorfin1994,[5]thereference
implementationofPHP(theZendEngine)isnowproducedbyThePHPGroup.[6]
WhilePHPoriginallystoodforPersonalHomePage,[5]itnowstandsforPHP:
HypertextPreprocessor,whichisarecursiveacronym.PHPcodecanbesimply
mixedwithHTMLcode,oritcanbeusedincombinationwithvarioustemplating
enginesandwebframeworks.PHPcodeisusuallyprocessedbyaPHPinterpreter,
whichisusuallyimplementedasawebserver'snativemoduleoraCommon
GatewayInterface(CGI)executable.AfterthePHPcodeisinterpretedand
executed,thewebserversendsresultingoutputtoitsclient,usuallyinformofa
partofthegeneratedwebpageforexample,PHPcodecangenerateawebpage's
HTMLcode,animage,orsomeotherdata.PHPhasalsoevolvedtoincludea
commandlineinterface(CLI)capabilityandcanbeusedinstandalonegraphical
applications.PHPisfreesoftwarereleasedunderthePHPLicense.PHPhasbeen
widelyportedandcanbedeployedonmostwebserversonalmosteveryoperating
systemandplatform,freeofcharge

Dept of CSE /IT

20

ICS-251

Experiment No 7
A PHP code to demonstrate the usage of Variable, String, Array and Control Structure
Objective

Student should start using basics of php variable, String, Arays

Student should start using Control statements in Php

Dept of CSE /IT

21

ICS-251

Requirements
Tools / Apparatus: Unix/Linux/Windows Operating System, Gedit Text Editor, LAMP STACK.

Exercise:
1. Basics of PHP scripts, variables, Data Types, Operators and Expressions, Arrays, loops
<html>
<head><title></head>
<body><h2>
<?php
$txt=my first string type variable;
echo $txt
$x=500;
If ( $x % 2==0)
echo $x is even no.;
else
echo $x is odd number.;
?>
</h2>
</body>
</html>
2. A PHP Proram to implemet customised Functions
<html><body>
<?php
Function multi($x,$y)
{
$pro=$x*$y;
Return #pro;
}
echo the value of 7*8=.multi(7,8);
</>?>
</body></html>
ii
A PHP Program to implement Form Handling
to demonstrate this we need to create 2 seprate files 1 for storing html content 2 for storing .php file
first html file will be as follows
<html><body>
<h2>Supply order form</h2>
<form action=process.php method=post>
<select name=book>
<option>Design Analysis And Algorithms </option>
<option>Data Structure With C++ </option>
<option>JAVA frameworks in depth </option>
<option>Distributed Systems </option>
<option>Operting System </option>
</select>
Quantity : <input name=quantity type=text />
Dept of CSE /IT

22

ICS-251

<input name=submit />


</form> </body></html>
Second php page will be like this
<html>
<body>
<?php
$quantity=$_POST[quantity];
Echo you ordered .$quantity. .$book. Books<br />;
Echo thanku for ordering
?>
</body></html>
iii

A PHP Program to implement PHP mail () Function

<?php
$to =abcdef@gmail.com;
$subject=TEST SENDING MAIL USING PHP;
$message=hi there I have send you the mail kindly RSPV;
$from=hodiu@ymail.com;
$headers=From: $from;
Mail($to,$subject,$message,$headers);
Echo Mail Sent Successfully ;
?>

Dept of CSE /IT

23

ICS-251

Learning Database Connectivity between PHP and MySql


Open a Connection to the MySQL Server
Before we can access data in a database, we must open a connection to the MySQL
server.
In PHP, this is done with the mysqli_connect() function.

Syntax
mysqli_connect(host,username,password,dbname);
Parameter
host
username
password
dbname

Description
Optional. Either a host name or an IP address
Optional. The MySQL user name
Optional. The password to log in with
Optional. The default database to be used when performing queries
Note: There are more available parameters, but the ones listed above are
the most important.

Experiment No 8
Use the PHP mysqli_connect() function to open a new connection to the
MySQL server.
Inthefollowingexamplewestoretheconnectioninavariable($con)forlateruseinthescript:
<?php
//Createconnection
$con=mysqli_connect("example.com","peter","abc123","my_db");
//Checkconnection
if(mysqli_connect_errno()){
echo"FailedtoconnecttoMySQL:".mysqli_connect_error();
}
?>
CloseConnection

Theconnectionwillbeclosedautomaticallywhenthescriptends.Toclosetheconnectionbefore,use
themysqli_close()function:
Dept of CSE /IT

24

ICS-251

<?php
$con=mysqli_connect("example.com","peter","abc123","my_db");
//Checkconnection
if(mysqli_connect_errno()){
echo"FailedtoconnecttoMySQL:".mysqli_connect_error();
}
mysqli_close($con);
?>

Objective:
1. Understanding the basic concepts of for loop.
2. Developing different patterns.

Requirements
Tools / Apparatus: Unix/Linux/Windows Operating System, Text Editor, Turbo C++ IDE

Exercise:
1. W.A.P for a calculator using do while.
1.

2. A PHP Program to demonstrate the use of PHP mail function.


<?php
2. $to =abcdef@gmail.com;
3. $subject=TEST SENDING MAIL USING PHP;
4. $message=hi there I have send you the mail kindly RSPV;
5. $from=hodiu@ymail.com;
6. $headers=From: $from;
7. Mail($to,$subject,$message,$headers);
8. Echo Mail Sent Successfully ;
9. ?>

Dept of CSE /IT

25

ICS-251

Connectivity of PHP wih MySql

Experiment No 9
Create a login Control for a web page to demonstrate the use of Connectivity and Basic
retrieval of data from database

Objective:
1. Understanding the basic concepts of login Control used in most web based User
Authentication system.
2. Developing ability to analyze the problem statement related to navigating pages
as per data given at run time.

Requirements
Tools / Apparatus: Unix/Linux/Windows Operating System, Text Editor, LAMP STACK

Exercise:
1. How to create login control and embed it in web pages

Solution
Step1:
Usefollowingsqlquerytocreateuserstable
CREATETABLE`users`(
`id`int(4)NOTNULLauto_increment,
`username`varchar(65)NOTNULLdefault'',
`password`varchar(65)NOTNULLdefault'',
PRIMARYKEY(`id`)
)TYPE=MyISAMAUTO_INCREMENT=2;

Dumpingdatafortable`users`

Dept of CSE /IT

26

ICS-251

Hereweareusingtwodatabasefields,Namelyusernameforstoringuseridsforloginsand
passwordforstoringthepasswords.
Step2:Createloginscreen
Afterthatweneedtocreatealoginscreenwhichwillultimatelyautehnticateuservia
database!,Letscreateasmallpageandformnamedlogin_home.php
<formname="form1"method="post"action="login_check.php">
<strong>MemberLogin</strong>
<br/>
Username:<inputname="myusername"type="text"id="myusername"/>
<br/>
Password:<inputname="mypassword"type="text"id="mypassword"/>
<br/>
<inputtype="submit"name="Submit"value="Login"/>
</form>
Step:3Authenticatingusers
Onceauserhasenteredtheusernameandpasswordonthelogin_home.php,theformpass
thevaluestologin_check.phpviaPOSTvariables,Thismethodisdefinedattheform
attributeelementonlogin_home.php.
Note:Whilethevaluesarepassedvia$_POSTvariables,wewillbequeryingpasswordsin
databaseafterencryptingthemwithmd5function.
<?php
$db_host="localhost";//Hostnameofyourdatabaseserver!,In90%casesit'slocalhost
$db_uname="";//Mysqlusernameofyourdatabase
$db_passwd="";//Mysqlpasswordofyourdatabase
$db_name="test";//Databasename
$db_table_name="users";//Nameofthetablewecreatedearlier
//Connecttoserverandselectdatabse.
$conn=mysql_connect("$db_host","$db_uname","$db_passwd")ordie("cannotconnect".
mysql_error());
$conn_db=mysql_select_db("$db_name",$conn)ordie("cannotselectDB".mysql_error());
//usernameandpasswordsentfromform
$form_uname=$_POST['myusername'];
$form_passwd=$_POST['mypassword'];
//ToprotectMySQLinjection(moredetailaboutMySQLinjection)
$form_uname=stripslashes($form_uname);
Dept of CSE /IT

27

ICS-251

$form_passwd=stripslashes($form_passwd);
$form_uname=mysql_real_escape_string($form_uname);
$form_passwd=mysql_real_escape_string($form_passwd);
$form_passwd=md5($form_passwd);//md5encryptionforqueryingthepasswordfrom
database
$sql="SELECT*FROM$db_table_nameWHEREusername='$form_uname'and
password='$form_passwd'";
$result=mysql_query($sql);
//Mysql_num_rowiscountingtablerow
$count=mysql_num_rows($result);
//Ifresultmatched$form_unameand$form_passwd,tablerowmustbe1row
if($count==1){
//Register$form_uname,$form_passwdandredirecttofile"login_success.php"
$logged_in=TRUE;
session_register("form_uname");
session_register("logged_in");
header("location:login_success.php");
}
else{
echo"WrongUsernameorPassword";
}
?>
Pleasenotethatthisisnotthebestwaytostorepasswords,Abetterwayforensuring
securityisdefinedinthisPasswordHashingtutorial.(CreditsJohnRockefeller)
Thiscodewillcreatesessionswhichcanusetoauthenticateusersontheparticularpages,
Thesepagesjustneedtocheckthesessionvalueoflogged_in,Iflogged_inissetfortruethen
theuserisauthenticatedandelseitwillberedirectedtotheloginpage

Dept of CSE /IT

28

ICS-251

A Sample Project to create a website for University Utilities


In this phase students will be given various university related web based Utilities as form of Data
management systems

Experiment No 10
OBJECTIVE
1.
2.

Students should able to Create simple Database management Web based Solutions
Lets Student understand the real world Web Based Software Industry Strategies.

Requirements
Tools / Apparatus: Unix/Linux/Windows Operating System, Text Editor, Turbo C++ IDE

Exercise:
1. Proper Drill for Documentation for all phases used in Web Development Strategies

Dept of CSE /IT

29

ICS-251

Potrebbero piacerti anche