0% found this document useful (0 votes)
17 views98 pages

Fos Final PDF - Removed

Uploaded by

hr215144
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views98 pages

Fos Final PDF - Removed

Uploaded by

hr215144
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 98

A LABORATORY MANUAL FOR

FREE AND OPEN SOURCE


SOFTWARE (FOS)
21527

ODD SEMESTER-V
DIPLOMA PROGRAMME IN INFORMATION
TECHNOLOGY

GOVERNMENT POLYTECHNIC, NASHIK


(An Autonomous Institute Of Government Maharashtra)
GOVERNMENT POLYTECHNIC, NASHIK
(An Autonomous Institute Of Government
Maharashtra)

VISION
To be a premier Technical Training and Development Institute catering to the skill and professional
development in multi-domain for Successful employment/self-employment by offering certified and
accredited NSQF compliant programmers. The Institute shall be the center for Excellence in skill
development and community development through different training programmers, business
incubation and Entrepreneurship development.

MISSION

The Government Polytechnic, Nashik, an Autonomous Institute of Government of Maharashtra has the
Mission to provide Education for skill Development, Engineering Diploma and continuing education
Programmers for enhancement of employability skills of the aspirants in the job/self-employment
through continually developing quality learning systems. The Institute aims at holistic and the student
centric education in collaboration with business, industry and having practice based education.
GOVERNMENT POLYTECHNIC, NASHIK
(An Autonomous Institute Of Government Maharashtra)

Vision of Information Technology Department:


To achieve quality education to deal with rapidly changing technologies which produce competent
manpower to address the global challenges and contribute to the field of computer technology.

Mission of Information Technology Department:


Department of Computer Technology is committed
M1. To make the student to Anticipate and respond effectively.
M2. To develop innovative skills and act robust and reliable ways to solve the engineering problems
ethically with integrity.
M3.To secure technological and decision-support services and applications to inspire student.
M4. To empower employers, stake holders and ultimately advance the state of education in the nation.
M5. To encourage student for employable, entrepreneurial and life- long learning skill and develop
leadership skills with social sensitivity.
PROGRAMME: Diploma Programme in Information Technology (IF)/Computer
Technology (CM)
COURSE: Free and Open Source Software (FOS) COURSECODE: 21527
TEACHING AND EXAMINATION SCHEME:
Teaching Scheme Examination Scheme

Hrs/week TH Marks
Credits
TH TU PR Paper Hrs. TH TEST TH+TEST PR OR TW TOTAL

Max. 80 20 100 -- 25 25 150


03 -- 02 04 03
Min. 32 -- 40 -- 10 10 --
1.0 RATIONALE:
Free and open-source software (FOSS) allows users and programmers to edit, modify or reuse the
software's source code. This gives developers the opportunity to improve program functionality by
modifying it. The term “free” indicates that the software does not have constraints on copyrights. Open
source has acquired a prominent place in software industry. Having knowledge of Open source and its
related technologies is essential. This course introduces various Free and Open source software’s.

2.0 COURSE OBJECTIVES:

The student will be able to,


1. Understand the difference between open source software and commercial software.
2. Familiarity with Linux operating system.
3. Understanding and development of web applications using open source web technologies like
Apache, MySql and PHP (LAMP / XAMP).

3.0 COURSE OUTCOMES:

The course content should be taught and learning imparted in such a manner that students are able to
acquire required learning outcome in cognitive, psychomotor and affective domain to demonstrate
following course outcomes:
1. Understand the difference between open source software and commercial software.
2. Identify, install and run Linux operating system.
3. Identify, install open source web technologies Apache
4. Write various queries in MySQL
5. Write session control PHP code for a website.
GOVERNMENT POLYTECHNIC NASHIK
(An Autonomous Institute Of Government
Maharashtra)

CERTIFICATE
This is to certify that Mr./Mrs.

Rollno of fifth Semester of Diploma in Information

Technology has completed term work satisfactory in subject Free and Open

Source Software (21527) for academic year 20__ to 20__ as prescribed in the

curriculum.

Date: Exam Seat No.:

Sign:

Name of Student:

Subject Teacher Head of Department Principal


INDEX

Academic Year: Name of Faculty:


Programme: _ Course & Code:

Name of Student:

Sr. Title of Practical Date Marks Sign of


No Lecturer
Performance Completion
Study of various Open
1 source Operating systems
Installation of Ubuntu
2
3 Write various Text processing
commands in Linux

Write various file handling


4
commands in Linux
5 Write a Shell script to
perform arithmetic
operations
Write commands to check an
6
abled module in APACHE
Create and Insert data
7
into table in MySQL
8 Sort data in MySQL
String functions in
9
MySQL
Write a simple PHP program
10 displaying sum
of digits
Write a PHP program for
11 handling strings

Write a PHP program for


12 cookies and session handling
Total
Average

Name & Signature of Student Signature of Faculty


Practical No.1
Title:-Study of various Open source Operating System.
Theory:

Define open source Operating System:


Open-source software is computer software that is released under a license in which the copyright holder
grants users the rights to use, study, change, and distribute the software and its source code to anyone
and for any purpose. Open-source software may be developed in a collaborative, public manner.

Examples of Open Source Software


1. Operating System
Examples of open source operating system are as follows:
• Linux
• Android
• ReactOS
2. Web Servers
Examples of open source web servers are as follows:
• Apache HTTP Server
• Apache Tomcat
• Lighttpd
• Node.js
3. Database Systems
Examples of open source database systems are as follows:
• MySQL
• SQLite
• Apache Hive
• Maria DB
4. Mobile Development Frameworks
Examples of open source mobile development frameworks are as follows:
• Ionic
• React Native
• Flutter
• Xamarian
5. QA Automation Tools
Examples of open source QA automation tools are as follows:
• Selenium
• Watir
6. Office Software Suites
Examples of open source office software suites are as follows:
• Apache OpenOffice
• Libre Office
7. Content Management Systems
Examples of open source content management systems are as follows:
• WordPress
• Django

LINUX Operating System:


o An operating system can be described as an interface among the computer hardware and the user of any
computer. It is a group of software that handles the resources of the computer hardware and facilitates basic
services for computer programs.
o An operating system is an essential component of system software within a computer system. The primary
aim of an operating system is to provide a platform where a user can run any program conveniently or
efficiently.

The Linux operating system's architecture mainly contains some of the components: the Kernel, System
Library, Hardware layer, System, and Shell utility.

1. Kernel:- The kernel is one of the core section of an operating system. It is responsible for each of the
major actions of the Linux OS. This operating system contains distinct types of modules and cooperates
with underlying hardware directly. The kernel facilitates required abstraction for hiding details of low-level
hardware or application programs to the system. There are some of the important kernel types which are
mentioned below:

o Monolithic Kernel o Micro kernels o Exo kernels o Hybrid kernels

2. System Libraries:- These libraries can be specified as some special functions. These are applied for
implementing the operating system's functionality and don't need code access rights of the modules of
kernel.

3. System Utility Programs: - It is responsible for doing specialized level and individual activities.
4. Hardware layer: - Linux operating system contains a hardware layer that consists of several peripheral
devices like CPU, HDD, and RAM.

5. Shell:- It is an interface among the kernel and user.. It can take commands through the user and runs the
functions of the kernel. The shell is available in distinct types of OSes. These operating systems are
categorized into two different types, which are the graphical shells and command-line shells.
Some of the primary features of Linux OS are as follows:
o Portable: Linux OS can perform different types of hardware and the kernel of Linux supports the
installation of any type of hardware environment.
o Open source: Linux operating system source code is available freely and for enhancing the capability of the
Linux OS, several teams are performing in collaboration.
o Multiprogramming: Linux OS can be defined as a multiprogramming system. It means more
than one application can be executed at the same time.

o Multi-user: Linux OS can also be defined as a multi-user system. It means more than one user
can use the resources of the system such as application programs, memory, or RAM at the same
time.
o Hierarchical file system: Linux OS affords a typical file structure where user files or system files are
arranged.

o Security: Linux OS facilitates user security systems with the help of various features of
authentication such as controlled access to specific files, password protection, or data
encryption.

o Shell: Linux operating system facilitates a unique interpreter program. This type of program can
be applied for executing commands of the operating system. It can be applied to perform various
types of tasks such as call application programs and others.

Android Operating System:

• Android is a mobile operating system based on a modified version of the Linux kernel and other open- source
software, designed primarily for touchscreen mobile devices such as smartphones and tablets.
• Android is developed by a partnership of developers known as the Open Handset Alliance and commercially
sponsored by Google. It was disclosed in November 2007, with the first commercial Android device, the HTC
Dream, launched in September 2008.
• It is free and open-source software. Its source code is Android Open Source Project (AOSP), primarily licensed
under the Apache License.

Features of Android Operating System o Near


Field Communication (NFC) o Infrared
Transmission o Automation o Wireless App
Downloads o Storage and Battery Swap o
Custom Home Screens o Widgets
o Custom ROMs

Architecture of Android OS
The android architecture contains a different number of components to support any android device needs. Android
software contains an open-source Linux Kernel with many C/C++ libraries exposed through application framework
services.
Among all the components, Linux Kernel provides the main operating system functions to Smartphone and
Dalvik Virtual Machine (DVM) to provide a platform for running an android application. An android
operating system is a stack of software components roughly divided into five sections and four main layers, as
shown in the below architecture diagram.
o Applications o
Application Framework o
Android Runtime o
Platform Libraries o Linux
Kernel

1. Applications

An application is the top layer of the android architecture. The pre-installed applications like camera, gallery,
home, contacts, etc., and third-party applications downloaded from the play store like games, chat
applications, etc., will be installed on this layer. It runs within the Android run time with the help of the
classes and services provided by the application framework.

2. Application framework

Application Framework provides several important classes used to create an Android application. It provides
a generic abstraction for hardware access and helps in managing the user interface with application
resources. Generally, it provides the services with the help of which we can create a particular class and
make that class helpful for the Applications creation.

It includes different types of services, such as activity manager, notification manager, view system, package
manager etc., which are helpful for the development of our application according to the prerequisite.

The Application Framework layer provides many higher-level services to applications in the form of Java
classes. Application developers are allowed to make use of these services in their applications. The Android
framework includes the following key services:

o Activity Manager: Controls all aspects of the application lifecycle and activity stack.
o Content Providers: Allows applications to publish and share data with other applications.
o Resource Manager: Provides access to non-code embedded resources such as strings, colour settings and user
interface layouts.
o Notifications Manager: Allows applications to display alerts and notifications to the user.

o View System: An extensible set of views used to create application user interfaces.

3. Application runtime

Android Runtime environment contains components like core libraries and the Dalvik virtual machine (DVM). It
provides the base for the application framework and powers our application with the help of the core libraries.

Like Java Virtual Machine (JVM), Dalvik Virtual Machine (DVM) is a register-based virtual machine designed and
optimized for Android to ensure that a device can run multiple instances efficiently.

It depends on the layer Linux kernel for threading and low-level memory management. The core libraries enable us
to implement android applications using the standard JAVA or Kotlin programming languages.

4. Platform libraries

The Platform Libraries include various C/C++ core libraries and Java-based libraries such as Media, Graphics,
Surface Manager, OpenGL, etc., to support Android development.
o app: Provides access to the application model and is the cornerstone of all Android applications.
o content: Facilitates content access, publishing and messaging between applications and application components.
o database: Used to access data published by content providers and includes SQLite database, management
classes.
o OpenGL: A Java interface to the OpenGL ES 3D graphics rendering API.
o os: Provides applications with access to standard operating system services, including messages, system
services and inter-process communication.
o text: Used to render and manipulate text on a device display. o view: The fundamental building blocks of
application user interfaces.
o widget: A rich collection of pre-built user interface components such as buttons, labels, list views, layout
managers, radio buttons etc.
o WebKit: A set of classes intended to allow web-browsing capabilities to be built into applications.
o media: Media library provides support to play and record an audio and video format.
o surface manager: It is responsible for managing access to the display subsystem. o SQLite: It provides
database support, and FreeType provides font support.
o SSL: Secure Sockets Layer is a security technology to establish an encrypted link between a web server and a
web browser.

5. Linux Kernel

Linux Kernel is the heart of the android architecture. It manages all the available drivers such as display, camera,
Bluetooth, audio, memory, etc., required during the runtime.
The Linux Kernel will provide an abstraction layer between the device hardware and the other android architecture
components. It is responsible for the management of memory, power, devices etc. The features of the Linux kernel are:
o Security: The Linux kernel handles the security between the application and the system.
o Memory Management: It efficiently handles memory management, thereby providing the freedom to develop our
apps.
o Process Management: It manages the process well, allocates resources to processes whenever they need them.
o Network Stack: It effectively handles network communication.
o Driver Model: It ensures that the application works properly on the device and hardware manufacturers
responsible for building their drivers into the Linux build.

ReactOS

ReactOS is a free and open-source operating system based on the best design principles found in the Windows NT
architecture. Written completely from scratch, ReactOS is not a Linux-based system and it shares none of the UNIX
architecture.

The main goal of the ReactOS project is to provide an operating system which is binary compatible with Windows.
This will allow Windows applications and drivers to run as they would on a Windows system.

The ultimate goal of ReactOS is to allow people to use it as an alternative to Windows without the need to change
software they are used to.

Questions:

1. List and explain any four Linux Distributions.


2. Differentiate between open source and commercial software.
3. Why use open source operating system?
4. Why is open source better than commercial software?

Conclusion:

Practical No.2
Title: -Installation of Ubuntu

Theory:
Ubuntu:
Ubuntu is a Linux distro based on Debian. It is suitable for cloud computing, servers, desktops, and
internet of things (IoT) devices. The main difference between Linux and Ubuntu is that the former is an
operating system family based on Unix, while Ubuntu is a Linux distribution.
Ubuntu is a free open-source operating system that you can download from its official website. You can
also modify its source code as you see fit – as of now, there are numerous projects based on Ubuntu.

Features of Ubuntu:

Following are some of the significant features of Ubuntu −

