Fos Final PDF - Removed
Fos Final PDF - Removed
ODD SEMESTER-V
DIPLOMA PROGRAMME IN INFORMATION
TECHNOLOGY
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)
Hrs/week TH Marks
Credits
TH TU PR Paper Hrs. TH TEST TH+TEST PR OR TW TOTAL
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.
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.
Sign:
Name of Student:
Name of Student:
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:
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 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.
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:
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:
• 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
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.
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.
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.
Conclusion
Output:
WELCOME TO
GOVERNMENT
POLYNASIK.
2) wc:-
The'wc' commandhelps incountingthelines,wordsandcharactersin afile.Syntax:
-wc<fileName>
(Countswords,linesandcharacters
)
wc-l<fileName
> (Countsonlylines
)
4) sort:-
The'sort'commandsortsthefilecontentinanalphabeticalorder.Syntax:-sort<fileName>
5) grep:-
The'grep'commandstandsfor"globalregularexpressionprint".grepcommandfiltersthecontentofafilew
hichmakesoursearcheasy.
Syntax:-command|grep<searchWord>
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.
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.
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.
Option Function
touch -r To update time of one file with reference to the other file.
cat [file1 file2 and so To concatenate contents of multiple files into one.
on] > [new file name]
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
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
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
Option Function
head -n <file name> The 'head -n' option displays specified number
of lines.
Option Function
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
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
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 #.
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:
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.
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:
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:
Software Server:
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.
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.
1. Open a Terminal:
Open a terminal window. You can usually do this by searching for "Terminal" in your
system's application launcher.
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:
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.
bash
sudo systemctl start apache2
bash
sudosystemctl enable apache2
bash
sudosystemctl status apache2
This will display information about the Apache service, including whether it's active 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.
This will display a list of all modules currently loaded and enabled in your Apache
configuration.
bash
httpd -t
This command will check the syntax of your configuration files and report any errors.
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?
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.
Step 1: Go to the terminal using Ctrl+Alt+T. Now using the following command to install MySQL(copy
and past it in terminal).
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
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
SHOW DATABASE;
Step2: Create a Database
The terminal prints out a list of databases and information about the time it took to
perform the query:
Step3:Create a Table
The Empire Strikes Back Epic space opera Irvin Kershner 1980
1. Create a table using the CREATE command. Using the information from our
movies example, the command is:
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:
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.
QUESTIONS:
1. What is meaning of “ORDER BY ”clause in MySQL.
2 How to sort by last 4 characters in MYSQL.
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.
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
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
Questions :
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);
?>
10.strrev($str)
This function is used to reverse a string.
Let's take an example and see,
<?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>
<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: