PHP एक popular server-side programming language है जिसका उपयोग dynamic websites, web applications, REST APIs और backend systems बनाने के लिए किया जाता है।
अगर आप Full Stack Developer बनना चाहते हैं या PHP frameworks जैसे Symfony और Laravel पर काम करना चाहते हैं, तो PHP fundamentals समझना जरूरी है।
इस guide में हम PHP syntax, variables, data types, operators, arrays, conditions, loops, functions, forms, sessions, database connectivity और security को practical examples के साथ समझेंगे।
1. PHP क्या है?#
PHP का full form PHP: Hypertext Preprocessor है।
यह एक general-purpose scripting language है, जिसे खासतौर पर web development के लिए इस्तेमाल किया जाता है।
PHP server पर execute होती है और application के अनुसार HTML, JSON या दूसरे response formats generate कर सकती है।
PHP का उपयोग कहाँ होता है?
- Dynamic websites बनाने में
- Backend development में
- REST APIs बनाने में
- Database operations में
- Authentication और authorization में
- Form handling में
- E-commerce applications में
- CMS और web frameworks में
PHP कैसे काम करती है?
जब user browser में कोई PHP-powered page request करता है, तो सामान्य flow कुछ ऐसा होता है:
User / Browser
|
v
HTTP Request
|
v
Web Server
|
v
PHP Runtime
|
v
Application Logic
|
v
Database (if needed)
|
v
HTTP Response
|
v
BrowserExample:
जब user login form submit करता है:
- Browser username और password server को भेजता है।
- PHP application input validate करती है।
- Application database में user record check करती है।
- Password verify होता है।
- Application login success या error response भेजती है।
याद रखें: PHP code server पर execute होता है। Browser को सामान्यतः PHP source code नहीं, बल्कि generated response मिलता है।
Official reference: PHP — What is PHP?
2. PHP Setup और First Program#
PHP सीखने के लिए आपको PHP runtime और एक code editor की जरूरत होती है।
Common setup options
- XAMPP
- MAMP
- Laragon
- PHP built-in development server
- Docker-based PHP environment
अपने system में PHP install होने के बाद terminal में version check करें:
php -vयह installed PHP version दिखाएगा।
First PHP Program
एक file बनाएँ: index.php
<?php
echo "Hello, World!";
?>Output:
Hello, World!PHP Built-in Development Server
अगर PHP installed है, तो project directory में यह command चला सकते हैं:
php -S localhost:8000अब browser में open करें:
http://localhost:8000यह development और testing के लिए built-in server है। इसे production web server की तरह इस्तेमाल नहीं करना चाहिए।
3. PHP Syntax और Basic Rules#
PHP code सामान्यतः <?php opening tag से शुरू होता है।
<?php
echo "Welcome to PHP";
Important rules:
- PHP statements सामान्यतः semicolon (
;) से end होते हैं। - Variables
$symbol से शुरू होते हैं। - PHP keywords और function names case-insensitive हो सकते हैं, लेकिन variables case-sensitive होते हैं।
- Code blocks के लिए curly braces
{}का उपयोग होता है। - Comments code को explain करने के लिए इस्तेमाल होते हैं।
Comments in PHP
<?php
// Single-line comment
# Another single-line comment
/*
Multi-line
comment
*/
echo "Learning PHP";
4. PHP Variables#
Variable एक named storage location है जिसमें data store किया जाता है।
PHP में variable $ से शुरू होता है।
<?php
$name = "Shrikant";
$age = 29;
$salary = 58000;
echo $name;
echo $age;
echo $salary;
Variable Naming Rules
- Variable
$से शुरू होना चाहिए। - इसके बाद name letter या underscore से शुरू होना चाहिए।
- Number से variable name शुरू नहीं हो सकता।
- Variable names case-sensitive होते हैं।
Example:
<?php
$name = "Rahul";
$Name = "Amit";
echo $name; // Rahul
echo $Name; // Amit
यहाँ $name और $Name अलग variables हैं।
Variable Interpolation
Double quotes में variables को string के अंदर use कर सकते हैं।
<?php
$name = "Rahul";
echo "Hello, $name";
Output:
Hello, Rahul5. PHP Data Types#
Data type बताता है कि variable में किस प्रकार का data store है।
PHP के common data types:
| Data Type | Description | Example |
|---|---|---|
| String | Text | "Hello" |
| Integer | Whole number | 100 |
| Float | Decimal number | 99.50 |
| Boolean | True या False | true |
| Array | Multiple values | [10, 20, 30] |
| Object | Class का instance | $user |
| NULL | No value | null |
| Resource | External resource reference | File handle |
Example:
<?php
$name = "Rahul";
$age = 25;
$price = 99.50;
$isActive = true;
$skills = ["PHP", "JavaScript", "React"];
$address = null;
var_dump($name);
var_dump($age);
var_dump($price);
var_dump($isActive);
var_dump($skills);
var_dump($address);
Type Checking
<?php
$value = 100;
var_dump(is_int($value));
var_dump(is_string($value));
var_dump(is_array($value));
Type Declaration
PHP में parameters और return values के लिए type declarations लिख सकते हैं।
<?php
function addNumbers(int $a, int $b): int
{
return $a + $b;
}
echo addNumbers(10, 20);
Output:
30Type declarations code को अधिक predictable बनाने में मदद करती हैं। Type checking के behavior पर strict typing और PHP के type system का प्रभाव पड़ सकता है।
6. PHP Constants#
Constant एक ऐसा identifier है जिसकी value define होने के बाद सामान्य रूप से बदली नहीं जाती।
define() का उपयोग
<?php
define("SITE_NAME", "TheEasyMaster");
echo SITE_NAME;
const का उपयोग
<?php
const APP_VERSION = "1.0.0";
echo APP_VERSION;
Common use cases:
- Application name
- Configuration values
- Fixed settings
- Default limits
Sensitive values जैसे API secrets को source code में hardcode करने के बजाय secure environment configuration में रखना चाहिए।
7. PHP Operators#
Operators values पर operations perform करते हैं।
7.1 Arithmetic Operators
| Operator | Meaning | Example |
|---|---|---|
+ | Addition | $a + $b |
- | Subtraction | $a - $b |
* | Multiplication | $a * $b |
/ | Division | $a / $b |
% | Modulus | $a % $b |
** | Exponentiation | $a ** $b |
Example:
<?php
$a = 10;
$b = 5;
echo $a + $b; // 15
echo $a - $b; // 5
echo $a * $b; // 50
echo $a / $b; // 2
echo $a % $b; // 0
7.2 Comparison Operators
| Operator | Meaning |
|---|---|
== | Equal value |
=== | Equal value and same type |
!= | Not equal |
!== | Not identical |
> | Greater than |
< | Less than |
>= | Greater than or equal |
<= | Less than or equal |
Example:
<?php
$a = 10;
$b = "10";
var_dump($a == $b); // true
var_dump($a === $b); // false
Important: जहाँ possible हो, strict comparison (===, !==) को prefer करें।
7.3 Logical Operators
| Operator | Meaning | ||
|---|---|---|---|
&& | AND | ||
| ` | ` | OR | |
! | NOT | ||
and | Logical AND | ||
or | Logical OR | ||
xor | Exclusive OR |
Example:
<?php
$age = 25;
$hasLicense = true;
if ($age >= 18 && $hasLicense) {
echo "Eligible to drive";
}
7.4 Null Coalescing Operator
अगर variable या array key मौजूद नहीं है या उसका value null है, तो default value इस्तेमाल कर सकते हैं।
<?php
$username = $_GET['username'] ?? 'Guest';
echo $username;
8. Conditional Statements#
Conditional statements किसी condition के आधार पर code execute करती हैं।
8.1 if Statement
<?php
$age = 20;
if ($age >= 18) {
echo "Adult";
}
8.2 if-else Statement
<?php
$age = 16;
if ($age >= 18) {
echo "Eligible";
} else {
echo "Not eligible";
}
8.3 elseif Statement
<?php
$marks = 75;
if ($marks >= 90) {
echo "Grade A";
} elseif ($marks >= 70) {
echo "Grade B";
} elseif ($marks >= 50) {
echo "Grade C";
} else {
echo "Needs improvement";
}
8.4 switch Statement
<?php
$day = 2;
switch ($day) {
case 1:
echo "Monday";
break;
case 2:
echo "Tuesday";
break;
default:
echo "Invalid day";
}
8.5 match Expression
match expression value return करता है और strict comparison (===) का उपयोग करता है।
<?php
$status = 200;
$message = match ($status) {
200 => "Success",
404 => "Not Found",
500 => "Server Error",
default => "Unknown Status",
};
echo $message;
9. PHP Loops#
Loops का उपयोग किसी code block को बार-बार execute करने के लिए किया जाता है।
9.1 for Loop
जब iterations की संख्या पता हो, तब for loop उपयोगी होता है।
<?php
for ($i = 1; $i <= 5; $i++) {
echo $i . PHP_EOL;
}
9.2 while Loop
जब तक condition true रहती है, loop चलता है।
<?php
$i = 1;
while ($i <= 5) {
echo $i . PHP_EOL;
$i++;
}
9.3 do-while Loop
यह loop कम से कम एक बार execute होता है, क्योंकि condition बाद में check होती है।
<?php
$i = 1;
do {
echo $i . PHP_EOL;
$i++;
} while ($i <= 5);
9.4 foreach Loop
Arrays और iterable values के साथ foreach बहुत उपयोगी है।
<?php
$skills = ["PHP", "Symfony", "React"];
foreach ($skills as $skill) {
echo $skill . PHP_EOL;
}
Output:
PHP
Symfony
React10. PHP Arrays#
Array एक variable में multiple values store करने का तरीका है।
PHP में arrays ordered maps की तरह काम करते हैं और numeric या string keys रख सकते हैं।
10.1 Indexed Array
<?php
$fruits = ["Apple", "Mango", "Banana"];
echo $fruits[0]; // Apple
echo $fruits[1]; // Mango
10.2 Associative Array
Associative array में named keys होती हैं।
<?php
$user = [
"name" => "Rahul",
"age" => 25,
"city" => "Chandigarh"
];
echo $user["name"];
echo $user["city"];
10.3 Multidimensional Array
एक array के अंदर दूसरे arrays store किए जा सकते हैं।
<?php
$users = [
[
"name" => "Rahul",
"age" => 25
],
[
"name" => "Amit",
"age" => 28
]
];
echo $users[0]["name"];
Common Array Functions
| Function | Purpose |
|---|---|
count() | Array में elements count करना |
array_push() | End में elements add करना |
array_pop() | Last element remove करना |
array_merge() | Arrays merge करना |
array_keys() | सभी keys प्राप्त करना |
array_values() | सभी values प्राप्त करना |
in_array() | Value check करना |
array_map() | प्रत्येक element पर callback apply करना |
array_filter() | Condition के आधार पर elements filter करना |
array_reduce() | Array को एक result में reduce करना |
Example:
<?php
$numbers = [10, 20, 30];
array_push($numbers, 40);
echo count($numbers); // 4
array_map() Example
<?php
$numbers = [1, 2, 3, 4];
$squared = array_map(
fn($number) => $number * $number,
$numbers
);
print_r($squared);
11. PHP Functions#
Function reusable code block होता है, जिसे जरूरत के अनुसार call किया जा सकता है।
Basic Function
<?php
function sayHello()
{
echo "Hello, PHP!";
}
sayHello();
Function with Parameters
<?php
function greet($name)
{
return "Hello, " . $name;
}
echo greet("Rahul");
Function with Return Type
<?php
function calculateTotal(float $price, int $quantity): float
{
return $price * $quantity;
}
echo calculateTotal(100.50, 2);
Default Parameters
<?php
function welcome($name = "Guest")
{
return "Welcome, " . $name;
}
echo welcome();
echo welcome("Rahul");
Arrow Functions
Short callback expressions के लिए arrow functions उपयोगी हैं।
<?php
$numbers = [1, 2, 3];
$squared = array_map(
fn($number) => $number * $number,
$numbers
);
print_r($squared);
Anonymous Functions
<?php
$greet = function ($name) {
return "Hello, " . $name;
};
echo $greet("Rahul");
Best practice: एक function को एक clear responsibility दें। इससे code maintain और test करना आसान होता है।
12. PHP Strings#
Strings text data store करती हैं।
<?php
$name = "TheEasyMaster";
echo strlen($name);
echo strtoupper($name);
echo strtolower($name);
echo str_replace("Easy", "Smart", $name);
Useful String Functions
| Function | Purpose |
|---|---|
strlen() | String length |
strtolower() | Lowercase |
strtoupper() | Uppercase |
trim() | Beginning और end के whitespace remove करना |
str_replace() | Text replace करना |
strpos() | Substring की position search करना |
substr() | String का हिस्सा निकालना |
explode() | String को array में divide करना |
implode() | Array values को string में join करना |
String Concatenation
PHP में . operator से strings join कर सकते हैं।
<?php
$firstName = "Rahul";
$lastName = "Sharma";
$fullName = $firstName . " " . $lastName;
echo $fullName;
13. PHP Forms: GET और POST#
Web applications में forms का उपयोग user input लेने के लिए किया जाता है।
PHP में form data access करने के common superglobals हैं:
$_GET$_POST
GET Method
GET data URL query string में भेजा जाता है।
Example URL:
https://example.com/search.php?q=phpPHP:
<?php
$search = $_GET['q'] ?? '';
echo htmlspecialchars($search, ENT_QUOTES, 'UTF-8');
GET method search और filtering जैसे use cases में useful है। Sensitive data GET query parameters में नहीं भेजना चाहिए।
POST Method
POST method form data request body में भेजता है।
HTML form:
<form method="POST" action="submit.php">
<input type="text" name="username">
<button type="submit">Submit</button>
</form>PHP:
<?php
$username = $_POST['username'] ?? '';
$username = trim($username);
echo htmlspecialchars($username, ENT_QUOTES, 'UTF-8');
GET vs POST
| Feature | GET | POST |
|---|---|---|
| Data location | URL query string | Request body |
| URL में data visible | Yes | Normally no |
| Common use | Search, filters | Form submissions |
| Bookmarkable | अक्सर हाँ | सामान्यतः नहीं |
| Sensitive data | URL में expose हो सकता है | HTTPS और proper handling जरूरी है |
Important: POST अपने आप secure नहीं होता। Sensitive information के लिए HTTPS, server-side validation और suitable security controls जरूरी हैं।
14. PHP Superglobals#
Superglobals PHP के predefined variables हैं जो सभी scopes में available होते हैं।
| Superglobal | Purpose |
|---|---|
$_GET | URL query parameters |
$_POST | POST request data |
$_REQUEST | GET, POST और COOKIE data (configuration पर निर्भर) |
$_SERVER | Server और request information |
$_FILES | Uploaded file information |
$_SESSION | Session data |
$_COOKIE | Cookie data |
$_ENV | Environment variables |
$GLOBALS | Global scope variables |
Example:
<?php
echo $_SERVER['REQUEST_METHOD'];
Best practice: External input को validate करें। $_REQUEST पर blindly depend करने के बजाय expected input source जैसे $_GET या $_POST explicitly use करें।
15. PHP Include और Require#
Code reuse के लिए एक PHP file को दूसरी file में include किया जा सकता है।
include
<?php
include 'header.php';
echo "Home Page";
अगर file include नहीं हो पाती, तो सामान्यतः warning मिलती है और script आगे चल सकती है।
require
<?php
require 'config.php';
echo "Application Started";
अगर required file load नहीं होती, तो execution सामान्यतः fatal error के साथ रुक जाती है।
include_once और require_once
ये सुनिश्चित करते हैं कि उसी file को एक execution के दौरान एक से अधिक बार include न किया जाए।
<?php
require_once 'database.php';
include_once 'header.php';
16. PHP Sessions और Cookies#
Sessions और cookies का उपयोग HTTP requests के बीच user-related state maintain करने के लिए किया जाता है।
Sessions
Session data server side पर store होता है। Browser सामान्यतः session identifier को cookie में रखता है।
Example:
<?php
session_start();
$_SESSION['username'] = 'Rahul';
echo $_SESSION['username'];
Session पढ़ने के लिए:
<?php
session_start();
$username = $_SESSION['username'] ?? 'Guest';
echo $username;
Logout के समय:
<?php
session_start();
$_SESSION = [];
session_destroy();
Production authentication system में session ID regeneration, secure cookie settings और proper logout handling भी जरूरी हैं।
Cookies
Cookies browser में store की जाती हैं।
<?php
setcookie(
'username',
'Rahul',
[
'expires' => time() + 3600,
'path' => '/',
'secure' => true,
'httponly' => true,
'samesite' => 'Lax'
]
);
Cookie read करना:
<?php
$username = $_COOKIE['username'] ?? 'Guest';
echo htmlspecialchars($username, ENT_QUOTES, 'UTF-8');
setcookie() को response body भेजने से पहले call करना चाहिए। HTTPS environment में secure option enable रखें।
Session vs Cookie
| Feature | Session | Cookie |
|---|---|---|
| Storage | Server-side session storage | Browser |
| Typical purpose | Login state | Preferences, identifiers |
| Size | Storage configuration पर निर्भर | Browser limits के अधीन |
| Security | Server-side storage का फायदा | Client-side data modify हो सकता है |
| Lifetime | Session configuration पर निर्भर | Expiry configure की जा सकती है |
17. PHP Database Connectivity#
PHP applications में MySQL, PostgreSQL और अन्य supported databases के साथ काम किया जा सकता है।
Database connectivity के लिए PHP में PDO (PHP Data Objects) एक common option है।
PDO क्या है?
PDO एक database access abstraction layer है, जो supported database drivers के जरिए database operations perform करने का consistent interface देती है।
PDO Connection Example
<?php
$host = 'localhost';
$dbname = 'my_database';
$username = 'db_user';
$password = 'db_password';
try {
$pdo = new PDO(
"mysql:host=$host;dbname=$dbname;charset=utf8mb4",
$username,
$password,
[
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
]
);
echo "Database connected successfully";
} catch (PDOException $e) {
error_log($e->getMessage());
echo "Database connection failed";
}
यह example connection समझाने के लिए है। Production में credentials को environment configuration या secure secret management में रखें।
Insert Data Using PDO
<?php
$sql = "INSERT INTO users (name, email)
VALUES (:name, :email)";
$stmt = $pdo->prepare($sql);
$stmt->execute([
'name' => 'Rahul',
'email' => 'rahul@example.com'
]);
echo "User added successfully";
Fetch Data Using PDO
<?php
$sql = "SELECT id, name, email FROM users";
$stmt = $pdo->query($sql);
$users = $stmt->fetchAll(PDO::FETCH_ASSOC);
print_r($users);
Why Prepared Statements?
Prepared statements SQL injection का risk कम करने में मदद करते हैं, क्योंकि parameter values को SQL query structure से अलग handle किया जाता है।
Important: SQL query में user input को directly concatenate न करें।
Official reference: PHP — PDO
18. PHP File Handling#
PHP का उपयोग files create, read, write और manage करने के लिए किया जा सकता है।
File Write
<?php
file_put_contents('notes.txt', 'Learning PHP');
File Read
<?php
$content = file_get_contents('notes.txt');
echo $content;
File Exists Check
<?php
if (file_exists('notes.txt')) {
echo "File exists";
} else {
echo "File not found";
}
File Handling Functions
| Function | Purpose |
|---|---|
fopen() | File open करना |
fclose() | File close करना |
fread() | File read करना |
fwrite() | File write करना |
file_get_contents() | File का content पढ़ना |
file_put_contents() | File में content लिखना |
file_exists() | File existence check करना |
unlink() | File delete करना |
File Upload
PHP uploaded file की information $_FILES में उपलब्ध कराता है।
लेकिन secure upload के लिए केवल file extension पर भरोसा न करें। File size, MIME type, actual content, filename और destination validate करें। Files को web root से बाहर store करना जहाँ संभव हो बेहतर है।
19. PHP Error Handling#
Application में errors और exceptions को सही तरीके से handle करना जरूरी है।
try-catch
<?php
try {
$result = 10 / 0;
} catch (DivisionByZeroError $e) {
echo "Cannot divide by zero";
}
throw Exception
<?php
function checkAge(int $age): void
{
if ($age < 18) {
throw new InvalidArgumentException(
"Age must be 18 or above"
);
}
echo "Access allowed";
}
try {
checkAge(16);
} catch (InvalidArgumentException $e) {
echo $e->getMessage();
}
Error vs Exception
PHP में errors और exceptions अलग concepts हैं, हालांकि दोनों Throwable hierarchy का हिस्सा हैं।
- Exceptions को
try-catchसे handle किया जा सकता है। - कई engine errors भी
Throwableimplement करते हैं। - हर error को suppress करना सही solution नहीं है।
Best Practices
- Development में useful error reporting enable करें।
- Production में sensitive error details users को न दिखाएँ।
- Errors को secure logs में record करें।
- Exceptions को केवल वहाँ catch करें जहाँ आप उन्हें meaningfully handle कर सकते हैं।
20. PHP Security Best Practices#
Backend development में security को शुरुआत से ध्यान में रखना जरूरी है।
1. SQL Injection से बचें
Prepared statements और parameterized queries का उपयोग करें।
2. XSS से बचें
HTML में user-generated text display करते समय सही context के अनुसार output escaping करें।
<?php
echo htmlspecialchars(
$username,
ENT_QUOTES,
'UTF-8'
);
3. Password Hashing
Passwords को plain text में store न करें।
<?php
$password = 'example-password';
$hash = password_hash(
$password,
PASSWORD_DEFAULT
);
Password verify करने के लिए:
<?php
if (password_verify($password, $hash)) {
echo "Password matched";
} else {
echo "Invalid password";
}
4. CSRF Protection
State-changing forms और requests के लिए CSRF protection लागू करें। Frameworks में उपलब्ध security features का सही उपयोग करें।
5. Input Validation
User input को expected format और business rules के अनुसार validate करें।
6. File Upload Security
- File size limit रखें।
- File type validate करें।
- Random server-side filename generate करें।
- Upload destination control करें।
- Uploaded files को executable access से सुरक्षित रखें।
7. Secrets Management
Database passwords, API keys और tokens को public repository में commit न करें।
Official reference: PHP — Security
21. PHP Coding Best Practices#
Maintainable PHP code लिखने के लिए इन practices को follow करें:
- Meaningful variable और function names रखें।
- Functions को छोटे और focused रखें।
- Strict comparison (
===) prefer करें। - User input validate करें।
- Output को सही context में escape करें।
- Prepared statements use करें।
- Exceptions को appropriately handle करें।
- Application logic और presentation को अलग रखें।
- Duplicate code कम करें।
- PSR coding standards से familiar हों।
- Dependencies और PHP runtime को supported versions पर maintain करें।
- Automated tests लिखें।
PSR क्या है?
PSR का full form PHP Standards Recommendations है।
PHP-FIG (PHP Framework Interop Group) द्वारा publish की गई recommendations PHP ecosystem में interoperability और coding consistency को बढ़ावा देती हैं।
Examples:
- PSR-1 — Basic Coding Standard
- PSR-4 — Autoloading Standard
- PSR-12 — Extended Coding Style
Reference: PHP-FIG — PSR Standards
22. PHP vs JavaScript#
दोनों popular programming languages हैं, लेकिन इनके common use cases अलग हो सकते हैं।
| Feature | PHP | JavaScript |
|---|---|---|
| Common backend use | Yes | Yes, using Node.js and other runtimes |
| Browser frontend | Directly नहीं | Yes |
| Server-side execution | Yes | Yes |
| Database integration | Supported drivers and libraries | Drivers and libraries |
| Common frameworks | Symfony, Laravel | Express, NestJS |
| Main use cases | Backend, APIs, websites | Frontend, backend, full-stack |
आज PHP और JavaScript दोनों का उपयोग full-stack development में किया जा सकता है।
23. PHP Quick Reference#
| Task | Syntax |
|---|---|
| Output | echo "Hello"; |
| Variable | $name = "Rahul"; |
| Constant | define("APP", "MyApp"); |
| Array | $items = [1, 2, 3]; |
| Associative array | ["name" => "Rahul"] |
| Condition | if ($age >= 18) {} |
| Loop | foreach ($items as $item) {} |
| Function | function greet() {} |
| Include | include 'file.php'; |
| Require | require 'file.php'; |
| GET input | $_GET['id'] ?? null |
| POST input | $_POST['email'] ?? '' |
| Session | $_SESSION['user'] |
| Cookie | $_COOKIE['name'] |
| JSON encode | json_encode($data) |
| JSON decode | json_decode($json, true) |
| Current PHP version | PHP_VERSION |
24. PHP Interview Questions#
Beginner Level
1. PHP क्या है?
PHP एक server-side scripting language है जिसका उपयोग dynamic websites, backend applications और APIs बनाने में किया जाता है।
2. PHP और HTML में क्या difference है?
HTML webpage की structure define करता है, जबकि PHP server-side logic execute करके dynamic output generate कर सकता है।
3. PHP variable कैसे declare करते हैं?
Variable $ से शुरू होता है, जैसे $name = "Rahul";
4. echo और print में क्या difference है?
दोनों output display करने के लिए इस्तेमाल होते हैं। echo एक या अधिक expressions output कर सकता है और return value नहीं देता। print एक value output करता है और 1 return करता है।
5. == और === में क्या difference है?
== values compare करता है, जबकि === value और type दोनों compare करता है।
Intermediate Level
6. Indexed और Associative Arrays में क्या difference है?
Indexed arrays में numeric indexes होते हैं, जबकि associative arrays में named keys होती हैं।
7. GET और POST में क्या difference है?
GET में data URL query string में भेजा जाता है, जबकि POST में data request body में भेजा जाता है।
8. Session और Cookie में क्या difference है?
Session data server-side store होता है, जबकि cookie browser में store होती है।
9. PDO क्या है?
PDO PHP का database access abstraction layer है, जो supported database drivers के जरिए database operations perform करने देता है।
10. Prepared Statements क्यों इस्तेमाल करते हैं?
ये SQL query और user-provided parameter values को अलग रखकर SQL injection risk कम करने में मदद करते हैं।
Practical Level
11. PHP में JSON कैसे generate करते हैं?
json_encode() function का उपयोग करके।
12. Password को securely store कैसे करेंगे?
password_hash() से hash generate करेंगे और login के समय password_verify() से verify करेंगे।
13. PHP में exception कैसे handle करते हैं?
try, catch और जरूरत पड़ने पर finally का उपयोग करके।
14. include और require में क्या difference है?
include failure पर सामान्यतः warning देता है और script आगे चल सकती है। require failure पर execution रोक देता है।
15. PHP में database connection कैसे बनाएँगे?
PDO या supported database extension का उपयोग करके, secure credentials और appropriate error handling के साथ।
25. Practice Exercises#
PHP fundamentals को मजबूत करने के लिए ये exercises करें:
- Exercise 1: PHP program बनाएँ जो आपका नाम, age और city display करे।
- Exercise 2: दो numbers का addition, subtraction, multiplication और division करें।
- Exercise 3: Marks के आधार पर grade calculate करने वाला program बनाएँ।
- Exercise 4: 1 से 100 तक numbers print करने के लिए loop लिखें।
- Exercise 5: एक array बनाएँ जिसमें पाँच programming languages हों और उन्हें
foreachसे display करें। - Exercise 6: एक function बनाएँ जो दो numbers का sum return करे।
- Exercise 7: HTML form बनाएँ और PHP से submitted data validate करें।
- Exercise 8: PHP sessions से simple login state implement करें।
- Exercise 9: PDO prepared statements से database में user record insert करें।
- Exercise 10: Password hashing और verification का छोटा example implement करें।
26. Summary#
PHP एक useful server-side language है जिसका उपयोग websites, backend applications और APIs बनाने में किया जाता है।
इस guide में आपने सीखा:
- PHP syntax और setup
- Variables और data types
- Constants और operators
- Conditions और loops
- Arrays और functions
- Strings और form handling
- Superglobals
- Include और require
- Sessions और cookies
- Database connectivity using PDO
- File handling और error handling
- Security और coding best practices
अगर आप PHP developer बनना चाहते हैं, तो इन concepts को केवल पढ़ें नहीं — छोटे programs बनाकर practice भी करें।
याद रखने वाली बात: PHP fundamentals मजबूत होंगे, तो frameworks और real-world backend applications को समझना आसान होगा।
27. Related Cheat Sheets#
PHP learning path में आगे बढ़ने के लिए:
- HTML Cheat Sheet — Webpage structure समझें।
- CSS Cheat Sheet — Styling और layout सीखें।
- JavaScript Cheat Sheet — Frontend programming fundamentals।
- SQL Cheat Sheet — Database queries सीखें।
- MySQL Cheat Sheet — Relational database fundamentals।
Official References#
Article में इन official resources को relevant sections के साथ link करें:
- PHP Manual — PHP language का complete reference. Manual
- PHP Getting Started — Installation और first PHP tutorial. Manual
- PHP Language Reference — Syntax, types, variables, operators, functions और control structures. Manual
- PHP PDO Documentation — Database connectivity और PDO.
- PHP Security — Security-related guidance.
- PHP-FIG PSR Standards — PHP coding standards.
Next Topic: PHP OOP (Object-Oriented Programming)
अगले guide में Classes, Objects, Constructors, Inheritance, Encapsulation, Abstraction, Interfaces और Traits को practical examples के साथ समझेंगे।