• The desktop version of Ubuntu supports all the normal software on Windows such as Firefox,
Chrome, VLC, etc.
• It supports the office suite called LibreOffice.
• Ubuntu has an in-built email software called Thunderbird, which gives the user access to email
such as Exchange, Gmail, Hotmail, etc.
• There are a host of free applications for users to view and edit photos.
• There are also applications to manage videos and it also allows the users to share videos.
• It is easy to find content on Ubuntu with the smart searching facility.
• The best feature is, it is a free operating system and is backed by a huge open source community.

Installation of Ubuntu
1. Installing ubuntu using USB

• This is one of the easiest method of installing Ubuntu 20.04 from a USB stick.

Step 1. Requirements

• An ISO image of Ubuntu 20.04


• 2 USB drives
• A computer system

Step 2. Prepare Live USB

• Follow the steps below to prepare a live USB drive:


• 1. Download the Ubuntu 20.04 LTS ISO file from the Ubuntu official Downloads page.
2. Insert the USB drive into your system. The USB drive must be a minimum of 4GB.
3. To make a Live USB in your Ubuntu system, open the Startup Disk creator application. If you are
using a Windows system, use Rufus, and for macOS, use the Disk utility. In this example, we are
working on an Ubuntu system, so we will use the Startup Disk creator application.
• 4. To launch the Startup Disk creator, hit the super key on your keyboard and search for the application
using the search bar that appears. When the search result appears, click on the Startup Disk creator icon
to launch the application. Under the Source disc image (.iso) section in the Startup Disk creator
application, click on the other button to insert the Ubuntu .iso file. The Disk to use section will
automatically detect and add your plugged-in USB drive.

Click the Make Startup Disk button to start creating a bootable USB drive.
Wait for a little while, and the bootable media will be created. You will see the following message.
Click the Quit button to close the notification.

Step 3. Run Ubuntu from USB

Once you have a bootable USB, you can take it with you anywhere and run the OS from it without
installation. However, remember that you cannot store files and data on the USB live image. If you want
to save files and data on the USB drive, you will first need to install Ubuntu on the USB and create
persistent storage.
Note: If the system you are using already has an OS installed, you should be sure to make a backup of all
your data.
Step 4. Try Ubuntu
If you want to just try out Ubuntu OS without installing it, follow the steps below:
Insert the bootable USB on your system and boot your system from it.
After the boot is finished, the following window will appear.
Select the Try Ubuntu option, after which the Ubuntu live session will be started.
Now, you can try using Ubuntu from the USB drive and get more familiar with its GUI layout and
appearance.

Step 5 . Install Ubuntu


If you want to keep files and data persistent in the Ubuntu OS, you will need to install it on your USB
drive. The following are the steps required to do so:
1. Insert the bootable USB on your system and boot your system from it.
2. After the boot is finished, the following window will appear. Select the Install Ubuntu option.
Step 6. Once you have selected the Install Ubuntu option, you will see the following window. Select the

keyboard layout and click Continue.


Step 7. Select the Normal Installation or Minimal Installation option, based on whether you want the
fully-featured Ubuntu OS, or you just want the basic features, respectively.

Uncheck the Install third-party software for graphics and Wi-Fi hardware and additional media
formats check box. Then, click the Continue button. You can choose to download the updates during
installation of the OS by checking the Download updates while installing Ubuntu box.

Step 7. Next, in the InstallarESPECT9pe window, choose the Something else option and click the
Install Now button.
Step 8. Identify the USB drive on which you want to install Ubuntu. In my case, it is
/dev/sdb with one partition, as the size of my USB drive is 32 GB. We will delete the old
partition and create new ones.
Select the USB drive from the Device list at the top and click the New Partition Table button.
Then, click the + button to open the Edit partition window and create three partitions, one by one:
• A swap partition of a size slightly larger than the system’s RAM. Choose the “swap” selection in
the Use as option.
• A FAT32 partition with any size greater than 512 MB.
• A root partition of a size not less than the 4 GB minimum. You can use all the remaining space on
your USB drive for the root partition. Choose the “ext4” selection in the Use as option and set the
mount point to “/.”
Under the Device for boot loader installation, make sure that you have selected the USB drive.
Then, click the Install Now button.
Step 9. A window will appear asking you to confirm the changes. Click Continue to proceed with the
installation process.

Step 10. Select the region where you live and click Continue.

Step 11. The system will ask you to create a username, system name, and password. Provide the
required information and click Continue.
Step 12. Now, the installation will be started. Once the installation is completed, you will see the
following message.
Click the Restart Now button to restart the system.

Questions and answers:


1. Define partitioning?

2. Explain types of partition.


3.
What are different files system are available in LINUX.
4. What is LINUX file system?

5. What is Differentiate between EXT3 and EXT4?

Conclusion
Output:
WELCOME TO
GOVERNMENT
POLYNASIK.

2) wc:-
The'wc' commandhelps incountingthelines,wordsandcharactersin afile.Syntax:
-wc<fileName>
(Countswords,linesandcharacters
)
wc-l<fileName
> (Countsonlylines
)

wc-w <fileName> (Counts onlywords) wc-c


<fileName> (Countsonlycharacters)
3) cut:-
The 'cut' command is useful in selecting a specific column of a file. After (-d), delimiter (fromwhere
youwanttoseparatethecolumns)comes.Delimiterscanbeaspace(''),ahyphen(- ),aslash(/)oranythingelse.After(-
f),columnnumberismentioned. Syntax:-cut-d(delimiter)-f(columnNumber) <fileName>

4) sort:-
The'sort'commandsortsthefilecontentinanalphabeticalorder.Syntax:-sort<fileName>

5) grep:-

The'grep'commandstandsfor"globalregularexpressionprint".grepcommandfiltersthecontentofafilew
hichmakesoursearcheasy.

grep-A commandisusedto displaytheline aftertheresult. grep-B


commandisusedtodisplaythelinebeforetheresult. grep -C command is used to
display the line after and line before the result.grep-
A<lineNumber><searchWord><fileName> grep -
B<
lin
eN
u
m
ber><searchWord><fileName>grep -
C<lineNumber><searchWord><fileName>grepwithpipe
The'grep'commandisgenerallyusedwithpipe(|).

Syntax:-command|grep<searchWord>

Questions and answers:


1. Write one line description for.
wc <filename> , wc –l <filename> , wc –c <filename>

2. True or False : and justify your answer cat emp.txt | tr ‘[a-z]’ ‘[A-Z]’
Is given command will change case from lower to upper.

3. $ echo "Welcome To My Academy" | tr -d ‘W' What output will


provided?
4. What is use of CAT command .

Conclusion
Practical No.4
Title:- Write Various File handling Commands in Linux.

ls option Description

ls -a In Linux, hidden files start with . (dot) symbol and they are not
visible in the regular directory. The (ls -a) command will enlist
the whole list of the current directory including the hidden
files.
l s-l It will show the list in a long list format.
ls -lh
This command will show you the file sizes in human readable
format. Size of the file is very difficult to read when displayed
in terms of byte. The (ls -lh)command will give you the data
in terms of Mb, Gb, Tb, etc.

ls -lhS If you want to display your files in descending order (highest at


the top) according to their size, then you can use (ls -lhS)
command.

ls -l - - It is used to display the files in a specific size format. Here, in


