Open Source Sotware
Open Source Sotware
COLLEGE
(Affiliated to Andhra University)
Pendurthi, Visakhapatnam - 531173
"Source code" is the part of software that most computer users don't ever see; it's the code
computer programmers can manipulate to change how a piece of software—a "program" or
"application"—works. Programmers who have access to a computer program's source code
can improve that program by adding features to it or fixing parts that don't always work
correctly.
Only the original authors of proprietary software can legally copy, inspect, and alter that
software. And in order to use proprietary software, computer users must agree (usually by
signing a license displayed the first time they run this software) that they will not do anything
with the software that the software's authors have not expressly permitted. Microsoft Office
and Adobe Photoshop are examples of proprietary software.
Open source software is different. Its authors make its source code available to others who
would like to view that code, copy it, learn from it, alter it, or share it. LibreOffice and the
GNU Image Manipulation Program are examples of open source software.
As they do with proprietary software, users must accept the terms of a license when they use
open source software—but the legal terms of open source licenses differ dramatically from
those of proprietary licenses.
Open source licenses affect the way people can use, study, modify, and distribute software. In
general, open source licenses grant computer users permission to use open source software
for any purpose they wish. Some open source licenses—what some people call "copyleft"
licenses—stipulate that anyone who releases a modified open source program must also
release the source code for that program alongside it. Moreover, some open source licenses
stipulate that anyone who alters and shares a program with others must also share that
program's source code without charging a licensing fee for it.
Open source software can have a major impact on your entire organization. There are several
advantages of using open source software. The following are a list of the advantages of
opting for open source software.
2. High-quality software
Open source software is mostly high-quality software. When you use the open source
software, the source code is available. Most open source software are well-designed.
Open source software can also be efficiently used in coding. These reasons make open
source software an ideal choice for organizations.
3. No vendor lock-in
IT managers in organizations face constant frustration when dealing with vendor lock-
ins'. Lack of portability, expensive license fees and inability to customize software are
some of the other disadvantages. Using open source software gives you more freedom
and you can effectively address all these disadvantages.
4. Integrated management
By using open source software, you can benefit from integrated management. Open
source software uses technologies, such as, common information model (CIM) and
web based enterprise management (WBEM). These high-end technologies enable you
to integrate and combine server, application, service and workstation management.
This integration would result in efficient administration.
Open Source operating systems are released under a license where the copyright holder
allows others to study, change as well as distribute the software to other people. This can be
done for any reason. The different open source operating system available in the market are −
Cosmos
This is an open source operating system written mostly in programming language C#. Its full
form is C# Open Source Managed Operating System. Till 2016, Cosmos did not intend to be
a fully fledged operating system but a system that allowed other developers to easily build
their own operating systems. It also hid the inner workings of the hardware from the
developers thus providing data abstraction.
FreeDOS
This was a free operating system developed for systems compatible with IBM PC computers.
FreeDOS provides a complete environment to run legacy software and other embedded
systems. It can booted from a floppy disk or USB flash drive as required. FreeDos is licensed
under the GNU General Public license and contains free and open source software. So there
is no license fees required for its distribution and changes to the system are permitted.
Genode
Genode is free as well as open source. It contains a microkernel layer and different user
components. It is one of the few open source operating systems not derived from a licenced
operating system such as Unix. Genode can be used as an operating system for computers,
tablets etc. as required. It is also used as a base for virtualisation, interprocess
communication, software development etc. as it has a small code system.
Ghost OS
This is a free, open source operating system developed for personal computers. It started as a
research project and developed to contain various advanced features like graphical user
interface, C library etc. The Ghost operating system features multiprocessing and
multitasking and is based on the Ghost Kernel. Most of the programming in Ghost OS is done
in C++.
ITS
The incompatible time-sharing system was developed by the MIT Artificial Intelligence
Library. It is principally a time sharing system. There is a remote login facility which allowed
guest users to informally try out the operating system and its features using ARPAnet. ITS
also gave out many new features that were unique at that time such as device independent
graphics terminal, virtual devices, inter machine file system access etc.
OSv
This was an operating system released in 2013. It was mainly focused on cloud computing
and was built to run on top of a virtual machine as a guest. This is the reason it doesn't
include drivers for bare hardware. In the OSv operating system, everything runs in the kernel
address space and there is no concept of a multi-user system.
Phantom OS
This is an operating system that is based on the concepts on persistent virtual memory and is
code oriented. It was mostly developed by Russian developers. Phantom OS is not based on
concepts of famous operating systems such as Unix. Its main goal is simplicity and
effectiveness in process management.
4. Introduction to LINUX?
Linux is a community of open-source Unix like operating systems that are based on the Linux
Kernel. It was initially released by Linus Torvalds on September 17, 1991. It is a free and
open-source operating system and the source code can be modified and distributed to anyone
commercially or noncommercially under the GNU General Public License.
Initially, Linux was created for personal computers and gradually it was used in other
machines like servers, mainframe computers, supercomputers, etc. Nowadays, Linux is also
used in embedded systems like routers, automation controls, televisions, digital video
recorders, video game consoles, smartwatches, etc. The biggest success of Linux is
Android(operating system) it is based on the Linux kernel that is running on smartphones and
tablets. Due to android Linux has the largest installed base of all general-purpose operating
systems. Linux is generally packaged in a Linux distribution.
Linux Distribution
MX Linux
Manjaro
Linux Mint
elementary
Ubuntu
Debian
Solus
Fedora
openSUSE
Deepin
Architecture of Linux
1. Kernel: Kernel is the core of the Linux based operating system. It virtualizes the
common hardware resources of the computer to provide each process with its virtual
resources. This makes the process seem as if it is the sole process running on the
machine. The kernel is also responsible for preventing and mitigating conflicts
between different processes. Different types of the kernel are:
o Monolithic Kernel
o Hybrid kernels
o Exo kernels
o Micro kernels
2. System Library: Isthe special types of functions that are used to implement the
functionality of the operating system.
3. Shell: It is an interface to the kernel which hides the complexity of the kernel’s
functions from the users. It takes commands from the user and executes the kernel’s
functions.
4. Hardware Layer: This layer consists all peripheral devices like RAM/ HDD/ CPU
etc.
5. System Utility: It provides the functionalities of an operating system to the user.
Advantages of Linux
Disadvantages of Linux
By and large, by the year 2000, operating systems designers considered scheduling to
be a solved problem… (the) year 2004 brought an end to Dennard scaling, ushered in the
multicore era and made energy efficiency a top concern in the design of computer systems.
These events once again made schedulers interesting, but at the same time increasingly more
complicated and often broken.
A thread’s weight is essentially its priority, or niceness in UNIX parlance. Threads with
lower niceness have higher weights and vice versa.
Threads are organized in a runqueue, implemented as a red-black tree, in which the threads
are sorted in the increasing order of their vruntime. When a CPU looks for a new thread to
run it picks the leftmost node in the red-black tree, which contains the thread with the
smallest vruntime.
Firstly we need per-core runqueues so that context switches can be fast. Now we have a new
problem of balancing work across multiple runqueues.
Consider a dual-core system with two runqueues that are not balanced.Suppose that one
queue has one low-priority thread and another has ten high-priority threads. If each core
looked for work only in its local runqueue, then high-priority threads would get a lot less
CPU time than the low-priority thread, which is not what we want. We could have each core
checknot only its runqueue but also the queues of other cores,but this would defeat the
purpose of per-core runqueues. Therefore, what Linux and most other schedulers do is
periodically run a load-balancing algorithm that will keep the queues roughly balanced.
MySQL is released under an open-source license. So you have nothing to pay to use
it.
MySQL is a very powerful program in its own right. It handles a large subset of the
functionality of the most expensive and powerful database packages.
MySQL uses a standard form of the well-known SQL data language.
MySQL works on many operating systems and with many languages including PHP,
PERL, C, C++, JAVA, etc.
MySQL works very quickly and works well even with large data sets.
MySQL is very friendly to PHP, the most appreciated language for web development.
MySQL supports large databases, up to 50 million rows or more in a table. The
default file size limit for a table is 4GB, but you can increase this (if your operating
system can handle it) to a theoretical limit of 8 million terabytes (TB).
MySQL is customizable. The open-source GPL license allows programmers to
modify the MySQL software to fit their own specific environments.
2. Type in the root password for this account and press Enter.
The prompt should change to show that you are in the mysql> shell.
Replace username and password with a username and password of your choice.
Alternatively, you can set up a user by specifying the machine hosting the database.
If you are working on the machine with MySQL, use username@localhost to define
the user.
If you are connecting remotely, use username@ip_address, and replace ip_address
with the actual address of the remote system hosting MySQL.
or
You can also create a user that can connect from any machine with the command:
Problem
You want to start and stop the mysql program.
Solution
Invoke mysql from your command prompt to start it, specifying any connection parameters
that may be necessary. To leave mysql, use a QUIT statement.
Discussion
To start the mysql program, try just typing its name at your command-line prompt. If mysql
starts up correctly, you’ll see a short message, followed by a mysql> prompt that indicates the
program is ready to accept queries. To illustrate, here’s what the welcome message looks like
(to save space, I won’t show it in any further examples):
% mysql
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 18427 to server version: 3.23.51-log
Type 'help;' or '\h' for help. Type '\c' to clear the buffer.
mysql>
If mysql tries to start but exits immediately with an “access denied” message, you’ll need to
specify connection parameters. The most commonly needed parameters are the host to
connect to (the host where the MySQL server runs), your MySQL username, and a password.
For example:
If you don’t have a MySQL username and password, you need to obtain permission to use the
MySQL server, as described earlier in Recipe 1.2.
The syntax and default values for the connection parameter options are shown in the
following table. These options have both a single-dash short form and a double-dash long
form.
As the table indicates, there is no default password. To supply one, use --password or -p,
then enter your password when mysql prompts you for it:
If you like, you can specify the password directly on the command line by using either -
ppassword (note that there is no space after the -p) or --password=password. I don’t
recommend doing this on a multiple-user machine, because the password may be visible
momentarily to other users who are running tools such as ps that report process information.
If you get an error message that mysql cannot be found or is an invalid command when you
try to invoke it, that means your command interpreter doesn’t know where mysql is installed.
See Recipe 1.8.
mysql> QUIT
You can also terminate the session by issuing an EXIT statement or (under Unix) by typing
Ctrl-D.
The way you specify connection parameters for mysql also applies to other MySQL
programs such as mysqldump and mysqladmin. For example, some of the actions that
mysqladmin can perform are available only to the MySQL root account, so you need to
specify name and password options for that user:
Many useful queries are quite simple and don’t specify all those things. For example, some
forms of SELECT don’t even name a table—a fact used in Recipe 1.32, which discusses how
to use mysql as a calculator. Other non-table-based queries are useful for purposes such as
checking what version of the server you’re running or the name of the current database:
Strings can be case sensitive (or not), which can affect the outcome of string
operations.
You can compare entire strings, or just parts of them by extracting substrings.
You can apply pattern-matching operations to look for strings that have a certain
structure.
This chapter discusses several useful string operations you can perform, including how to
account for whether or not strings are case sensitive.
You can create the table using the metal.sql script in the tables directory of the recipes
distribution.
Types of Strings
MySQL can operate on regular strings or binary strings. “Binary” in this context has little to
do with the presence of non-ASCII values, so it’s useful right at the outset to make a
distinction:
Binary data may contain bytes that lie outside the usual range of printable ASCII
characters.
A binary string in MySQL is one that MySQL treats as case sensitive in comparisons.
For binary strings, the characters A and a are considered different. For non-binary
strings, they’re considered the same.
A binary column type is one that contains binary strings. Some of MySQL’s column types are
binary (case sensitive) and others are not, as illustrated here:
When invoked with the days form of the second argument, MySQL treats it as an integer
number of days to be added to expr.
ADDTIME(expr1,expr2)
ADDTIME() adds expr2 to expr1 and returns the result. expr1 is a time or datetime
expression and expr2 is a time expression.
CONVERT_TZ(dt,from_tz,to_tz)
This converts a datetime value dt from the time zone given by from_tz to the time zone given
by to_tz and returns the resulting value. This function returns NULL if the arguments are
invalid.
CURDATE()
Returns the current date as a value in 'YYYY-MM-DD' or YYYYMMDD format, depending
on whether the function is used in a string or numeric context.
CURTIME()
Returns the current time as a value in 'HH:MM:SS' or HHMMSS format, depending on
whether the function is used in a string or numeric context. The value is expressed in the
current time zone.
CURRENT_TIMESTAMP and
CURRENT_TIMESTAMP()
CURRENT_TIMESTAMP and CURRENT_TIMESTAMP() are synonyms for NOW().
DATE(expr)
Extracts the date part of the date or datetime expression expr.
DATEDIFF(expr1,expr2)
DATEDIFF() returns expr1 . expr2 expressed as a value in days from one date to the other.
expr1 and expr2 are date or date-and-time expressions. Only the date parts of the values are
used in the calculation.
The INTERVAL keyword and the unit specifier are not case sensitive.
The following table shows the expected form of the expr argument for each unit value;
The values QUARTER and WEEK are available beginning with MySQL 5.0.0.
DATE_FORMAT(date,format)
Formats the date value according to the format string.
The following specifiers may be used in the format string. The .%. character is required
before format specifier characters.
DAY(date)
DAY() is a synonym for DAYOFMONTH().
DAYNAME(date)
Returns the name of the weekday for date.
DAYOFMONTH(date)
Returns the day of the month for date, in the range 0 to 31.
DAYOFWEEK(date)
Returns the weekday index for date (1 = Sunday, 2 = Monday, ., 7 = Saturday). These index
values correspond to the ODBC standard.
DAYOFYEAR(date)
Returns the day of the year for date, in the range 1 to 366.
FROM_DAYS(N)
Given a day number N, returns a DATE value.
Use FROM_DAYS() with caution on old dates. It is not intended for use with values that
precede the advent of the Gregorian calendar (1582).
FROM_UNIXTIME(unix_timestamp)
FROM_UNIXTIME(unix_timestamp,format)
Returns a representation of the unix_timestamp argument as a value in 'YYYY-MM-DD
HH:MM:SS' or YYYYMMDDHHMMSS format, depending on whether the function is used
in a string or numeric context. The value is expressed in the current time zone.
unix_timestamp is an internal timestamp value such as is produced by the
UNIX_TIMESTAMP() function.
If format is given, the result is formatted according to the format string, which is used the
same way as listed in the entry for the DATE_FORMAT() function.
HOUR(time)
Returns the hour for the time. The range of the return value is 0 to 23 for time-of-day values.
However, the range of TIME values actually is much larger, so HOUR can return values
greater than 23.
LAST_DAY(date)
Takes a date or datetime value and returns the corresponding value for the last day of the
month. Returns NULL if the argument is invalid.
MAKEDATE(year,dayofyear)
Returns a date, given year and day-of-year values. dayofyear must be greater than 0 or the
result is NULL.
MAKETIME(hour,minute,second)
Returns a time value calculated from the hour, minute and second arguments.
MICROSECOND(expr)
Returns the microseconds from the time or datetime expression expr as a number in the range
from 0 to 999999.
MONTH(date)
Returns the month for date, in the range 0 to 12.
MONTHNAME(date)
Returns the full name of the month for date.
NOW()
Returns the current date and time as a value in 'YYYY-MM-DD HH:MM:SS' or
YYYYMMDDHHMMSS format, depending on whether the function is used in a string or
numeric context. The value is expressed in the current time zone.
PERIOD_ADD(P,N)
Adds N months to period P (in the format YYMM or YYYYMM). Returns a value in the
format YYYYMM. Note that the period argument P is not a date value.
PERIOD_DIFF(P1,P2)
Returns the number of months between periods P1 and P2. P1 and P2 should be in the format
YYMM or YYYYMM. Note that the period arguments P1 and P2 are not date values.
QUARTER(date)
Returns the quarter of the year for date, in the range 1 to 4.
SECOND(time)
Returns the second for time, in the range 0 to 59.
SEC_TO_TIME(seconds)
Returns the seconds argument, converted to hours, minutes, and seconds, as a value in
'HH:MM:SS' or HHMMSS format, depending on whether the function is used in a string or
numeric context.
SUBTIME(expr1,expr2)
SUBTIME() returns expr1 . expr2 expressed as a value in the same format as expr1. expr1 is
a time or datetime expression, and expr2 is a time.
SYSDATE()
Returns the current date and time as a value in 'YYYY-MM-DD HH:MM:SS' or
YYYYMMDDHHMMSS format, depending on whether the function is used in a string or
numeric context.
mysql> SELECT SYSDATE();
+---------------------------------------------------------+
| SYSDATE() |
+---------------------------------------------------------+
| 2006-04-12 13:47:44 |
+---------------------------------------------------------+
1 row in set (0.00 sec)
TIME(expr)
Extracts the time part of the time or datetime expression expr and returns it as a string.
TIMEDIFF(expr1,expr2)
TIMEDIFF() returns expr1 . expr2 expressed as a time value. expr1 and expr2 are time or
date-and-time expressions, but both must be of the same type.
TIMESTAMP(expr), TIMESTAMP(expr1,expr2)
With a single argument, this function returns the date or datetime expression expr as a
datetime value. With two arguments, it adds the time expression expr2 to the date or datetime
expression expr1 and returns the result as a datetime value.
TIMESTAMPADD(unit,interval,datetime_expr)
Adds the integer expression interval to the date or datetime expression datetime_expr. The
unit for interval is given by the unit argument, which should be one of the following values:
FRAC_SECOND, SECOND, MINUTE, HOUR, DAY, WEEK, MONTH, QUARTER or
YEAR.
The unit value may be specified using one of keywords as shown, or with a prefix of
SQL_TSI_. For example, DAY and SQL_TSI_DAY both are legal.
TIMESTAMPDIFF(unit,datetime_expr1,datetime_expr2)
Returns the integer difference between the date or datetime expressions datetime_expr1 and
datetime_expr2. The unit for the result is given by the unit argument. The legal values for
unit are the same as those listed in the description of the TIMESTAMPADD() function.
TIME_FORMAT(time,format)
This is used like the DATE_FORMAT() function, but the format string may contain format
specifiers only for hours, minutes, and seconds.
If the time value contains an hour part that is greater than 23, the %H and %k hour format
specifiers produce a value larger than the usual range of 0..23. The other hour format
specifiers produce the hour value modulo 12.
TIME_TO_SEC(time)
Returns the time argument, converted to seconds.
TO_DAYS(date)
Given a date, returns a day number (the number of days since year 0).
UNIX_TIMESTAMP(), UNIX_TIMESTAMP(date)
If called with no argument, returns a UNIX timestamp (seconds since '1970-01-01 00:00:00'
UTC) as an unsigned integer. If UNIX_TIMESTAMP() is called with a date argument, it
returns the value of the argument as seconds since '1970-01-01 00:00:00' UTC. date may be a
DATE string, a DATETIME string, a TIMESTAMP, or a number in the format YYMMDD
or YYYYMMDD.
UTC_DATE, UTC_DATE()
Returns the current UTC date as a value in 'YYYY-MM-DD' or YYYYMMDD format,
depending on whether the function is used in a string or numeric context.
UTC_TIME, UTC_TIME()
Returns the current UTC time as a value in 'HH:MM:SS' or HHMMSS format, depending on
whether the function is used in a string or numeric context.
UTC_TIMESTAMP, UTC_TIMESTAMP()
Returns the current UTC date and time as a value in 'YYYY-MM-DD HH:MM:SS' or
YYYYMMDDHHMMSS format, depending on whether the function is used in a string or
numeric context.
WEEK(date[,mode])
This function returns the week number for date. The two-argument form of WEEK() allows
you to specify whether the week starts on Sunday or Monday and whether the return value
should be in the range from 0 to 53 or from 1 to 53. If the mode argument is omitted, the
value of the default_week_format system variable is used
WEEKDAY(date)
Returns the weekday index for date (0 = Monday, 1 = Tuesday, . 6 = Sunday).
WEEKOFYEAR(date)
Returns the calendar week of the date as a number in the range from 1 to 53.
WEEKOFYEAR() is a compatibility function that is equivalent to WEEK(date,3).
YEAR(date)
Returns the year for date, in the range 1000 to 9999, or 0 for the .zero. date.
YEARWEEK(date), YEARWEEK(date,mode)
Returns year and week for a date. The mode argument works exactly like the mode argument
to WEEK(). The year in the result may be different from the year in the date argument for the
first and the last week of the year.
We have seen the SQL SELECT command to fetch data from a MySQL table. When you
select rows, the MySQL server is free to return them in any order, unless you instruct it
otherwise by saying how to sort the result. But, you sort a result set by adding an ORDER
BY clause that names the column or columns which you want to sort.
Syntax
The following code block is a generic SQL syntax of the SELECT command along with the
ORDER BY clause to sort the data from a MySQL table.
You can sort the returned result on any field, if that field is being listed out.
You can sort the result on more than one field.
You can use the keyword ASC or DESC to get result in ascending or descending
order. By default, it's the ascending order.
You can use the WHERE...LIKE clause in the usual way to put a condition.
Example
Try out the following example, which returns the result in an ascending order.
mysql>
Verify all the author names that are listed out in the ascending order.
Example
Try out the following example, which returns the result in a descending order of the tutorial
authors.
<?php
$dbhost = 'localhost:3036';
$dbuser = 'root';
$dbpass = 'rootpassword';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn ) {
die('Could not connect: ' . mysql_error());
}
$sql = 'SELECT tutorial_id, tutorial_title,
tutorial_author, submission_date
FROM tutorials_tbl
ORDER BY tutorial_author DESC';
mysql_select_db('TUTORIALS');
$retval = mysql_query( $sql, $conn );
if(! $retval ) {
die('Could not get data: ' . mysql_error());
}
Rasmus Lerdorf inspired the first version of PHP and participating in the later versions. It is
an interpreted language and it does not require a compiler.
http://127.0.0.1/info.php
If this displays a page showing your PHP installation related information then it means you
have PHP and Webserver installed properly. Otherwise you have to follow given procedure
to install PHP on your computer.
This section will guide you to install and configure PHP over the following four platforms −
Apache Configuration
If you are using Apache as a Web Server then this section will guide you to edit Apache
Configuration Files.
The PHP configuration file, php.ini, is the final and most immediate way to affect PHP's
functionality.
All variables in PHP are denoted with a leading dollar sign ($).
The value of a variable is the value of its most recent assignment.
Variables are assigned with the = operator, with the variable on the left-hand side and
the expression to be evaluated on the right.
Variables can, but do not need, to be declared before assignment.
Variables in PHP do not have intrinsic types - a variable does not know in advance
whether it will be used to store a number or a string of characters.
Variables used before they are assigned have default values.
PHP does a good job of automatically converting types from one to another when
necessary.
PHP variables are Perl-like.
PHP has a total of eight data types which we use to construct our variables −
The first five are simple types, and the next two (arrays and objects) are compound - the
compound types can package up other arbitrary values of arbitrary type, whereas the simple
types cannot.
We will explain only simple data type in this chapters. Array and Objects will be explained
separately.
Integers
They are whole numbers, without a decimal point, like 4195. They are the simplest type .they
correspond to simple whole numbers, both positive and negative. Integers can be assigned to
variables, or they can be used in expressions, like so −
$int_var = 12345;
$another_int = -12345 + 12345;
Integer can be in decimal (base 10), octal (base 8), and hexadecimal (base 16) format.
Decimal format is the default, octal integers are specified with a leading 0, and hexadecimals
have a leading 0x.
For most common platforms, the largest integer is (2**31 . 1) (or 2,147,483,647), and the
smallest (most negative) integer is . (2**31 . 1) (or .2,147,483,647).
Doubles
They like 3.14159 or 49.1. By default, doubles print with the minimum number of decimal
places needed. For example, the code −
Live Demo
<?php
$many = 2.2888800;
$many_2 = 2.2111200;
$few = $many + $many_2;
Boolean
They have only two possible values either true or false. PHP provides a couple of constants
especially for use as Booleans: TRUE and FALSE, which can be used like so −
if (TRUE)
print("This will always print<br>");
else
print("This will never print<br>");
Here are the rules for determine the "truth" of any value not already of the Boolean type −
If the value is a number, it is false if exactly equal to zero and true otherwise.
If the value is a string, it is false if the string is empty (has zero characters) or is the
string "0", and is true otherwise.
Values of type NULL are always false.
If the value is an array, it is false if it contains no other values, and it is true otherwise.
For an object, containing a value means having a member variable that has been
assigned a value.
Valid resources are true (although some functions that return resources when they are
successful will return FALSE when unsuccessful).
Don't use double as Booleans.
Each of the following variables has the truth value embedded in its name when it is used in a
Boolean context.
$true_num = 3 + 0.14159;
$true_str = "Tried and true"
$true_array[49] = "An array element";
$false_array = array();
$false_null = NULL;
$false_num = 999 - 999;
$false_str = "";
NULL
NULL is a special type that only has one value: NULL. To give a variable the NULL value,
simply assign it like this −
$my_var = NULL;
The special constant NULL is capitalized by convention, but actually it is case insensitive;
you could just as well have typed −
$my_var = null;
A variable that has been assigned NULL has the following properties −
Strings
They are sequences of characters, like "PHP supports string operations". Following are valid
examples of string
Singly quoted strings are treated almost literally, whereas doubly quoted strings replace
variables with their values as well as specially interpreting certain character sequences.
Live Demo
<?php
$variable = "name";
$literally = 'My $variable will not print!';
print($literally);
print "<br>";
There are no artificial limits on string length - within the bounds of available memory, you
ought to be able to make arbitrarily long strings.
Strings that are delimited by double quotes (as in "this") are preprocessed in both the
following two ways by PHP −
Certain character sequences beginning with backslash (\) are replaced with special
characters
Variable names (starting with $) are replaced with string representations of their
values.
The escape-sequence replacements are −
Here Document
You can assign multiple lines to a single string variable using here document −
Live Demo
<?php
$channel =<<<_XML_
<channel>
<title>What's For Dinner</title>
<link>http://menu.example.com/ </link>
<description>Choose what to eat tonight.</description>
</channel>
_XML_;
echo <<<END
This uses the "here document" syntax to output multiple lines with
variable
interpolation. Note that the here document terminator must appear on a
line with
just a semicolon. no extra whitespace!
END;
print $channel;
?>
<channel>
<title>What's For Dinner<title>
<link>http://menu.example.com/<link>
<description>Choose what to eat tonight.</description>
Variable Scope
Scope can be defined as the range of availability a variable has to the program in which it is
declared. PHP variables can be one of four scope types −
Local variables
Function parameters
Global variables
Static variables
Variable Naming
Rules for naming a variable is −
A function is a block of code written in a program to perform some specific task. We can
relate functions in programs to employees in a office in real life for a better understanding of
how functions work. Suppose the boss wants his employee to calculate the annual budget. So
how will this process complete? The employee will take information about the statics from
the boss, performs calculations and calculate the budget and shows the result to his boss.
Functions works in a similar manner. They take informations as parameter, executes a block
of statements or perform operations on this parameters and returns the result.
PHP provides us with two major types of functions:
Reusability: If we have a common code that we would like to use at various parts of
a program, we can simply contain it within a function and call it whenever required.
This reduces the time and effort of repetition of a single code. This can be done both
within a program and also by importing the PHP file, containing the function, in some
other program
Easier error detection: Since, our code is divided into functions, we can easily
detect in which function, the error could lie and fix them fast and easily.
Easily maintained: As we have used functions in our program, so if anything or any
line of code needs to be changed, we can easily change it inside the function and the
change will be reflected everywhere, where the function is called. Hence, easy to
maintain.
Creating a Function
While creating a user defined function we need to keep few things in mind:
Syntax:
function function_name(){
executable code;
}
Example:
<?php
function funcGeek()
{
echo "This is Geeks for Geeks";
}
?>
Output:
The information or variable, within the function’s parenthesis, are called parameters. These
are used to hold the values executable during runtime. A user is free to take in as many
parameters as he wants, separated with a comma(,) operator. These parameters are used to
accept inputs during runtime. While passing the values like during a function call, they are
called arguments. An argument is a value passed to a function and a parameter is used to hold
those arguments. In common term, both parameter and argument mean the same. We need to
keep in mind that for every parameter, we need to pass its corresponding argument.
Syntax:
Example:
<?php
?>
Output:
The product is 30
PHP allows us to set default argument values for function parameters. If we do not pass any
argument for a parameter with default value then PHP will use the default set value for this
parameter in the function call.
Example:
<?php
?>
Output:
In the above example, the parameter $num has a default value 12, if we do not pass any value
for this parameter in a function call then this default value 12 will be considered. Also the
parameter $str has no default value , so it is compulsory.
Functions can also return values to the part of program from where it is called. The return
keyword is used to return value back to the part of program, from where it was called. The
returning value may be of any type including the arrays and objects. The return statement also
marks the end of the function and stops the execution after that and returns the value.
Example:
<?php
?>
Output:
The product is 30
PHP allows us two ways in which an argument can be passed into a function:
Pass by Value: On passing arguments using pass by value, the value of the argument
gets changed within a function, but the original value outside the function remains
unchanged. That means a duplicate of the original value is passed as an argument.
Pass by Reference: On passing arguments as pass by reference, the original value is
passed. Therefore, the original value gets altered. In pass by reference we actually
pass the address of the value, where it is stored using ampersand sign(&).
Example:
<?php
// pass by value
function valGeek($num) {
$num += 2;
return $num;
}
// pass by reference
function refGeek(&$num) {
$num += 10;
return $num;
}
$n = 10;
valGeek($n);
echo "The original value is still $n \n";
refGeek($n);
echo "The original value changes to $n";
?>
Output:
Operators are used to perform operations on some values. In other words, we can describe
operators as something that takes some values, performs some operation on them and gives a
result. From example, “1 + 2 = 3” in this expression ‘+’ is an operator. It takes two values 1
and 2, performs addition operation on them to give 3.
Just like any other programming language, PHP also supports various types of operations like
the arithmetic operations(addition, subtraction, etc), logical operations(AND, OR etc),
Increment/Decrement Operations etc. Thus, PHP provides us with many operators to perform
such operations on various operands or variables or values. These operators are nothing but
symbols needed to perform operations of various types. Given below are the various groups
of operators:
Arithmetic Operators
Logical or Relational Operators
Comparison Operators
Conditional or Ternary Operators
Assignment Operators
Spaceship Operators (Introduced in PHP 7)
Array Operators
Increment/Decrement Operators
String Operators
Arithmetic Operators
The arithmetic operators are use to perform simple mathematical operations like addition,
subtraction, multiplication etc. Below is the list of arithmetic operators along with there
syntax and operations, that PHP provides us:
An array is a data structure that stores one or more similar type of values in a single value.
For example if you want to store 100 numbers then instead of defining 100 variables its easy
to define an array of 100 length.
There are three different kind of arrays and each array value is accessed using an ID c which
is called array index.
Numeric array − An array with a numeric index. Values are stored and accessed in
linear fashion.
Associative array − An array with strings as index. This stores element values in
association with key values rather than in a strict linear index order.
Multidimensional array − An array containing one or more arrays and values are
accessed using multiple indices
NOTE − Built-in array functions is given in function reference PHP Array Functions
Numeric Array
These arrays can store numbers, strings and any object but their index will be represented by
numbers. By default array index starts from zero.
Example
Following is the example showing how to create and access numeric arrays.
Here we have used array() function to create array. This function is explained in function
reference.
Live Demo
<html>
<body>
<?php
/* First method to create array. */
$numbers = array( 1, 2, 3, 4, 5);
Value is 1
Value is 2
Value is 3
Value is 4
Value is 5
Value is one
Value is two
Value is three
Value is four
Value is five
Associative Arrays
The associative arrays are very similar to numeric arrays in term of functionality but they are
different in terms of their index. Associative array will have their index as string so that you
can establish a strong association between key and values.
To store the salaries of employees in an array, a numerically indexed array would not be the
best choice. Instead, we could use the employees names as the keys in our associative array,
and the value would be their respective salary.
NOTE − Don't keep associative array inside double quote while printing otherwise it would
not return any value.
Example
Live Demo
<html>
<body>
<?php
/* First method to associate create array. */
$salaries = array("mohammad" => 2000, "qadir" => 1000, "zara" =>
500);
</body>
</html>
Multidimensional Arrays
A multi-dimensional array each element in the main array can also be an array. And each
element in the sub-array can be an array, and so on. Values in the multi-dimensional array are
accessed using multiple index.
Example
In this example we create a two dimensional array to store marks of three students in three
subjects −
This example is an associative array, you can create numeric array in the same fashion.
Live Demo
<html>
<body>
<?php
$marks = array(
"mohammad" => array (
"physics" => 35,
"maths" => 30,
"chemistry" => 39
),
</body>
</html>
This will produce the following result −
Regular expressions are nothing more than a sequence or pattern of characters itself. They
provide the foundation for pattern-matching functionality.
Using regular expression you can search a particular string inside a another string, you can
replace one string by another string and you can split a string into many chunks.
PHP offers functions specific to two sets of regular expression functions, each corresponding
to a certain type of regular expression. You can use any of them based on your comfort.
The simplest regular expression is one that matches a single character, such as g, inside
strings such as g, haggle, or bag.
Lets give explanation for few concepts being used in POSIX regular expression. After that
we will introduce you with regular expression related functions.
Brackets
Brackets ([]) have a special meaning when used in the context of regular expressions. They
are used to find a range of characters.
[0-9]
1
It matches any decimal digit from 0 through 9.
[a-z]
2
It matches any character from lower-case a through lowercase z.
[A-Z]
3
It matches any character from uppercase A through uppercase Z.
[a-Z]
4
It matches any character from lowercase a through uppercase Z.
The ranges shown above are general; you could also use the range [0-3] to match any decimal
digit ranging from 0 through 3, or the range [b-v] to match any lowercase character ranging
from b through v.
Quantifiers
The frequency or position of bracketed character sequences and single characters can be
denoted by a special character. Each special character having a specific connotation. The +, *,
?, {int. range}, and $ flags all follow a character sequence.
p+
1
It matches any string containing at least one p.
p*
2
It matches any string containing zero or more p's.
p?
3
It matches any string containing zero or one p's.
p{N}
4
It matches any string containing a sequence of N p's
p{2,3}
5
It matches any string containing a sequence of two or three p's.
p{2, }
6
It matches any string containing a sequence of at least two p's.
p$
7
It matches any string with p at the end of it.
^p
8
It matches any string with p at the beginning of it.
Examples
[^a-zA-Z]
1
It matches any string not containing any of the characters ranging from a through z and
A through Z.
p.p
2
It matches any string containing p, followed by any character, in turn followed by
another p.
^.{2}$
3
It matches any string containing exactly two characters.
<b>(.*)</b>
4
It matches any string enclosed within <b> and </b>.
p(hp)*
5
It matches any string containing a p followed by zero or more instances of the sequence
php.
For your programming convenience several predefined character ranges, also known as
character classes, are available. Character classes specify an entire range of characters, for
example, the alphabet or an integer set −
[[:alpha:]]
1
It matches any string containing alphabetic characters aA through zZ.
[[:digit:]]
2
It matches any string containing numerical digits 0 through 9.
[[:alnum:]]
3
It matches any string containing alphanumeric characters aA through zZ and 0 through
9.
[[:space:]]
4
It matches any string containing a space.
ereg()
1
The ereg() function searches a string specified by string for a string specified by
pattern, returning true if the pattern is found, and false otherwise.
ereg_replace()
2
The ereg_replace() function searches for string specified by pattern and replaces pattern
with replacement if found.
eregi()
3
The eregi() function searches throughout a string specified by pattern for a string
specified by string. The search is not case sensitive.
eregi_replace()
4
The eregi_replace() function operates exactly like ereg_replace(), except that the search
for pattern in string is not case sensitive.
split()
5
The split() function will divide a string into various elements, the boundaries of each
element based on the occurrence of pattern in string.
spliti()
6
The spliti() function operates exactly in the same manner as its sibling split(), except
that it is not case sensitive.
sql_regcase()
7
The sql_regcase() function can be thought of as a utility function, converting each
character in the input parameter string into a bracketed expression containing two
characters.
Lets give explanation for few concepts being used in PERL regular expressions. After that we
will introduce you wih regular expression related functions.
Meta characters
A meta character is simply an alphabetical character preceded by a backslash that acts to give
the combination a special meaning.
For instance, you can search for large money sums using the '\d' meta character: /([\d]+)000/,
Here \d will search for any string of numerical character.
Following is the list of meta characters which can be used in PERL Style Regular
Expressions.
Character Description
. a single character
\s a whitespace character (space, tab, newline)
\S non-whitespace character
\d a digit (0-9)
\D a non-digit
\w a word character (a-z, A-Z, 0-9, _)
\W a non-word character
[aeiou] matches a single character in the given set
[^aeiou] matches a single character outside the given set
(foo|bar|baz) matches any of the alternatives specified
Modifiers
Several modifiers are available that can make your work with regexps much easier, like case
sensitivity, searching in multiple lines etc.
Modifier Description
i Makes the match case insensitive
m Specifies that if the string has newline or carriage
return characters, the ^ and $ operators will now
match against a newline boundary, instead of a
string boundary
o Evaluates the expression only once
s Allows use of . to match a newline character
x Allows you to use white space in the expression for clarity
g Globally finds all matches
cg Allows a search to continue even after a global match fails
preg_match()
1
The preg_match() function searches string for pattern, returning true if pattern exists,
and false otherwise.
preg_match_all()
2
The preg_match_all() function matches all occurrences of pattern in string.
preg_replace()
3
The preg_replace() function operates just like ereg_replace(), except that regular
expressions can be used in the pattern and replacement input parameters.
preg_split()
4
The preg_split() function operates exactly like split(), except that regular expressions
are accepted as input parameters for pattern.
preg_grep()
5
The preg_grep() function searches all elements of input_array, returning all elements
matching the regexp pattern.
PC Magazine announced Perl as the finalist for its 1998 Technical Excellence Award in the
Development Tool category.
Perl Features
Perl takes the best features from other languages, such as C, awk, sed, sh, and BASIC,
among others.
Perls database integration interface DBI supports third-party databases including
Oracle, Sybase, Postgres, MySQL and others.
Perl works with HTML, XML, and other mark-up languages.
Perl supports Unicode.
Perl is Y2K compliant.
Perl supports both procedural and object-oriented programming.
Perl interfaces with external C/C++ libraries through XS or SWIG.
Perl is extensible. There are over 20,000 third party modules available from the
Comprehensive Perl Archive Network (CPAN).
The Perl interpreter can be embedded into other systems.
Perl is Interpreted
Perl is an interpreted language, which means that your code can be run as is, without a
compilation stage that creates a non portable executable program.
Traditional compilers convert programs into machine language. When you run a Perl
program, it's first compiled into a byte code, which is then converted ( as the program runs)
into machine instructions. So it is not quite the same as shells, or Tcl, which are strictly
interpreted without an intermediate representation.
It is also not like most versions of C or C++, which are compiled directly into a machine
dependent format. It is somewhere in between, along with Python and awk and Emacs .elc
files.
Overview
Perl is a programming language used widely in the UNIX/Linux world to write everything
from quick scripts to powerful, broad-featured programs. The following is a description from
the perlintro man page:
What is Perl?
The language is intended to be practical (easy to use, efficient, complete) rather than beautiful
(tiny, elegant, minimal). Its major features are that it's easy to use, supports both procedural
and object-oriented (OO) programming, has powerful built-in support for text processing, and
has one of the world's most impressive collections of third-party modules.
Different definitions of Perl are given in perl, perlfaq1 and no doubt other places. From this
we can determine that Perl is different things to different people, but that lots of people think
it's at least worth writing about.
History
Perl was created in the mid-1980s by Larry Wall. Its original intent was to fill in the gap
between so-called "low-level" languages like C and C++, and the higher level scripting
languages like awk, sed, and shell scripts. It has evolved considerably since then, becoming
the de facto language of choice for many *nix system administrators and power users. It has
found broad appeal on the Internet (a mostly *nix based network) as the background code
behind many sites on the World Wide Web. A notable example is Slashdot.
Perl on DreamHost
Path to the Perl interpreter
The path to Perl on DreamHost's servers is shown below. This path is standard on *nix based
systems and most scripts should not need to be modified.
/usr/bin/perl
mod_perl is currently not supported at DreamHost. You must use FastCGI instead.
As with Python and PHP, you can build another version in your user's home directory if
necessary. However, most Perl programs should work fine with the installed version.
You can also install a custom version of Perl under your username. View the following article
for instructions:
DreamHost has nearly all the common Perl modules installed, as well as many uncommon
ones.
To check whether a Perl module is installed on DreamHost's servers, log into your shell
account, and then type the following:
where The::Module::Name is the name of the Perl module you are looking for.
The command outputs nothing when the module is found. If it's not found, an error is thrown.
You can install your own modules in your user's home directory. Follow these DreamHost
specific instructions for installing CPAN modules.
Perl FastCGI
To test if FastCGI is configured and working properly, try this simple 'Hello World' program.
Paste this text into a file with the ending .fcgi. Make sure to change username to your Shell
user.
#!/usr/bin/perl
my $counter = 0;
while ( FCGI::accept() >= 0 ) {
$counter++;
print
"Content-Type: text/plain",
$CRLF,
$CRLF,
"Hello World, in Perl FastCGI!",
$CRLF,
"I am process $$.",
$CRLF,
"I have served $counter request(s).",
$CRLF;
}
The $CRLF is a server-neutral line ending equivalent to "\015\012." It will always work. "\n"
or even "\r\n" sometimes will not.
If you change the extension of this script to .pl or .cgi so it's handled by regular CGI, you'll
notice that the PID is different on every request, and the request counter stays at 1.
Debugging
DreamHost runs suexec and requires that all cgi scripts and the directories in which they
reside not be writable by anyone but the owner (i.e., user). This means that you must change
the permissions of the script using chmod (see the following example):
24 . Perl Variables
Variables in Perl are used to store and manipulate data throughout the program. When a
variable is created it occupies memory space. The data type of a variable helps the interpreter
to allocate memory and decide what to be stored in the reserved memory. Therefore,
variables can store integers, decimals, or strings with the assignment of different data types to
the variables.
Naming of a Variable
A variable in Perl can be named anything with the use of a specific datatype. There are some
rules to follow while naming a variable:
It starts with $, @ or % as per the datatype required, followed by zero or more letters,
underscores and digits
Variables in Perl cannot contain white spaces or any other special character except
underscore.
Example:
$my-name = "John"; // Invalid
$my name = "John"; // Invalid
$my_name = "John"; // Valid
Declaration of a Variable
Variable Declaration is done on the basis of the datatype used to define the variable. These
variables can be of three different datatypes:
Scalar Variables: It contains a single string or numeric value. It starts with $ symbol.
Example:
$item = "Hello"
$item_one = 2
Example:
Hash Variables: It contains (key, value) pair efficiently accessed per key. It starts
with % symbol.
Example:
Modification of a Variable
Perl allows to modify its variable values anytime after the variable declaration is done. There
are various ways for the modification of a variable:
Variable Interpolation
Perl provides various methods to define a String to a variable. This can be done with the use
of single quotes, double quotes, using q-operator and double-q operator, etc.
Using single quotes and double quotes for writing strings is same but there exists a slight
difference between how they work. Strings which are written with the use of single quotes
display the content written within it exactly as it is.
Example:
$name = "John"
print 'Hi $name\nHow are you?'
Whereas strings written within double quotes replace the variables with their value and then
displays the string. It even replaces the escape sequences by their real use.
Example:
$name = "John"
print "Hi $name\nHow are you?"
Hi John
How are you?
Example Code:
#!/usr/bin/perl
use Data::Dumper;
# Scalar Variable
$name = "GeeksForGeeks";
# Array Variable
@array = ("G", "E", "E", "K", "S");
# Hash Variable
%Hash = ('Welcome', 10, 'to', 20, 'Geeks', 40);
# Variable Modification
@array[2] = "F";
# Interpolation of a Variable