Skip to content

PHP Cheat Sheet in Hindi: Complete Guide for Beginners

Updated 10 Nov 2026 7 min scan

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 कुछ ऐसा होता है:

Code
User / Browser
      |
      v
HTTP Request
      |
      v
Web Server
      |
      v
PHP Runtime
      |
      v
Application Logic
      |
      v
Database (if needed)
      |
      v
HTTP Response
      |
      v
Browser

Example:

जब user login form submit करता है:

  1. Browser username और password server को भेजता है।
  2. PHP application input validate करती है।
  3. Application database में user record check करती है।
  4. Password verify होता है।
  5. 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 करें:

Code
php -v

यह installed PHP version दिखाएगा।

First PHP Program

एक file बनाएँ: index.php

Code
<?php

echo "Hello, World!";

?>

Output:

Code
Hello, World!

PHP Built-in Development Server

अगर PHP installed है, तो project directory में यह command चला सकते हैं:

Code
php -S localhost:8000

अब browser में open करें:

Code
http://localhost:8000

यह development और testing के लिए built-in server है। इसे production web server की तरह इस्तेमाल नहीं करना चाहिए।

3. PHP Syntax और Basic Rules#

PHP code सामान्यतः <?php opening tag से शुरू होता है।

Code
<?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

Code
<?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 $ से शुरू होता है।

Code
<?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:

Code
<?php

$name = "Rahul";
$Name = "Amit";

echo $name; // Rahul
echo $Name; // Amit

यहाँ $name और $Name अलग variables हैं।

Variable Interpolation

Double quotes में variables को string के अंदर use कर सकते हैं।

Code
<?php

$name = "Rahul";

echo "Hello, $name";

Output:

Code
Hello, Rahul

5. PHP Data Types#

Data type बताता है कि variable में किस प्रकार का data store है।

PHP के common data types:

Data TypeDescriptionExample
StringText"Hello"
IntegerWhole number100
FloatDecimal number99.50
BooleanTrue या Falsetrue
ArrayMultiple values[10, 20, 30]
ObjectClass का instance$user
NULLNo valuenull
ResourceExternal resource referenceFile handle

Example:

Code
<?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

Code
<?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 लिख सकते हैं।

Code
<?php

function addNumbers(int $a, int $b): int
{
    return $a + $b;
}

echo addNumbers(10, 20);

Output:

Code
30

Type declarations code को अधिक predictable बनाने में मदद करती हैं। Type checking के behavior पर strict typing और PHP के type system का प्रभाव पड़ सकता है।

6. PHP Constants#

Constant एक ऐसा identifier है जिसकी value define होने के बाद सामान्य रूप से बदली नहीं जाती।

define() का उपयोग

Code
<?php

define("SITE_NAME", "TheEasyMaster");

echo SITE_NAME;

const का उपयोग

Code
<?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

OperatorMeaningExample
+Addition$a + $b
-Subtraction$a - $b
*Multiplication$a * $b
/Division$a / $b
%Modulus$a % $b
**Exponentiation$a ** $b

Example:

Code
<?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

OperatorMeaning
==Equal value
===Equal value and same type
!=Not equal
!==Not identical
>Greater than
<Less than
>=Greater than or equal
<=Less than or equal

Example:

Code
<?php

$a = 10;
$b = "10";

var_dump($a == $b);  // true
var_dump($a === $b); // false

Important: जहाँ possible हो, strict comparison (===, !==) को prefer करें।

7.3 Logical Operators

OperatorMeaning
&&AND
``OR
!NOT
andLogical AND
orLogical OR
xorExclusive OR

Example:

Code
<?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 इस्तेमाल कर सकते हैं।

Code
<?php

$username = $_GET['username'] ?? 'Guest';

echo $username;

8. Conditional Statements#

Conditional statements किसी condition के आधार पर code execute करती हैं।

8.1 if Statement

Code
<?php

$age = 20;

if ($age >= 18) {
    echo "Adult";
}

8.2 if-else Statement

Code
<?php

$age = 16;

if ($age >= 18) {
    echo "Eligible";
} else {
    echo "Not eligible";
}

8.3 elseif Statement

Code
<?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

Code
<?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 (===) का उपयोग करता है।

Code
<?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 उपयोगी होता है।

Code
<?php

for ($i = 1; $i <= 5; $i++) {
    echo $i . PHP_EOL;
}

9.2 while Loop

जब तक condition true रहती है, loop चलता है।

Code
<?php

$i = 1;

while ($i <= 5) {
    echo $i . PHP_EOL;
    $i++;
}

9.3 do-while Loop

यह loop कम से कम एक बार execute होता है, क्योंकि condition बाद में check होती है।

Code
<?php

$i = 1;

do {
    echo $i . PHP_EOL;
    $i++;
} while ($i <= 5);

9.4 foreach Loop

Arrays और iterable values के साथ foreach बहुत उपयोगी है।

Code
<?php

$skills = ["PHP", "Symfony", "React"];

foreach ($skills as $skill) {
    echo $skill . PHP_EOL;
}

Output:

Code
PHP
Symfony
React

10. PHP Arrays#

Array एक variable में multiple values store करने का तरीका है।

PHP में arrays ordered maps की तरह काम करते हैं और numeric या string keys रख सकते हैं।

10.1 Indexed Array

Code
<?php

$fruits = ["Apple", "Mango", "Banana"];

echo $fruits[0]; // Apple
echo $fruits[1]; // Mango

10.2 Associative Array

Associative array में named keys होती हैं।

Code
<?php

$user = [
    "name" => "Rahul",
    "age" => 25,
    "city" => "Chandigarh"
];

echo $user["name"];
echo $user["city"];

10.3 Multidimensional Array

एक array के अंदर दूसरे arrays store किए जा सकते हैं।

Code
<?php

$users = [
    [
        "name" => "Rahul",
        "age" => 25
    ],
    [
        "name" => "Amit",
        "age" => 28
    ]
];

echo $users[0]["name"];

Common Array Functions

FunctionPurpose
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:

Code
<?php

$numbers = [10, 20, 30];

array_push($numbers, 40);

echo count($numbers); // 4

array_map() Example

Code
<?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

Code
<?php

function sayHello()
{
    echo "Hello, PHP!";
}

sayHello();

Function with Parameters

Code
<?php

function greet($name)
{
    return "Hello, " . $name;
}

echo greet("Rahul");

Function with Return Type

Code
<?php

function calculateTotal(float $price, int $quantity): float
{
    return $price * $quantity;
}

echo calculateTotal(100.50, 2);

Default Parameters

Code
<?php

function welcome($name = "Guest")
{
    return "Welcome, " . $name;
}

echo welcome();
echo welcome("Rahul");

Arrow Functions

Short callback expressions के लिए arrow functions उपयोगी हैं।

Code
<?php

$numbers = [1, 2, 3];

$squared = array_map(
    fn($number) => $number * $number,
    $numbers
);

print_r($squared);

Anonymous Functions

Code
<?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 करती हैं।

Code
<?php

$name = "TheEasyMaster";

echo strlen($name);
echo strtoupper($name);
echo strtolower($name);
echo str_replace("Easy", "Smart", $name);

Useful String Functions

FunctionPurpose
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 कर सकते हैं।

Code
<?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:

Code
https://example.com/search.php?q=php

PHP:

Code
<?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:

Code
<form method="POST" action="submit.php">
    <input type="text" name="username">
    <button type="submit">Submit</button>
</form>

PHP:

Code
<?php

$username = $_POST['username'] ?? '';

$username = trim($username);

echo htmlspecialchars($username, ENT_QUOTES, 'UTF-8');

GET vs POST

FeatureGETPOST
Data locationURL query stringRequest body
URL में data visibleYesNormally no
Common useSearch, filtersForm submissions
Bookmarkableअक्सर हाँसामान्यतः नहीं
Sensitive dataURL में 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 होते हैं।

SuperglobalPurpose
$_GETURL query parameters
$_POSTPOST request data
$_REQUESTGET, POST और COOKIE data (configuration पर निर्भर)
$_SERVERServer और request information
$_FILESUploaded file information
$_SESSIONSession data
$_COOKIECookie data
$_ENVEnvironment variables
$GLOBALSGlobal scope variables

Example:

Code
<?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

Code
<?php

include 'header.php';

echo "Home Page";

अगर file include नहीं हो पाती, तो सामान्यतः warning मिलती है और script आगे चल सकती है।

require

Code
<?php

require 'config.php';