block- [SIZE] you can assign size according to your requirement.
size=[SIZ
E]

ls -d */ It is used to display only sub directories.


Theory:
1) ls:-
The ls is the list command in Linux. It will show the full list or content of your directory.
Just type ls and press enter key. The whole content will be shown. Syntax: ls [option]

2) cd:-
The "cd" stands for 'change directory' and this command is used to change the current
directory i.e; the directory in which the user is currently working.
Syntax:- cd <dirname>
2.1) Change from current directory to a new directory
In the snapshot, first I have given pwd command, it brings me to the current directory, that
is /home/sssit. Now I have given the command 'cd' to change my current directory
and have mentioned the path for the new directory
/home/sssit/Desktop. Now as you can see I'm on my new directory that is Desktop. And
now my current working directory has changed toDesktop.

2.2) Change directory using absolute path


In absolute path we have to mention whole path starting from root.
In above example, we want to change our directory to 'certs' from 'cups'. So we are
providing the whole path /run/cups/certs starting from the root (/). This is called absolute
path.
2.3) Change directory using relative path
This exmple is same as the above one. Only difference is that we are providing relative path.
Look, here also we have changed our directory from 'cups' to 'certs' but have not mentioned
the whole path. This is the relative path.
3) pwd:-
Linux pwd (print working directory) command displays your location currently you are
working on. It will give the whole path starting from the root ending to the directory. Syntax:-
pwd
4) touch:- touch command is a way to create empty files (there are some other
mehtods also). You can update the modification and access time of each file with the
help of touch command.
Syntax:- touch <filename>

Option Function

touch -a To change file access and modification time.

touch -m It is used to only modify time of a file.

touch -r To update time of one file with reference to the other file.

touch -t To create a file by specifying the time.


5) cat:-
The 'cat' command is the most universal and powerful tool. It is considered to be one
of the most frequently used commands. It can be used in many types as given below.
Syntax:- cat <fileName>
Option Function

cat > [fileName] To create a file.


6) [oldfile] > [newfile]
cat To copy content from older to new file.

cat [file1 file2 and so To concatenate contents of multiple files into one.
on] > [new file name]

cat -n/cat -b [fileName] To display line numbers.

cat -e [fileName] To display $ character at the end of each line.

cat [fileName] <<EOF Used as page end marker.

mkdir:-
The mkdir stands for 'make directory'. With the help of mkdir command, you can create a
new directory wherever you want in your system. Just type
"mkdir<dir name>, in place of <dir name> type the name of new directory, you want
to create and then press enter.
Syntax:-mkdir <dirname>
Options Description

mkdir -p, -parents Add directory including its sub directory.


7) rmdir:-
mkdir -v, -verbose Print a message for each created directory.
This
mkdir -m - Set access privilege.
mode=MODE

command is used to delete a directory. But will not be able to delete a directory including
a sub-directory. It means, a directory has to be empty to be deleted.
Syntax:-rmdir <dirname>
8) rm:-
The 'rm' means remove. This command is used to remove a file. The command line
doesn't have a recycle bin or trash unlike other GUI's to recover the files. Hence, be
very much careful while using this command. Once you have deleted a file, it is
removed permanently. Syntax:-rm <filename>

Option Description

rm *extension Used to delete files having same extension.

rm -r or R To delete a directory recursively.

rm -i Remove a file interactively.


Option Function
9) mv:-
mv file1 file2 If file2 does not exist, then file1 is
renamed file2. If file2 exists, its contents are silently
replaced with the contents of file1.

mv -i file1 file2
Like above however, since the "-i" (interactive) option is
specified, if file2 exists, the user is prompted before it is
overwritten with the contents of file1.
Linux mv command is used to move existing file or directory from one location to
another. It is also used to rename a file or directory. If you want to rename a single
directory or file then 'mv' option will be better to use.
The files file1 and file2 are moved to directory dir1.
mv file1 file2 dir1 If dir1 does not exist, mv will exit with an error.

mv dir1 dir2
If dir2 does not exist, then dir1 is renamed dir2. If
dir2 exists, the directory dir1 is moved within
directory dir2.

10) cp:-
'cp' means copy. 'cp' command is used to copy a file or a directory.To copy a file into the
same directory syntax will be,
Syntax:-cp <existing file name> <new file name>

Option Function

cp -r To copy a directory along with its


sub directories.

cp file1 file 2 directory name To copy multiple file or directories in


a directory.

cp -backup To backup the existing file before


over writing it.

cp -i Asks for confirmation.

cp -l To create hard link file.

cp -p Preserves attribute of a file.

cp -u -v To make sure source file is newer


then destination file.
11) head:-
The 'head' command displays the starting content of a file. By default, it
displays starting 10 lines of any file.

Syntax:- head <file name>

Option Function

head -n <file name> The 'head -n' option displays specified number
of lines.

head - The 'head -c' command counts the number of


c <number> <file name> bytes of a file.
12) tail:-
The 'tail' command displays the last lines of a file. Its main purpose is to read the
error message. By default, it will also display the last ten lines of a file. Syntax:- tail
<file name>

Option Function

tail - The 'tail -n' option displays the specified


n<number> <file name> number of lines.

tail - The 'tail -c' option displays the specified


c<number> <file name> number of bytes from the last.

13) comm.:-

The 'comm' command compares two files or streams. By default, 'comm' will always
display three columns. First column indicates non-matching items of first file, second
column indicates non-matching items of second file, and third column indicates
matching items of both the files. Both the files has to be in sorted order for 'comm'
command to be executed. Syntax:-comm <file1> <file2>
Questions:

1 Write one line description for i.ls –la ii.rm –rf iii. touch -c

2 List File manipulation command.

3 How to create new file in Linux?


4. How to use mv command?
Conclusion:
Practical No.5
Title: - Write a shell script to perform arithmetic operators.

Theory: Shell:
A shell is a special user program that provides an interface for the user to use operating system services.
Shell accepts human-readable commands from users and converts them into something which the kernel
can understand. It is a command language interpreter that executes commands read from input devices
such as keyboards or from files. The shell gets started when the user logs in or starts the terminal.
Shell is broadly classified into two categories –
➢ Command Line Shell ➢
Graphical shell

Command Line Shell


Shell can be accessed by users using a command line interface. A special program called Terminal in
Linux/macOS, or Command Prompt in Windows OS is provided to type in the human-readable
commands such as “cat”, “ls” etc. and then it is being executed. The result is then displayed on the
terminal to the user.

Graphical Shells
Graphical shells provide means for manipulating programs based on the graphical user interface (GUI),
by allowing for operations such as opening, closing, moving, and resizing windows, as well as switching
focus between windows.

• Shell Scripting –is an open-source computer program designed to be run by the Unix/Linux
shell. Shell Scripting is a program to write a series of commands for the shell to execute. It can combine
lengthy and repetitive sequences of commands into a single and simple script that can be stored and
executed anytime which, reduces programming efforts. Types of Shell:
1. The C Shell
Bill Joy created it at the University of California at Berkeley. It incorporated features such as aliases
and command history. It includes helpful programming features like built-in arithmetic and C-like
expression syntax. In C shell:
➢ Command full-path name is /bin/csh, ➢ Non-root user default prompt is
hostname %,
➢ Root user default prompt is hostname #.

