PHP Basics: A Comprehensive Guide
The popular server-side programming language PHP (Hypertext Preprocessor) was created for web development. It enables programmers to produce dynamic content that manages sessions, processes user input, and communicates with databases. Everything from syntax and data types to more complex ideas like OOP, security, and APIs is covered in this primer to PHP.
1. Basic Syntax
It begins with `<?php` and ends with `?>` for PHP scripts. The code inside these tags is executed on the server before being sent to the browser.
<?php
echo "Welcome to DigAboutIT!";
?>
echo "Welcome to DigAboutIT!";
?>
2. Variables
Variables in PHP start with `$` and do not need explicit data type declarations.
Variables in PHP start with `$` and do not need explicit data type declarations.
<?php
$name = "Dig";
$age = 23;
?>
3. Data Types
PHP supports various data types, below given are a few:
String: `$str = "DigAboutIT";`
Integer: `$num = 10;`
Float: `$price = 100.59;`
Boolean: `$is_valid = yes;`
Array: `$colors = ["Orange", "Green", "Red"];`
Object: `$bike = new Bike();`
PHP supports various data types, below given are a few:
String: `$str = "DigAboutIT";`
Integer: `$num = 10;`
Float: `$price = 100.59;`
Boolean: `$is_valid = yes;`
Array: `$colors = ["Orange", "Green", "Red"];`
Object: `$bike = new Bike();`
4. Strings
Strings can be manipulated using the string functions like `strlen()`, `str_replace()`, and `substr()`.
Strings can be manipulated using the string functions like `strlen()`, `str_replace()`, and `substr()`.
<?php
echo strlen("DigAboutIT"); // Output: 10
?>
echo strlen("DigAboutIT"); // Output: 10
?>
5. Arrays
Arrays contains values, can be indexed, associative, or multidimensional.
Arrays contains values, can be indexed, associative, or multidimensional.
<?php
$colors = array("Orange", "Green", "Red");
echo $colors[0]; // Output: Orange
?>
$colors = array("Orange", "Green", "Red");
echo $colors[0]; // Output: Orange
?>
6. Functions
Functions encapsulate reusable code, we can use it where needed in our code.
Functions encapsulate reusable code, we can use it where needed in our code.
<?php
function hello($name) {
return "Hello, $name!";
}
echo hello("Ravin");
?>
function hello($name) {
return "Hello, $name!";
}
echo hello("Ravin");
?>
7. Conditionals
`if`, `else`, `elseif`, and `switch` statements will control the program flow, using these we can create conditional statements in the script.
`if`, `else`, `elseif`, and `switch` statements will control the program flow, using these we can create conditional statements in the script.
<?php
if ($age >= 18) {
echo "Major";
} else {
echo "Minor";
}
?>
if ($age >= 18) {
echo "Major";
} else {
echo "Minor";
}
?>
8. Loops
Loops `for`, `while`, `foreach` are used for iteration. Which helps to build a business logic as per the requirement.
Loops `for`, `while`, `foreach` are used for iteration. Which helps to build a business logic as per the requirement.
<?php
for ($i = 0; $i < 5; $i++) {
echo "$i ";
}
?>
for ($i = 0; $i < 5; $i++) {
echo "$i ";
}
?>
9. Superglobals
PHP provides predefined global arrays like `$_GET`, `$_POST`, `$_SESSION`, and `$_COOKIE`.
10. Forms Handling
Form data can be captured using `$_POST` or `$_GET` methods.
Form data can be captured using `$_POST` or `$_GET` methods.
<?php
$name = $_POST['name'];
echo "Hello, $name";
?>
$name = $_POST['name'];
echo "Hello, $name";
?>
You can find a few more PHP basic questions and answers here in this video:
11. Sessions & Cookies
Sessions store data across pages, while cookies store small data on the client-side.
<?php
session_start();
$_SESSION['user'] = "John";
echo $_SESSION['user'];
?>
session_start();
$_SESSION['user'] = "John";
echo $_SESSION['user'];
?>
12. File Handling
Using PHP we can read and write files with the help of `fopen()`, `fwrite()`, and `fread()` functions.
<?php
$somefile = fopen("somefile.txt", "w");
fwrite($somefile, "Hello, DigAboutIT!");
fclose($somefile);
?>
$somefile = fopen("somefile.txt", "w");
fwrite($somefile, "Hello, DigAboutIT!");
fclose($somefile);
?>
13. Error Handling
Using `try-catch` block we can handle the exceptions in PHP.
<?php
try {
throw new Exception("Opps, its an Error!");
} catch (Exception $e) {
echo $e->getMessage();
}
?>
try {
throw new Exception("Opps, its an Error!");
} catch (Exception $e) {
echo $e->getMessage();
}
?>
14. Object-Oriented Programming (OOP)
PHP supports OOP concepts like classes, objects, inheritance, and polymorphism. This features gives us code reusability and modularity.
PHP supports OOP concepts like classes, objects, inheritance, and polymorphism. This features gives us code reusability and modularity.
<?php
class Bike {
public $brand;
function __construct($brand) {
$this->brand = $brand;
}
}
$bike = new Bike("Yamaha");
echo $bike->brand;
?>
class Bike {
public $brand;
function __construct($brand) {
$this->brand = $brand;
}
}
$bike = new Bike("Yamaha");
echo $bike->brand;
?>
15. Constructors & Destructors
Constructors initialize an object, and destructors execute upon object destruction, even we can perform or implement specific logic in these two functions.
Constructors initialize an object, and destructors execute upon object destruction, even we can perform or implement specific logic in these two functions.
<?php
class ConDemo {
function __construct() {
echo "ConDemo object created.";
}
function __destruct() {
echo "ConDemo object destroyed.";
class ConDemo {
function __construct() {
echo "ConDemo object created.";
}
function __destruct() {
echo "ConDemo object destroyed.";
}
}
$obj = new ConDemo();
?>
}
$obj = new ConDemo();
?>
16. Static Methods
Static methods belong to a class and don’t require an instance, we can directly invoke by using scope resolution operator (::).
Static methods belong to a class and don’t require an instance, we can directly invoke by using scope resolution operator (::).
<?php
class Sq {
static function square($a) {
return $a * $a;
}
}
echo Sq::square(2);
?>
class Sq {
static function square($a) {
return $a * $a;
}
}
echo Sq::square(2);
?>
17. Namespaces & Traits
Namespaces prevent name conflicts, and traits enable code reusability, and supports multiple inheritance.
Namespaces prevent name conflicts, and traits enable code reusability, and supports multiple inheritance.
<?php
namespace App;
class AppClass {}
?>
namespace App;
class AppClass {}
?>
18. Database Handling with PDO & MySQLi
PHP supports MySQL database connections using PDO and MySQLi.
PHP supports MySQL database connections using PDO and MySQLi.
<?php
$pdo = new PDO("mysql:host=localhost;dbname=testdb", "rootuser", "pwd");
?>
$pdo = new PDO("mysql:host=localhost;dbname=testdb", "rootuser", "pwd");
?>
19. SQL Injection Prevention
In PHP, we can use prepared statements to prevent SQL injection.
In PHP, we can use prepared statements to prevent SQL injection.
<?php
$stmt = $pdo->prepare("SELECT * FROM tutorials WHERE subject = :subject");
$stmt->bindParam(":subject", $subject);
$stmt->execute();
?>
$stmt = $pdo->prepare("SELECT * FROM tutorials WHERE subject = :subject");
$stmt->bindParam(":subject", $subject);
$stmt->execute();
?>
20. Regular Expressions
PHP supports regular expressions, using regex with `preg_match()` and `preg_replace()`.
PHP supports regular expressions, using regex with `preg_match()` and `preg_replace()`.
<?php
if (preg_match("/^[a-zA-Z]+$/", "DigAboutIT")) {
echo "Valid";
}
?>
if (preg_match("/^[a-zA-Z]+$/", "DigAboutIT")) {
echo "Valid";
}
?>
21. cURL, JSON & XML
Use client URL (cURL) for API requests, and JSON/XML for data exchange.
Use client URL (cURL) for API requests, and JSON/XML for data exchange.
<?php
$json = json_encode(["name" => "Ravin", "age" => 23]);
echo $json;
?>
$json = json_encode(["name" => "Ravin", "age" => 23]);
echo $json;
?>
22. Date & Time Functions
In PHP `date()` and `strtotime()` help manipulate the dates as needed.
In PHP `date()` and `strtotime()` help manipulate the dates as needed.
<?php
echo date("Y-m-d");
?>
echo date("Y-m-d");
?>
23. PHP Mail Function
In PHP we can send emails using `mail()` function.
In PHP we can send emails using `mail()` function.
<?php
mail("testemail@example.com", "Subject", "Message");
?>
mail("testemail@example.com", "Subject", "Message");
?>
24. Encryption
Use `md5()`, `hash()`, or `password_hash()` for security.
Use `md5()`, `hash()`, or `password_hash()` for security.
<?php
echo password_hash("password123", PASSWORD_DEFAULT);
?>
echo password_hash("password123", PASSWORD_DEFAULT);
?>
25. File Upload Handling
PHP manages file uploads securely.
PHP manages file uploads securely.
<?php
move_uploaded_file($_FILES['somefile']['tmp_name'], "uploads/" . $_FILES['somefile']['name']);
?>
move_uploaded_file($_FILES['somefile']['tmp_name'], "uploads/" . $_FILES['somefile']['name']);
?>
26. PHP & HTML Integration
PHP can be embedded within HTML.
<html>
<body>
<h1><?php echo "DigAboutIT Content"; ?></h1>
</body>
</html>
PHP can be embedded within HTML.
<html>
<body>
<h1><?php echo "DigAboutIT Content"; ?></h1>
</body>
</html>
27. PHP Command Line
PHP scripts can run from the command line.
PHP scripts can run from the command line.
<?bash
php script.php
?>
php script.php
?>
28. Error Reporting
We can enable error reporting for debugging in PHP as below.
We can enable error reporting for debugging in PHP as below.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
?>
error_reporting(E_ALL);
ini_set('display_errors', 1);
?>
29. Frameworks & Composer
Use Laravel, Symfony, or CodeIgniter for development. Composer manages dependencies.
<?bash
composer require vendor/package
?>
composer require vendor/package
?>
30. RESTful APIs, SOAP, AJAX & Templating
Use PHP to develop REST APIs and handle AJAX requests.
Use PHP to develop REST APIs and handle AJAX requests.
<?php
header("Content-Type: application/json");
echo json_encode(["message" => "Simple API Test"]);
?>
header("Content-Type: application/json");
echo json_encode(["message" => "Simple API Test"]);
?>
Conclusion
PHP is the perfect language for dynamic web applications because it is strong and supports many features. You will be prepared for PHP programming if you can master these subjects!, Hope you enjoyed this article on basic questions and answers.

0 Comments