echo "Application Started";

अगर required file load नहीं होती, तो execution सामान्यतः fatal error के साथ रुक जाती है।

include_once और require_once

ये सुनिश्चित करते हैं कि उसी file को एक execution के दौरान एक से अधिक बार include न किया जाए।

Code
<?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:

Code
<?php

session_start();

$_SESSION['username'] = 'Rahul';

echo $_SESSION['username'];

Session पढ़ने के लिए:

Code
<?php

session_start();

$username = $_SESSION['username'] ?? 'Guest';

echo $username;

Logout के समय:

Code
<?php

session_start();

$_SESSION = [];

session_destroy();

Production authentication system में session ID regeneration, secure cookie settings और proper logout handling भी जरूरी हैं।

Cookies

Cookies browser में store की जाती हैं।

Code
<?php

setcookie(
    'username',
    'Rahul',
    [
        'expires' => time() + 3600,
        'path' => '/',
        'secure' => true,
        'httponly' => true,
        'samesite' => 'Lax'
    ]
);

Cookie read करना:

Code
<?php

$username = $_COOKIE['username'] ?? 'Guest';

echo htmlspecialchars($username, ENT_QUOTES, 'UTF-8');

setcookie() को response body भेजने से पहले call करना चाहिए। HTTPS environment में secure option enable रखें।

Session vs Cookie

FeatureSessionCookie
StorageServer-side session storageBrowser
Typical purposeLogin statePreferences, identifiers
SizeStorage configuration पर निर्भरBrowser limits के अधीन
SecurityServer-side storage का फायदाClient-side data modify हो सकता है
LifetimeSession 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

Code
<?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

Code
<?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

Code
<?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

Code
<?php

file_put_contents('notes.txt', 'Learning PHP');

File Read

Code
<?php

$content = file_get_contents('notes.txt');

echo $content;

File Exists Check

Code
<?php

if (file_exists('notes.txt')) {
    echo "File exists";
} else {
    echo "File not found";
}

File Handling Functions

FunctionPurpose
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

Code
<?php

try {
    $result = 10 / 0;

} catch (DivisionByZeroError $e) {
    echo "Cannot divide by zero";
}

throw Exception

Code
<?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 भी Throwable implement करते हैं।
  • हर 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 करें।

Code
<?php

echo htmlspecialchars(
    $username,
    ENT_QUOTES,
    'UTF-8'
);

3. Password Hashing

Passwords को plain text में store न करें।

Code
<?php

$password = 'example-password';

$hash = password_hash(
    $password,
    PASSWORD_DEFAULT
);

Password verify करने के लिए:

Code
<?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 अलग हो सकते हैं।

FeaturePHPJavaScript
Common backend useYesYes, using Node.js and other runtimes
Browser frontendDirectly नहींYes
Server-side executionYesYes
Database integrationSupported drivers and librariesDrivers and libraries
Common frameworksSymfony, LaravelExpress, NestJS
Main use casesBackend, APIs, websitesFrontend, backend, full-stack

आज PHP और JavaScript दोनों का उपयोग full-stack development में किया जा सकता है।

23. PHP Quick Reference#

TaskSyntax
Outputecho "Hello";
Variable$name = "Rahul";
Constantdefine("APP", "MyApp");
Array$items = [1, 2, 3];
Associative array["name" => "Rahul"]
Conditionif ($age >= 18) {}
Loopforeach ($items as $item) {}
Functionfunction greet() {}
Includeinclude 'file.php';
Requirerequire 'file.php';
GET input$_GET['id'] ?? null
POST input$_POST['email'] ?? ''
Session$_SESSION['user']
Cookie$_COOKIE['name']
JSON encodejson_encode($data)
JSON decodejson_decode($json, true)
Current PHP versionPHP_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 को समझना आसान होगा।

PHP learning path में आगे बढ़ने के लिए:

Official References#

Article में इन official resources को relevant sections के साथ link करें:

  1. PHP Manual — PHP language का complete reference. Manual
  2. PHP Getting Started — Installation और first PHP tutorial. Manual
  3. PHP Language Reference — Syntax, types, variables, operators, functions और control structures. Manual
  4. PHP PDO Documentation — Database connectivity और PDO.
  5. PHP Security — Security-related guidance.
  6. 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 के साथ समझेंगे।