2. The Bourne Shell


It was written by Steve Bourne at AT&T Bell Labs. It is the original UNIX shell. It is faster and more
preferred. It lacks features for interactive use like the ability to recall previous commands. It also lacks
built-in arithmetic and logical expression handling. It is default shell for Solaris OS. For the Bourne
shell the:
➢ Command full-path name is /bin/sh and /sbin/sh,
➢ Non-root user default prompt is $, ➢ Root user
default prompt is #.
3. The Korn Shell
It is denoted as ksh .
It was written by David Korn at AT&T Bell Labs. It is a superset of the Bourne shell. So it supports
everything in the Bourne shell.It has interactive features. It includes features like built-in arithmetic and
C-like arrays, functions, and string-manipulation facilities. It is faster than C shell. It is compatible with
script written for C shell. For the Korn shell the:

➢ Command full-path name is /bin/ksh, ➢


Non-root user default prompt is $, ➢ Root
user default prompt is #.

4. GNU Bourne-Again Shell –

The BASH (Bourne Again SHell) command-line interpreter and scripting language runs on Linux and
macOS, among other Unix-based platforms. It has advanced scripting capabilities and a user-friendly
command line interface, with support for things like variables, control structures, and tab completion. On
Unix and Linux systems, BASH is commonly used for a variety of automation, administration, and
interactive purposes. Denoted as bash.
It is compatible to the Bourne shell. It includes features from Korn and Bourne shell. For the GNU Bourne-
Again shell the:

➢ Command full-path name is /bin/bash,


➢ Default prompt for a non-root user is bash-g.gg$
➢ Root user default prompt is bash-g.gg#.

5. Z Shell –
Denoted by zsh
Z Shell (zsh) was created by Paul Falstad in 1990 while he was a student at Princeton University. Z Shell is
an extended version of the Bourne-Again Shell (bash), with additional features and capabilities.

➢ Command full-path name is /bin/zsh,


➢ Default prompt for a non-root user is abhishekaslk(user)% ➢ Root user default
prompt is root@abhishekaslk(user):~#

Let's create a simple script in bash that outputs Hello World.


1. Create a file using a vi editor (or any other editor). Name script file
with extension .sh
2. Start the script with #! /bin/sh 3. Write some code.
4. Save the script file as filename.sh
5. Make the script executable with command chmod +x <fileName>.
6. For executing the script type bash filename.sh
Write a Shell program to check the given number is even or odd ALGORITHM:

SEPT 1: Start the program.


STEP 2: Read the value of n.
STEP 3: Calculate „r=expr $n%2‟.
STEP 4: If the value of r equals 0 then print the number is even
STEP 5: If the value of r not equal to 0 then print the number is odd.
PROGRAM:
echo "Enter the Number"
read n r=`expr $n %
2` if [ $r -eq 0 ] then
echo "$n is Even number" else
echo "$n is Odd number" Fi

Write a Shell program to find the factorial of a number ALGORITHM:

SEPT 1: Start the program.


STEP 2: Read the value of n.
STEP 3: Calculate „i=expr $n-1‟.
STEP 4: If the value of i is greater than 1 then calculate „n=expr $n \* $i‟ and „i=expr $i – 1‟ STEP 5:
Print the factorial of the given number.

PROGRAM:
echo "Enter a Number"
read n i=`expr $n - 1` p=1
while [ $i -ge 1 ] do
n=`expr $n \* $i`
i=`expr $i - 1` done
echo "The Factorial of the given Number is $n
Questions:

1 How to check which SHELL is currently working on your system.


2 List features of BASH shell.

3 Define shell scripting?

4 4. Write one line description for


i. sudo su ii. chmod +x filename.sh

Conclusion:

Practical No.6
Title:- Write commands to check an enable module in
APACHE

Theory:

What is Server?
A server is a computer program or device that provides a service to another computer
program and its user, also known as the client. In a data center, the physical computer that
a server program runs on is also frequently referred to as a server. That machine might be
a dedicated server or it might be used for other purposes.

Hardware Server:

A hardware server refers to a physical computer system that is dedicated to providing


specific services, resources, or functionalities to other computers, known as clients, over
a network. Servers are designed to be more powerful and reliable than regular personal
computers, as they often need to handle multiple client requests simultaneously. Servers
can serve various purposes, such as hosting websites, storing files, running applications,
managing databases, and more.

Software Server:

In the context of software, a server refers to a program or a piece of software that


provides specific services to other software or devices. This can include web servers,
database servers, email servers, and more. These software servers run on hardware
servers and respond to client requests, allowing clients to access the services they
provide.

In the context of your previous question regarding Apache, the term "server" typically
refers to the Apache HTTP Server software, which is a widely used open-source web
server software that serves web content (such as HTML pages, images, and other
resources) to clients (usually web browsers) over the internet or an intranet.

Here's how the basic process of a web server works:

1. Client Request: A user opens a web browser and enters a URL or clicks on a link,
which triggers a request for a specific web resource (like a webpage).

2. DNS Resolution: The URL is translated into an IP address using the Domain Name
System (DNS), which identifies the server that hosts the requested resource.

3. Connection Establishment: The user's browser connects to the IP address using the
HTTP (Hypertext Transfer Protocol) or HTTPS (HTTP Secure) protocol.
4. Request Handling: The web server receives the client's request, which typically
includes the requested resource and other relevant information, such as the type of
browser being used.

5. Processing and Response: The web server processes the request, which might involve
accessing databases, executing scripts, or gathering data. It then generates an
appropriate response, which usually includes the requested resource and additional
metadata.
6. Sending Response: The server sends the response back to the user's browser over the
established connection.

7. Rendering: The user's browser receives the response and renders the web content,
displaying it on the screen for the user to interact with.

Common web servers include Apache HTTP Server, Nginx, Microsoft Internet
Information Services (IIS), and LiteSpeed. These servers are responsible for efficiently
managing and serving web content, as well as handling various aspects of security, load
balancing, and scalability to ensure smooth user experiences.

In addition to delivering static content, web servers can also handle dynamic content
generation by interfacing with application servers, databases, and other backend systems
to create personalized and interactive web experiences.

• Here's a step-by-step guide to installing Apache on a typical Linux distribution (like


Ubuntu):

1. Open a Terminal:

Open a terminal window. You can usually do this by searching for "Terminal" in your
system's application launcher.

2. Update Package Repository:

Before installing any software, it's a good idea to update the package repository to ensure
you're getting the latest packages. Run the following command:

Bash sudo apt


update

3. Install Apache:
Use the package manager to install Apache. In the terminal, enter the following
command:

bash
sudo apt install apache2
This will start the installation process for Apache. You might be asked for your sudo
password.

4. Start Apache Service:


After the installation is complete, you can start the Apache service using the following
command:

bash
sudo systemctl start apache2

5. Enable Apache to Start at Boot:


To ensure that Apache starts automatically whenever you boot your system, run:

bash
sudosystemctl enable apache2

6. Check Apache Status:


You can check the status of the Apache service to make sure it's running properly:

bash
sudosystemctl status apache2

This will display information about the Apache service, including whether it's active and
running.

