Web servers are fundamental components of the internet infrastructure, responsible for hosting and delivering web content and applications to users worldwide. Understanding the different types of web servers and development environments is crucial for developers and system administrators alike.
Development environments play a crucial role in the software development lifecycle, providing developers with tools and resources to create, test, and debug web applications effectively. These environments often include web servers, databases, scripting languages, and other development tools necessary for building and deploying web projects.
Following are the development environment stacks commonly used:
<? php
echo "PHP";
?>
abc.php
) or place an existing PHP file in this
directory.http://localhost/abc.php
(replace
abc.php
with your PHP file name).
http://localhost:8080/abc.php
).
Example:
<?php
echo "Hello World";
?>
In PHP, a variable is declared using a $ sign followed by the variable name. Here are some important points to know about variables:
Syntax of declaring a variable in PHP is given below:
$variablename = value;
Let's see the example to store string, integer, and float values in PHP variables.
<?php
$str = "hello string";
$x = 200;
$y = 44.6;
echo "string is: $str
";
echo "integer is: $x
";
echo "float is: $y
";
?>
<?php
$num1 = 5;
$num2 = 4;
$sum = $num1 + $num2;
echo "The sum is = $sum";
?>
In PHP, data types are used to specify the type of data that variables can hold. PHP supports various data types, each with its own characteristics and usage.
' '
) or double quotes (" "
).PHP is a loosely typed language known for dynamic typing, meaning you don't need to declare the data type explicitly. PHP determines the data type based on the value assigned to the variable.
$integerVar = 10; // Integer
$floatVar = 3.14; // Float
$stringVar = "Hello, PHP!"; // String
$boolVar = true; // Boolean
$arrayVar = array(1, 2, 3); // Array
$objectVar = new stdClass(); // Object
$nullVar = null; // Null
You can also explicitly convert data types using type casting. For example:
$intValue = (int) 10.5; // Converts float to integer (10)
$floatValue = (float) "3.14"; // Converts string to float (3.14)
$stringValue = (string) 100; // Converts integer to string ("100")
$boolValue = (bool) ""; // Converts empty string to boolean (false)
Control statements in PHP are used to control the flow of execution in a program. They allow you to make decisions, repeat actions, and perform different tasks based on conditions.
Conditional statements are used to execute code based on certain conditions. PHP supports the following conditional statements:
Let's see examples of each control statement:
$age = 25;
if ($age >= 18) {
echo "You are eligible to vote.";
}
$marks = 85;
if ($marks >= 60) {
echo "You passed.";
} else {
echo "You failed.";
}
$score = 85;
if ($score >= 90) {
echo "Excellent!";
} elseif ($score >= 70) {
echo "Good!";
} else {
echo "Needs improvement.";
}
$day = "Monday";
switch ($day) {
case "Monday":
echo "Today is Monday.";
break;
case "Tuesday":
echo "Today is Tuesday.";
break;
default:
echo "Invalid day.";
}
Looping statements are used to execute a block of code repeatedly as long as a specified condition is true. PHP supports the following looping statements:
Let's see examples of each loop:
$num = 1;
while ($num <= 5) {
echo "Number: $num<br>";
$num++;
}
$num = 1;
do {
echo "Number: $num<br>";
$num++;
} while ($num <= 5);
for ($i = 1; $i <= 5; $i++) {
echo "Number: $i<br>";
}
$fruits = array("Apple", "Banana", "Orange", "Mango");
foreach ($fruits as $fruit) {
echo "$fruit<br>";
}
Arrays in PHP allow you to store multiple values in a single variable. PHP supports several types of arrays:
An indexed array stores elements with numeric indices. Elements are accessed using their index numbers.
$colors = array("Red", "Green", "Blue");
echo $colors[0]; // Outputs: Red
echo $colors[1]; // Outputs: Green
echo $colors[2]; // Outputs: Blue
An associative array stores elements with named keys. Elements are accessed using their keys.
$person = array("name" => "John", "age" => 30, "city" => "New York");
echo $person["name"]; // Outputs: John
echo $person["age"]; // Outputs: 30
echo $person["city"]; // Outputs: New York
A multidimensional array contains one or more arrays. It is used to store arrays within an array.
$students = array(
array("name" => "John", "age" => 20),
array("name" => "Jane", "age" => 22),
array("name" => "Doe", "age" => 25)
);
echo $students[0]["name"]; // Outputs: John
echo $students[1]["age"]; // Outputs: 22
$students = array(
array("John", 20),
array("Jane", 22),
array("Doe", 25)
);
echo $students[0][0]; // Outputs: John
echo $students[1][1]; // Outputs: 22
PHP provides built-in functions to work with arrays, such as count() to count elements in an array and array_push() to add elements to an array.
$fruits = array("Apple", "Banana", "Orange");
echo count($fruits); // Outputs: 3
array_push($fruits, "Mango");
print_r($fruits); // Outputs: Array ( [0] => Apple [1] => Banana [2] => Orange [3] => Mango )
Strings in PHP are sequences of characters, which can include letters, numbers, symbols, and spaces. PHP provides various functions and methods to manipulate and work with strings.
Concatenation is the process of combining strings. In PHP, the dot (.) operator is used for concatenation.
$name = "John";
$greeting = "Hello, " . $name . "!";
echo $greeting; // Outputs: Hello, John!
The strlen() function is used to get the length of a string in PHP.
$text = "This is a string.";
echo strlen($text); // Outputs: 16 (including spaces)
The substr() function is used to extract a part of a string.
$text = "Hello World";
$substring = substr($text, 0, 5); // Extracts "Hello"
echo $substring;
PHP provides functions like strtolower() and strtoupper() to change the case of strings.
$text = "Hello World";
echo strtolower($text); // Outputs: hello world
echo strtoupper($text); // Outputs: HELLO WORLD
The str_replace() function is used to replace a substring with another substring in a string.
$text = "Hello World";
$newText = str_replace("World", "PHP", $text);
echo $newText; // Outputs: Hello PHP
PHP provides functions like explode() and implode() to split and join strings based on delimiters.
$text = "apple,banana,orange";
$fruitsArray = explode(",", $text); // Splits the string into an array
print_r($fruitsArray); // Outputs: Array ( [0] => apple [1] => banana [2] => orange )
$fruitsString = implode(", ", $fruitsArray); // Joins the array elements into a string
echo $fruitsString; // Outputs: apple, banana, orange
A function in PHP is a block of reusable code that performs a specific task. Functions help in organizing code, improving readability, and reducing redundancy. Here's how you declare and use functions in PHP:
<?php
function functionName($param1, $param2, ...) {
// Function body
// Code to be executed when the function is called
return $returnValue; // Optional: return value
}
?>
Let's break down the components of a PHP function:
<?php
function calculateSum($num1, $num2) {
$sum = $num1 + $num2;
return $sum;
}
$number1 = 10;
$number2 = 5;
$result = calculateSum($number1, $number2);
echo "The sum of $number1 and $number2 is: $result";
?>
In this example, the calculateSum function takes two parameters and returns their sum.
<?php
function checkEvenOdd($number) {
if ($number % 2 == 0) {
return "Even";
} else {
return "Odd";
}
}
$inputNumber = 15;
$result = checkEvenOdd($inputNumber);
echo "$inputNumber is $result";
?>
This example demonstrates a function that checks whether a number is even or odd.
<?php
function greetUser($name = "Guest") {
echo "Hello, $name!";
}
greetUser(); // Outputs: Hello, Guest!
greetUser("John"); // Outputs: Hello, John!
?>
Here, the greetUser function has a default parameter value, allowing it to be called without an argument.
Variable scope refers to the visibility and accessibility of variables within different parts of a PHP script. Understanding variable scope is crucial for writing efficient and bug-free code. Here are the key aspects of PHP variable scope:
Variables declared within a function have local scope and can only be accessed within that function.
<?php
function myFunction() {
$localVariable = "This is a local variable.";
echo $localVariable;
}
myFunction(); // Outputs: This is a local variable.
echo $localVariable; // Error: Undefined variable
?>
Variables declared outside of any function have global scope and can be accessed from anywhere within the
script. To access a global variable inside a function, use the global
keyword.
<?php
$globalVariable = "This is a global variable.";
function myFunction() {
global $globalVariable;
echo $globalVariable;
}
myFunction(); // Outputs: This is a global variable.
echo $globalVariable; // Outputs: This is a global variable.
?>
Static variables retain their values between function calls and are initialized only once. They are useful when you need a variable to persist its value across multiple function calls.
<?php
function staticCounter() {
static $count = 0; // Initialized only once
$count++;
echo "Static Count: $count<br>";
}
function regularCounter() {
$count = 0; // Initialized every time the function is called
$count++;
echo "Regular Count: $count<br>";
}
staticCounter(); // Outputs: Static Count: 1
staticCounter(); // Outputs: Static Count: 2
staticCounter(); // Outputs: Static Count: 3
regularCounter(); // Outputs: Regular Count: 1
regularCounter(); // Outputs: Regular Count: 1
regularCounter(); // Outputs: Regular Count: 1
?>
PHP provides several superglobal variables that are used to collect data from various sources. These superglobal variables are accessible from any part of the script, regardless of scope. Here are some of the most commonly used superglobals:
This example demonstrates how to use the $_POST variable to collect data from a form.
<!-- form.html file -->
<!DOCTYPE html>
<html>
<body>
<form method="post" action="post_handler.php">
<label>Enter your name: </label>
<input type="text" name="name" />
<input type="submit" value="Submit" />
</form>
</body>
</html>
<?php
// post_handler.php
$name = $_POST['name'];
echo "Hello, $name!";
?>
This example demonstrates how to use the $_GET variable to collect data from a form.
<!-- form.html file -->
<!DOCTYPE html>
<html>
<body>
<form action="get_handler.php" method="get">
Name: <input type="text" name="name">
<input type="submit" value="Submit">
</form>
</body>
</html>
<?php
// get_handler.php
$name = $_GET['name'];
echo "Hello, $name!";
?>
This example demonstrates how to use the $_REQUEST variable to collect data from a form.
<!-- form_request.html file -->
<!DOCTYPE html>
<html>
<body>
<form method="post" action="request_handler.php">
<label>Enter your age: </label>
<input type="text" name="age" />
<input type="submit" value="Submit" />
</form>
</body>
</html>
<?php
// request_handler.php
$age = $_REQUEST['age'];
echo "Your age is: $age";
?>
This example demonstrates how to use the $_COOKIE variable to store and retrieve a cookie.
<?php
// set_cookie.php
setcookie("user", "John", time() + (86400 * 30), "/"); // 86400 = 1 day
?>
<!DOCTYPE html>
<html>
<body>
<?php
if(isset($_COOKIE["user"])) {
echo "User is " . $_COOKIE["user"];
} else {
echo "User is not set";
}
?>
</body>
</html>
This example demonstrates how to use the $_SESSION variable to store and retrieve session data.
<?php
// start_session.php
session_start();
$_SESSION["favcolor"] = "green";
$_SESSION["favanimal"] = "cat";
echo "Session variables are set.";
?>
<?php
// retrieve_session.php
session_start();
echo "Favorite color is " . $_SESSION["favcolor"] . ".<br>";
echo "Favorite animal is " . $_SESSION["favanimal"] . ".";
?>
By understanding and using these superglobal variables, you can effectively manage and manipulate data within your PHP applications.
This example demonstrates how to create a simple web form that allows users to input two numbers, add them, and display the result in another input field using PHP.
<!DOCTYPE html>
<html>
<head>
<title>Add Two Numbers</title>
</head>
<body>
<h3>Program to Add Two Numbers Inputted in an HTML Input Tag and Show the Result in an HTML Input Tag Upon Clicking the Add Button</h3>
<?php
$sum = ""; // Initialize the sum variable
// Fetch data directly without checking request method
$num1 = $_POST["num1"];
$num2 = $_POST["num2"];
$sum = $num1 + $num2;
?>
<form method="post" action="">
<label>Num 1: </label>
<input type="text" name="num1" value="<?php echo $num1; ?>" required>
<br>
<label>Num 2: </label>
<input type="text" name="num2" value="<?php echo $num2; ?>" required>
<br>
<label>Result: </label>
<input type="text" name="result" value="<?php echo $sum; ?>" >
<br>
<input type="submit" value="Add">
<input type="reset" value="Reset">
</form>
</body>
</html>
Make sure you save this file with ".php" extension.
MySQL is a popular relational database management system used with PHP for building dynamic web applications. It allows storing, retrieving, and managing structured data efficiently.
Connecting PHP to a MySQL database is essential for web applications that require data storage, retrieval, and manipulation. It enables seamless integration of dynamic content and user data management.
There are three main methods used in PHP to connect to MySQL databases:
Explanation of Code:
<?php
// Database credentials
$servername = "localhost";
$username = "root";
$password = "";
// Create a connection to the MySQL database
$conn = mysqli_connect($servername, $username, $password);
// Check if the connection was successful
if (!$conn) {
// If connection fails, terminate the script and display an error message
die("Connection failed: " . mysqli_connect_error());
} else {
// If the connection is successful, display a success message
echo "Connected successfully";
}
mysqli_close($conn);
?>
In the code:
PHP allows you to connect to a MySQL database using the mysqli_connect() function.
mysqli_close()
function to free up resources.Example:
<?php
$host = 'localhost:3306';
$user = 'root';
$pass = 'your_password';
$dbname = 'your_database';
// Establishing the connection
$conn = mysqli_connect($host, $user, $pass, $dbname);
if (!$conn) {
die('Could not connect: ' . mysqli_connect_error());
}
echo 'Connected successfully<br/>';
// Perform database operations here
// Closing the connection
mysqli_close($conn);
?>
Since PHP 4.3, the mysql_create_db() function is deprecated. Now it is recommended to use one of the two alternatives:
<?php
$host = 'localhost:3306';
$user = 'root';
$pass = '';
$conn = mysqli_connect($host, $user, $pass);
if(!$conn) {
die('Could not connect: ' . mysqli_connect_error());
}
echo 'Connected successfully';
$sql = 'CREATE DATABASE mydb';
if(mysqli_query($conn, $sql)) {
echo "Database mydb created successfully.";
} else {
echo "Sorry, database creation failed: " . mysqli_error($conn);
}
mysqli_close($conn);
?>
$conn = mysqli_connect($host, $user, $pass);
This line establishes a connection to the MySQL server using the specified hostname, username,
and password.
if(!$conn) { die('Could not connect: ' . ysqli_connect_error()); }
This block checks if the connection was successful. If not, it outputs an error message and
terminates the script.
$sql = 'CREATE DATABASE mydb';
This line stores the SQL query for creating a new database named 'mydb'.
if(mysqli_query($conn, $sql)) {
echo "Database mydb created successfully.";
} else {
echo "Sorry, database creation failed: " . mysqli_error($conn);
}
This block executes the SQL query. It checks the success of the query and outputs an appropriate
message.
mysqli_close($conn);
This line closes the database connection that was previously opened.
PHP mysqli_query() function is used to create tables in MySQL databases.
Example:
<?php
$host = 'localhost:3306';
$user = 'root';
$pass = '';
$dbname = 'test';
// Establishing the connection
$conn = mysqli_connect($host, $user, $pass, $dbname);
if (!$conn) {
die('Could not connect: ' . mysqli_connect_error());
}
echo 'Connected successfully<br/>';
// SQL query to create a table
$sql = "CREATE TABLE emp5 (
id INT AUTO_INCREMENT,
name VARCHAR(20) NOT NULL,
emp_salary INT NOT NULL,
PRIMARY KEY (id)
)";
if (mysqli_query($conn, $sql)) {
echo "Table emp5 created successfully";
} else {
echo "Could not create table: " . mysqli_error($conn);
}
// Closing the connection
mysqli_close($conn);
?>
$host = 'localhost:3306';
$user = 'root';
$pass = '';
$dbname = 'test';
$conn = mysqli_connect($host, $user, $pass, $dbname);
$sql = "CREATE TABLE emp5 (
id INT AUTO_INCREMENT,
name VARCHAR(20) NOT NULL,
emp_salary INT NOT NULL,
PRIMARY KEY (id)
)";
id
for each new record.name
that can store
a string of up to 20 characters and cannot be null.emp_salary
that stores an
integer and cannot be null.id
column as the primary key of
the table.
if (mysqli_query($conn, $sql)) {
echo "Table emp5 created successfully";
} else {
echo "Could not create table: " . mysqli_error($conn);
}
<?php
$host = 'localhost:3306';
$user = 'root';
$pass = '';
$dbname = 'test';
// Establishing the connection
$conn = mysqli_connect($host, $user, $pass, $dbname);
if (!$conn) {
die('Could not connect: ' . mysqli_connect_error());
}
echo 'Connected successfully<br/>';
// SQL query to insert a record
$sql = "INSERT INTO emp4 (name, salary) VALUES ('sonoo', 9000)";
if (mysqli_query($conn, $sql)) {
echo "Record inserted successfully";
} else {
echo "Could not insert record: " . mysqli_error($conn);
}
// Closing the connection
mysqli_close($conn);
?>
$sql = "INSERT INTO emp4 (name, salary) VALUES ('sonoo', 9000)";
if (mysqli_query($conn, $sql)) {
echo "Record inserted successfully";
} else {
echo "Could not insert record: " . mysqli_error($conn);
}
emp4
table with specified values.
<?php
$host = 'localhost:3306';
$user = 'root';
$pass = '';
$dbname = 'test';
// Establishing the connection
$conn = mysqli_connect($host, $user, $pass, $dbname);
if (!$conn) {
die('Could not connect: ' . mysqli_connect_error());
}
echo 'Connected successfully<br/>';
// Variables to update the record
$id = 2;
$name = "Rahul";
$salary = 80000;
// SQL query to update a record
$sql = "UPDATE emp4 SET name='$name', salary=$salary WHERE id=$id";
if (mysqli_query($conn, $sql)) {
echo "Record updated successfully";
} else {
echo "Could not update record: " . mysqli_error($conn);
}
// Closing the connection
mysqli_close($conn);
?>
<?php
$host = 'localhost:3306';
$user = 'root';
$pass = '';
$dbname = 'test';
// Establishing the connection
$conn = mysqli_connect($host, $user, $pass, $dbname);
if (!$conn) {
die('Could not connect: ' . mysqli_connect_error());
}
echo 'Connected successfully<br/>';
// SQL query to delete a record
$id = 2;
$sql = "DELETE FROM emp4 WHERE id=$id";
if (mysqli_query($conn, $sql)) {
echo "Record deleted successfully";
} else {
echo "Could not delete record: " . mysqli_error($conn);
}
// Closing the connection
mysqli_close($conn);
?>
<?php
$host = 'localhost:3306';
$user = 'root';
$pass = '';
$dbname = 'test';
// Establishing the connection
$conn = mysqli_connect($host, $user, $pass);
if (!$conn) {
die('Could not connect: ' . mysqli_connect_error());
}
echo 'Connected successfully<br/>';
// Creating a database
$sql = "CREATE DATABASE IF NOT EXISTS $dbname";
if (mysqli_query($conn, $sql)) {
echo "Database $dbname created successfully<br/>";
} else {
echo "Could not create database: " . mysqli_error($conn) . "<br/>";
}
// Selecting the database
mysqli_select_db($conn, $dbname);
// Creating a table
$sql = "CREATE TABLE IF NOT EXISTS emp4 (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(20) NOT NULL,
salary INT NOT NULL
)";
if (mysqli_query($conn, $sql)) {
echo "Table emp4 created successfully<br/>";
} else {
echo "Could not create table: " . mysqli_error($conn) . "<br/>";
}
// Inserting a record
$sql = "INSERT INTO emp4 (name, salary) VALUES ('sonoo', 9000)";
if (mysqli_query($conn, $sql)) {
echo "Record inserted successfully<br/>";
} else {
echo "Could not insert record: " . mysqli_error($conn) . "<br/>";
}
// Updating a record
$id = 1;
$name = "Rahul";
$salary = 80000;
$sql = "UPDATE emp4 SET name='$name', salary=$salary WHERE id=$id";
if (mysqli_query($conn, $sql)) {
echo "Record updated successfully<br/>";
} else {
echo "Could not update record: " . mysqli_error($conn) . "<br/>";
}
// Deleting a record
$id = 1;
$sql = "DELETE FROM emp4 WHERE id=$id";
if (mysqli_query($conn, $sql)) {
echo "Record deleted successfully<br/>";
} else {
echo "Could not delete record: " . mysqli_error($conn) . "<br/>";
}
// Closing the connection
mysqli_close($conn);
?>
<!DOCTYPE html>
<html>
<head>
<title>User Registration</title>
</head>
<body>
<h2>User Registration</h2>
<form action="register.php" method="post">
<label for="username">Username:</label>
<input type="text" id="username" name="username" required><br><br>
<label for="email">Email:</label>
<input type="email" id="email" name="email" required><br><br>
<label for="password">Password:</label>
<input type="password" id="password" name="password" required><br><br>
<input type="submit" value="Register">
</form>
</body>
</html>
<?php
$host = 'localhost:3306';
$user = 'root';
$pass = '';
$dbname = 'user_registration';
// Establishing the connection
$conn = mysqli_connect($host, $user, $pass);
if (!$conn) {
die('Could not connect: ' . mysqli_connect_error());
}
echo 'Connected successfully<br/>';
// Creating a database
$sql = "CREATE DATABASE IF NOT EXISTS $dbname";
if (mysqli_query($conn, $sql)) {
echo "Database $dbname created successfully<br/>";
} else {
echo "Could not create database: " . mysqli_error($conn) . "<br/>";
}
// Selecting the database
mysqli_select_db($conn, $dbname);
// Creating a table
$sql = "CREATE TABLE IF NOT EXISTS users (
id INT AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(50) NOT NULL,
email VARCHAR(50) NOT NULL,
password VARCHAR(50) NOT NULL
)";
if (mysqli_query($conn, $sql)) {
echo "Table users created successfully<br/>";
} else {
echo "Could not create table: " . mysqli_error($conn) . "<br/>";
}
// Getting form data
$username = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['password'];
// Inserting a record
$sql = "INSERT INTO users (username, email, password) VALUES ('$username', '$email', '$password')";
if (mysqli_query($conn, $sql)) {
echo "Registration successful!<br/>";
} else {
echo "Could not register user: " . mysqli_error($conn) . "<br/>";
}
// Closing the connection
mysqli_close($conn);
?>