7. Access Apache Default Page:


Open a web browser and enter your server's IP address or `localhost` in the address bar. You
should see the default Apache welcome page, which confirms that Apache is installed and
running.

That's it! You've successfully installed Apache on your Linux system. You can now start
configuring Apache to host websites, set up virtual hosts, and more.

1. List Loaded Modules:


To list all loaded modules in Apache, you can use the following command:
bash httpd -M

This will display a list of all modules currently loaded and enabled in your Apache
configuration.

2. Check if a Specific Module is Loaded:


If you want to check if a specific module is loaded, you can use the `grep` command
along with `httpd -M`. For example, to check if the `mod_rewrite` module is loaded, you
can use:
bash
httpd -M | grep mod_rewrite

If the module is loaded, you'll see its name in the output.

3. Check Module Configuration:*


If you want to see the configuration settings for a specific module, you can use the
following command:
bash
httpd -M -c "LoadModulemodulename_module path/to/module.so"

Replace `modulename_module` with the appropriate module name and


`path/to/module.so` with the actual path to the module's `.so` file.

4. Check Apache Configuration Syntax:*


To make sure your Apache configuration file is error-free, you can use the following
command:

bash
httpd -t

This command will check the syntax of your configuration files and report any errors.

5. Check Apache Server Status:*


If you want to see an overview of your Apache server's current status, you can use the
following command:

bash
systemctl status apache2 # On systemd-based systems

QUESTIONS:

1. Characteristics of services .
2. How to start and stop the Apache Web server?
3. What is the advantage of Apache?

4 what is the apache web server.

5. W hat is Virtual Hosting?


Conclusion:
Practical No.7
Title: - Create and insert data into table in MYSQL

Theory:

MySQL is an open-source relational database management system (RDBMS) that allows you to store,
manage, and manipulate structured data. It's one of the most widely used database systems and is known
for its performance, reliability, and ease of use. MySQL is often used for web applications, content
management systems, data warehousing, and various other types of software that require data storage and
retrieval. A MySQL table stores and organizes data in columns and rows as defined during table creation.

Installing MySQL on Linux


For almost every Linux system, the following commands are used to install MySQL:

Step 1: Go to the terminal using Ctrl+Alt+T. Now using the following command to install MySQL(copy
and past it in terminal).

sudo apt install mysql-


server

Then give your password and hit ENTER.


Step 2: Press “y” to continue.

It will take some time to download and install MySQL.

Step 3: To verify the installation or to know the version enter the following commands in
your Terminal. mysql --version
Step 4: Now we will set the VALIDATE PASSWORD component. sudo
mysql_secure_installation

Then press “y” to set the password. Next press “0” for the low-level password or choose as
you want to set the password.
Create a password. Then Re-enter the password, then to continue press “y” s.
Now the whole setup is done.

Step 5: To get started with MySQL go to the root directory. sudo mysql
-u root

The general syntax for creating a table in MySQL is:

CREATE TABLE [IF NOT EXISTS] table_name


( column_definition1, column_definition2,
........,
table_constraints
);

Steps to create a Table in MySQL:


Step 1: Log into the MySQL Shell.
1. Open a terminal window and log into the MySQL shell. Use either an existing
MySQL user account or log in as root. (Replace username\root with your username.)

Sudo mysql-uusername\root-p
2. Type the password for your account. The mysql> prompt indicates that you are
logged in the MySQL shell.
Free andOpenSourcesoftware-21527

CREATE DATABASE movies;

SHOW DATABASE;
Step2: Create a Database

Let’s create a movies database.

1. Create a database using the CREATE statement:


2. Next, verify that the database was created by showing a list of all databases. Use
the SHOW statement:

The terminal prints out a list of databases and information about the time it took to
perform the query:

Step3:Create a Table

We’ll create a table containing information about two movies:


FreeandOpenSourcesoftware-21527

Title Genre Director Release


year

Joker Psychological thriller Todd Phillips 2019

The Empire Strikes Back Epic space opera Irvin Kershner 1980

In the process of creating a table, you need to specify the following


information:
• Column names – We are creating the title, genre, director, and release year
columns for our table.
• Varchar of the columns containing characters – Specifies the maximum
number of characters stored in the column.
• The integer of the columns containing numbers – Defines numeric variables
holding whole numbers.
• Not null rule – Indicates that each new record must contain information for the
column.
• Primary key – Sets a column that defines a record.

1. Create a table using the CREATE command. Using the information from our
movies example, the command is:

CREATE TABLE movies (title VARCHAR(50) NOT NULL,genre


VARCHAR(30) NOT NULL, director VARCHAR(60) NOT
NULL,PRIMARY KEY(title));
Step4: Insert a data into a Table

INSERT INTO movies


VALUE("Joker","psychologicalthriller","ToddPhillips",2019);

1.Insert movie information in column order – title, genre, director, and release
year. Use the INSERT command:

2.Repeat the previous step with the second movie. Use the SELECT command
to display the table:

SELECT *FROM movies;

The terminal prints out the movie table:


QUESTIONS:
1. How to install MySQL in Linux?

2. How To Check If MySQL Is Installed On Linux.

3. How to create table in MySQL.


Conclusion:

Practical No.8 Title:


- Sort data in MYSQL.

Theory:
Sorting data is an essential aspect of database management. The `ORDER BY`
clause in SQL allows you to sort the result set of a query based on one or more
columns. This practical will guide you through the process of sorting data in
MySQL.

1. Connect to the MySQL Server:


Open a terminal or a MySQL client (such as MySQL Workbench) and connect to
your MySQL server using appropriate credentials.
2. Select the Database:
Choose the database where your data is stored. Use the following command:

3. View Initial Data:


Before sorting, let's have a look at the initial data in the table. You can use a
simple `SELECT` statement without the `ORDER BY` clause to retrieve the
data:
SELECT * FROM your_table_name;

4. Sort Data in Ascending Order:


To sort data in ascending order, use the `ORDER BY` clause along with the
column(s) you want to sort by. For instance, to sort by a column named
`column name` in ascending order:
SELECT * FROM your_table_name
ORDER BY column_name;
5. Sort Data in Descending Order:
To sort data in descending order, add the `DESC` keyword after the column name
in the `ORDER BY` clause:
SELECT * FROM your_table_name
ORDER BY column_name DESC;

6. Sorting by Multiple Columns:


You can also sort by multiple columns by specifying them in the `ORDER BY`
clause. Data will be sorted based on the first column, and for rows with equal values
in the first column, the second column will be considered, and so on:
SELECT * FROM your_table_name
ORDER BY column1, column2;
7. Sorting with NULL Values:
By default, NULL values are usually sorted as the lowest possible value. If
you want to change this behaviour and have NULL values appear at the end
when sorting in ascending order, use the `IS NULL` condition:
SELECT * FROM your_table_name
ORDER BY column_name IS NULL, column_name

QUESTIONS:
1. What is meaning of “ORDER BY ”clause in MySQL.
2 How to sort by last 4 characters in MYSQL.

3. Differentiate between order by and group by clause in SQL.

Conclusion:
Practical No.9 Title:-
String function in MYSQL. Theory:
String Function:
String functions in MySQL can be used to perform various manipulations and operations on the
strings in a database. Using the MySQL string functions, we can perform various operations such
as concatenation, substring extraction, character case alteration, whitespace trimming, character
replacement, etc.

String Functions in MYSQL :

1. ASCII:
Returns the numeric value of the leftmost character of the string str. Returns 0 if str is the
empty string. Returns NULL if str is NULL. ASCII() works for characters with numeric
values from 0 to 255
2. BIN(N):
Returns a string representation of the binary value of N, where N is a longlong (BIGINT)
number. This is equivalent to CONV(N,10,2). Returns NULL if N is NULL

3. BIT_LENGTH(str):
Returns the length of the string str in bits.

4. CHAR_LENGTH(str):
Returns the length of the string str, measured in characters. A multi-byte character counts as a
single character. This means that for a string containing five two-byte characters, LENGTH()
returns 10, whereas CHAR_LENGTH() returns 5.
5. CHAR(N,… [USING charset_name]):
CHAR() interprets each argument N as an integer and returns a string consisting of the
characters given by the code values of those integers. NULL values are skipped

6. REPLACE(str,from_str,to_str):
Returns the string str with all occurrences of the string from_str replaced by the string to_str.
REPLACE() performs a case-sensitive match when searching for from_str.

7. CONCAT(str1,str2,…):
Returns the string that results from concatenating the arguments. May have one or more
arguments.

8. INSERT(str,pos,len,newstr):
Returns the string str, with the substring beginning at position pos and len characters long
replaced by the string newstr. Returns the original string if pos is not within the length of the
string. Replaces the rest of the string from position pos if len is not within the length of the
rest of the string. Returns NULL if any argument is NULL.
9. LOWER(str):
Returns the string str with all characters changed to lowercase according to the current
character set mapping.

10. UPPER(str):
Returns the string str with all characters changed to uppercase according to the current
character set mapping.

QUESTIONS:
1. What is the advantage of string function?
2. List any four string functions.

3. Explain strlen(),str_word_count()
Conclusion:
Practical No.10 Title:- Write a simple PHP
program displaying sum of digits.

Theory:
Introduction to PHP:

PHP stands for “PHP: Hypertext Preprocessor” where “Preprocessor” means that
changes happen before the HTML page is created. This converts static webpage to
dynamic webpage with the capacity to interact with databases. The PHP
programming language is commonly
used for developing web-based software applications. However, use of the language
is not limited to web development and it can also be used for developing GUI
applications. As per netcraft.com in 2013, PHP found application in over 244
million websites..
PHP Syntax :
A PHP script is executed on the server, and the plain HTML result is sent back to the
browser.
Basic PHP Syntax :
A PHP script can be placed anywhere in the document.
A PHP script starts with <?php and ends with ?>:
<!DOCTYPE html>
<html>
<body>
<?PHP
// php code is here
?>
</html>
</body>
The default file extension for PHP files is ".php".
A PHP file normally contains HTML tags, and some PHP scripting code.
Features of PHP:
It is most popular and frequently used world wide scripting language, the main
reason of popularity is; It is open source and very simple.
• Simple
• Faster
• Interpreted
• Open Source
• Case Sensitive
• SimplicityFree and Open Sourcesoftware - 21527
• Efficiency
• Platform Independent
• Security
• Flexibility
• Familiarity
• Error Reporting
• Loosely Typed Language
• Real-Time Access Monitoring

Advantages of PHP :
1. The most important advantage of PHP is that it’s open-source and free from
cost. It can be downloaded anywhere and is readily available to use for
events or web applications.
2. It is platform-independent. PHP-based applications can run on any OS like
UNIX, Linux, Windows, etc.
3. Applications can easily be loaded which are based on PHP and connected to
the database. It’s mainly used due to its faster rate of loading over slow
internet speed than other programming language.
4. It has less learning curve because it is simple and straightforward to use.
Someone familiar with C programming can easily work on PHP.
5. It is more stable for a few years with the assistance of providing continuous

support to various versions.


Disadvantages of PHP :
1. It is not that secure due to its open-source, because the ASCII text file is often
easily available.
2. It is not suitable for giant content-based web applications.
3. It has a weak type, which can cause incorrect data and knowledge to users. 4. PHP
frameworks got to learn to use PHP built-in functionalities to avoid writing
additional code.
5. Using more features of PHP framework and tools cause poor performance of

online applications.
PHP variable :
A variable can have a short name (like x and y) or a more descriptive name (age,
carname, total_volume).Free and Open Sourcesoftware - 21527 Rules for PHP
variables:
• A variable starts with the $ sign, followed by the name of the variable
• A variable name must start with a letter or the underscore character
• A variable name cannot start with a number
• A variable name can only contain alpha-numeric characters and underscores
(A-z, 0-9, and _ )

• Variable names are case-sensitive ($age and $AGE are two different variables).
PHP Data Types :
Variables can store data of different types, and different data types can do different
things.
PHP supports the following data types:
• String
• Integer
• Float (floating point numbers - also called double)
• Boolean
• Array
• Object
• NULL
• Resource

Simple PHP Program for finding sum of digits in a number :


<!DOCTYPE html>
<html>
<body> <?PHP function
sumOfDigits ($number){
$sum =0; while($number!=0)
{
$digit =$number % 10; //Get the last digit
$sum +=$digit; //Add the digit to the sum
$number =(int) ($number / 10); //remove the last digit
} return $sum;Free and Open Sourcesoftware -
21527
}
//prompt the user to enter a number echo
“Enter the number “;
$number =123; // Read the user’s input as an integer
$result =sumOfDigits($number); echo “ The Sum of all
digits in ”. $number .” is”. $result ;
?>
</body >
</html>

Questions :

1. Define PHP with its syntax.

2. Write Advantages of PHP .

3. Enlist all Data types in PHP.


4. Define variable in PHP.

5. Write a PHP program for displaying Fibonacci series .


Conclusion :
Practical No.11
Title:- Write a PHP program for handling strings.
Theory:
A string is a collection of characters. String is one of the data types supported by
PHP.
The string variables can contain alphanumeric characters. Strings are created
when;
• You declare variable and assign string characters to it
• You can directly use PHP Strings with echo statement.
• PHP String functions are language construct, it helps capture words.
• Learning how strings work in PHP and how to manipulate them will make
you a very effective and productive developer.

PHP Create Strings Using Double quotes with Example


The double quotes are used to create relatively complex strings compared to
single quotes.
Variable names can be used inside double quotes and their values will be
displayed.
Let’s look at an example.
<?php
$name='Alicia';
echo "$name is friends with kalinda";
?>
HERE,
• The above example creates a simple string with the value of Alicia.
• The variable name is then used in the string created using double quotes
and its value is interpolated at run time.
Output:
Alicia is friends with kalinda

PHP String Function Examples


String functions in PHP are used to manipulate string values.
1. Strtolower : Used to convert all string characters to lower case letters
echo strtolower( ‘Benjamin’); outputs: benjamin
2. Strtoupper: Used to convert all string characters to upper case letters
echo strtoupper(‘george w bush’);
outputs:GEORGE W BUSH
3. Strlen: The string length function is used to count the number of
character in a string. Spaces in between characters are also counted
echo strlen(‘united states of america’);
24

4. Substr: Used to return part of the string. It accepts three (3) basic
parameters. The first one is the string to be shortened, the second
parameter is the position of the starting point, and the third parameter is
the number of characters to be returned.
$my_var = ‘This is a really long sentence that I wish to cut short’;echo
substr($my_var,0, 12).’…’;
This is a re…
5. str_replace: Used to locate and replace specified string values in a
given string. The The function accepts three arguments. The first
argument is the text to be replaced, the second argument is the
replacement text and the third argument is the text that is analyzed.
echo str_replace (‘the’, ‘that’, ‘the laptop is very expensive’);
that laptop is very expensive
6. str_word_count: Used to count the number of words in a string. echo
str_word_count (‘This is a really long sentence that I wish to cut
short’);
12

7. ucfirst: Make the first character of a string value upper case echo
ucfirst(‘respect’); Outputs Respect

8. lcfirst: Make the first character of a string value lower case echo
lcfirst(‘RESPECT’); Outputs rESPECT
9.strcmp($str1, $str2)
This function is used to compare two strings. The comparison is done
alphabetically. If the first string is greater than second string, the result
will be greater than 0, if the first string is equal to the second string, the
result will be equal to 0 and if the second string is greater than the first
string, then the result will be less than 0.

<?php

$str1 = "Studytonight";
$str2 = "Studytonight.com";
// comparing str1 and str2
echo strcmp($str1, $str2);

// comparing str2 and str1


echo strcmp($str2,
$str1); // comparing str1
with str1 echo
strcmp($str1, $str1);

?>

10.strrev($str)
This function is used to reverse a string.
Let's take an example and see,

<?php

$str = "Welcome to Studytonight";

// using strrev in echo method


echo "Reverse: ". strrev($str);

?>

Output: Reverse: thginotydutS ot emocleW


Questions:

Q.1. .What is the difference between print and echo in php?

Q.2. What is String in PHP?


Q.3. What is the use of strpos in PHP?

Q.4. What is TRIM function in PHP?

Conclusion
Practical No.12
Title: - Write a PHP program for cookies and session handling.

Theory:

Cookies:
Cookies are small pieces of data that a web server sends to a user's web browser, and the
Browser stores them locally. Cookies are used to store information that can be retrieved by the
web server on subsequent visits. They serve several purposes:

User Tracking: Cookies are often used to track user behavior and sessions. They can store
Information like user IDs, preferences, or shopping cart contents.
Remembering User Information:
Cookies can remember login credentials or user preferences, allowing users to stay logged
in or have a personalized experience on a website.

Tracking Analytics:
Websites use cookies to collect data on user interactions, helping to analyze
website traffic and improve user experiences.
Targeted Advertising:
Cookies are used for targeted advertising by tracking users' browsing habits
and displaying relevant ads.

Session Handling:
Sessions are a server-side mechanism for maintaining stateful information about a user's
interaction with a website. Unlike cookies, which are stored on the user's device, session data
is stored on the web server. Here's how session handling works:
Session Initialization: When a user visits a website, a unique session ID is generated for that
user. This session ID is often stored in a cookie on the user's device.

Server-Side Storage: Session data, including user-specific information, is stored on the web
server. The session ID allows the server to associate incoming requests with the correct session
data.

Data Retrieval and Updates: As the user interacts with the website, the server retrieves and
updates session data as needed. This allows the website to maintain state, such as login status
or items in a shopping cart, across multiple page views.
Session Termination: Sessions typically have a timeout period, and when a user is inactive for
too long or logs out, the session is terminated. Session data is cleared from the server.
Free and Open Source software - 21527
Here's a step-by-step guide and code example:
Step 1: Create a PHP login form (index.php)
<!DOCTYPE html>
<html>
<head>
<title>Login Page</title>
</head>
<body>
<?php
// Check if the user is already logged in, redirect to dashboard if
yes session_start(); if (isset($_SESSION['username']))
{ header("Location: dashboard.php");
exit();
}
// Check if the login form is submitted if
(isset($_POST['login'])) {
$username = $_POST['username'];
$password = $_POST['password'];
// You should replace this with your own user authentication logic if
($username === 'your_username' && $password === 'your_password') {
// Set session variables
$_SESSION['username'] = $username; Free
and Open Source software - 21527 // Remember
the user with a cookie for 7 days
setcookie('remember_me', $username, time() + (7 * 24 * 60 * 60),
'/'); header("Location: dashboard.php"); exit(); } else {
echo "Invalid username or password.";
}
}
?>
<h2>Login</h2>
<form method="POST" action="index.php">
<label for="username">Username:</label>
<input type="text" id="username" name="username" required><br><br>
<label for="password">Password:</label>
<input type="password" id="password" name="password" required><br><br>
<input type="submit" name="login" value="Login">
</form>
</body>
</html>
Step 2: Create a dashboard (dashboard.php)
<!DOCTYPE html>
<html>
<head>
Free and Open Source software - 21527
<title>Dashboard</title>
</head>
<body> <?php
session_start();
// Check if the user is not logged in, redirect to login page
if (!isset($_SESSION['username'])) {
header("Location: index.php"); exit();
}
// Display the user's username from the session echo
"Welcome, " . $_SESSION['username'] . "!<br><br>";
// Logout button
echo '<a href="logout.php">Logout</a>';
?>
</body>
</html>

Step 3: Create a logout script (logout.php)


<?php
// Start the session session_start();
Free and Open Source software - 21527
// Unset all session variables
session_unset(); // Destroy the
session session_destroy();
// Delete the "remember_me" cookie if
(isset($_COOKIE['remember_me']))
{ setcookie('remember_me', '', time() - 3600,
'/');
}
// Redirect back to the login page
header("Location: index.php"); exit();
?>
• Write a PHP program that demonstrate use of session:1
<html>
<head>
<title>Session</title>
</head>
<body> <?php
session_start();
$_SESSION["name"]="Anil";
$_SESSION["Password"]="nil";
?>
</body>
</html>
• Write a program that demonstrate use of session:2

<html>
<head>
<title>Session</title>
</head>
<body> <?php
session_start();
echo "Welcome ".$_SESSION["name"]."<br/>"; echo
"your Password:".$_SESSION["Password"];
?>
</body>
</html> O/P:
Welcome Anil your Password: nil
• Write a program that demonstrate use of cookies: 1
<html>
<head>
<title>Examle of cookies. . !</title>
</head>
<body> <?php
setcookie("name","Anil Basantani",time()
+3600,"/","",0); setcookie("age","21",time()
+3600,"/","",0); echo "set cookies";
?>
</body>
</html> O/P:
set cookies
• Write a program that demonstrate use of cookies:2

<html>
<head>
<title>Access cookies. . !</title>
</head>
<body> <?php echo
$_COOKIE["name"]."<br/>";
echo $_COOKIE["age"]."<br/>";
?>
</body>
</html> O/P:
Anil Basantani 21

Questions:

Q.1. what is cookies?

Q.2. Explain Session Handling in short?

Q.3. Explain any two purpose of cookies?

Q.4. Enlist the steps of working of session handling.


Conclusion

You might also like