دامینز
خانه همه ابزارها وبلاگ پشتیبانی

چیت‌شیت PHP

مرجع کامل توابع و دستورات PHP آنلاین برای برنامه‌نویسان

رایگان و بدون ثبت‌نام اجرای فوری در مرورگر
میانگین — از ۵ (۰ رأی)
Online PHP Cheat Sheet

✦ PHP Cheat Sheet ✦

Interactive PHP reference for developers
Basics Syntax
Basic PHP syntax and introduction
Hello World!
<?php
$i = "World!";
echo "Hello " . $i;
?>
Comments
<?php
// One liner
# another one liner
/* This is
a multiline
comment */
?>
Defining Functions
function sayHello() {
    echo "Hello!";
}
sayHello(); // Outputs: Hello!
Variables
$i = 1;
$pi = 3.14;
$stringName = "value";
$names = array("John", "Jane", "Jack");
var_dump($names);
var_dump
$a = array(1, 2, array("a", "b", "c"));
var_dump($a);
Objects
class foo {
   function do_foo() {
     echo "Doing foo.";
    }
 }
$bar = new foo;
$bar->do_foo();
Escaping characters
echo "\n"; //New line
Line feed\n
Carriage return\r
Horizontal tab space\t
Vertical tab\v
Escape characters\e
Form (page or section separator)\f
Backslash\\
Dollar sign\$
Single quote\'
Double quote\"
Loops Iteration
For and while loops in PHP
For Loop
// For loop count to 10
for( $i = 0; $i < 10; $i += 1) {
    echo $i . "\n";
}
Foreach Loop
// Declare an array
$arr = array("tesla", "bmw", "audi");
// Loop through the array elements
foreach ($arr as $element) {
    echo "$element ";
}
While Loop
// Declare a number
$i = 10;
// Counting down to 0
while ($i >= 0) {
  echo $i . "\n";
  $i--;
}
Do-While Loop
$i = 10;
// Counting back to 0
do {
    echo $i . "\n";
    $i--;
} while ($i >= 0);
Operators Math
The compiler performs specific mathematical or logical manipulations
Arithmetic
$x + $yAddition
$x - $ySubtraction
$x * $yMultiplication
$x / $yDivision
$x % $yModulus
$x ** $yExponentiation
Assignment
x = yx = y
x += yx = x + y
x -= yx = x - y
x *= yx = x * y
x /= yx = x / y
x %= yx = x % y
Comparison
$x == $yEqual
$x === $yIdentical
$x != $yNot equal
$x <> $yNot equal
$x !== $yNot identical
$x > $yGreater than
$x < $yLess than
$x >= $yGreater than or equal to
$x <= $yLess than or equal to
Increment / Decrement
++$xPre-increment
$x++Post-increment
--$xPre-decrement
$x--Post-decrement
Logical
!$xNot
$x and $y / $x && $yAnd
$x or $y / $x || $yOr
$x xor $yXor
String
$s1 . $s2Concatenation
$s1 .= $s2Concatenation assignment
Conditions Control
Conditional statements
If statement
if (condition) {
// execute this if condition is true
}
If - Else
if (condition) {
  // do this if condition is true
} else {
  // do this if condition is false
}
If - Elseif - Else
if (condition) {
  // code if condition is true
} elseif (condition2) {
  // condition is false and condition2 is true
} else {
  // if none of the conditions are met
}
Switch Statement
switch (n) {
case a:
  //code to execute if n=a;
break;
case b:
  //code to execute if n=b;
break;
case c:
  //code to execute if n=c;
break;
  // more cases as needed
default:
  // if n is neither of the above;
}
Ternary
$result = condition ? value1 : value2;

Is the same as:

if (condition) {
    $result = value1;
} else {
    $result = value2;
}
Functions Reusable
Functions are reusable blocks of code
Parameters
function greet($name) {
    echo "Hello " . $name;
}
greet("John");
// Outputs: Hello John
Default Parameters
function greet($name = "Visitor") {
    echo "Hello, " . $name;
}
greet(); // Outputs: Hello, Visitor
Return Values
function add($a, $b) {
    return $a + $b;
}
$result = add(3, 5);
// $result is 8
Variable Scope
$number = 10;
function multiplyByTwo() {
    global $number;
    $number *= 2;
}
multiplyByTwo();
echo $number; // Outputs: 20
Anonymous Functions
$greet = function($name) {
    echo "Hello, " . $name;
};
$greet("Alice"); // Outputs: Hello, Alice
Built-in Functions
  • String: strlen(), str_replace(), substr()
  • Array: array_merge(), array_pop(), array_keys()
  • Math: abs(), ceil(), floor()
  • Date: date(), strtotime(), mktime()
  • File: fopen(), fwrite(), fread()
Arrays Collections
A PHP array can store multiple values of different types
Indexed arrays
$colors = array("Red", "Green", "Blue");
echo $colors[0]; // Outputs: Red
Associative arrays
$age = array("Peter" => 35, "Ben" => 37, "Joe" => 43);
echo $age['Peter']; // Outputs: 35
Multidimensional arrays
$students = array(
  "John" => array("Math" => 123, "Science" => 456),
  "Jane" => array("Math" => 789, "Science" => 987)
);
echo $students['John']['Math']; // Outputs: 123
Array Functions
array_change_key_case, array_chunk, array_column, array_combine, array_count_values, array_diff, array_diff_assoc, array_diff_key, array_diff_uassoc, array_diff_ukey, array_fill, array_fill_keys, array_filter, array_flip, array_intersect, array_intersect_assoc, array_intersect_key, array_intersect_uassoc, array_intersect_ukey, array_key_exists, array_keys, array_map, array_merge, array_merge_recursive, array_multisort, array_pad, array_pop, array_product, array_push, array_rand, array_reduce, array_replace, array_replace_recursive, array_reverse, array_search, array_shift, array_slice, array_splice, array_sum, array_udiff, array_udiff_assoc, array_udiff_uassoc, array_uintersect, array_uintersect_assoc, array_uintersect_uassoc, array_unique, array_unshift, array_values, array_walk, array_walk_recursive, arsort, asort, compact, count, current, each, end, extract, in_array, key, krsort, ksort, list, natcasesort, natsort, next, prev, range, reset, rsort, shuffle, sort, uasort, uksort, usort
Predefined Variables Superglobals
PHP offers a wide range of predefined variables
$GLOBALS
$a = 5;
$b = 10;
function addition() {
  $GLOBALS['sum'] = $GLOBALS['a'] + $GLOBALS['b'];
}
addition();
echo $sum;
Super Global Variables
$_SERVER, $_SERVER['PHP_SELF'], $_SERVER['GATEWAY_INTERFACE'], $_SERVER['SERVER_ADDR'], $_SERVER['SERVER_NAME'], $_SERVER['SERVER_SOFTWARE'], $_SERVER['SERVER_PROTOCOL'], $_SERVER['REQUEST_METHOD'], $_SERVER['REQUEST_TIME'], $_SERVER['QUERY_STRING'], $_SERVER['HTTP_ACCEPT'], $_SERVER['HTTP_ACCEPT_CHARSET'], $_SERVER['HTTP_HOST'], $_SERVER['HTTP_REFERER'], $_SERVER['HTTPS'], $_SERVER['REMOTE_ADDR'], $_SERVER['REMOTE_HOST'], $_SERVER['REMOTE_PORT'], $_SERVER['SCRIPT_FILENAME'], $_SERVER['SERVER_ADMIN'], $_SERVER['SERVER_PORT'], $_SERVER['SERVER_SIGNATURE'], $_SERVER['PATH_TRANSLATED'], $_SERVER['SCRIPT_NAME'], $_SERVER['SCRIPT_URI']
PHP Forms Input
An associative array of variables passed to the current script
$_GET
// URL: html6.com?x=1&y=2
$x = $_GET['x'];  // $x will be 1
$_POST
$username = $_POST['username'];
// Variable will contain the value entered in the form
HTML Form
<form method="post" action="form.php">
  <input type="text" name="username">
   <input type="submit">
</form>
$_REQUEST
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $username = $_REQUEST['username'];
    echo "Hello, " . htmlspecialchars($username);
}
Security
  • htmlspecialchars(): Converts special characters to HTML entities
  • trim(): Removes whitespace from beginning and end of a string
  • stripslashes(): Removes backslashes from a string
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $input = htmlspecialchars($_POST['input_field'], ENT_QUOTES, 'UTF-8');
    $input = trim($input);
    if (get_magic_quotes_gpc()) {
        $input = stripslashes($input);
    }
}
Predefined Functions Built-in
PHP variable handling functions
boolval
inputboolval(input)
0false
12true
0.0false
1.2true
""false
"hello"true
"0"false
"1"true
[1, 2]true
[]false
new stdClasstrue
isset
$x = 0;
if (isset($x)) {
echo "x is set";
}
// True because $x is set
unset
$x = "Hello world!";
echo "before unset: " . $x;
unset($x);
echo "after unset: " . $a;
// Throws warning for undefined variable
empty
inputempty(input)
""true
0true
"php"false
gettype
$variablegettype($variable)
12integer
12.3double
"HTML Cheat Sheet"string
array(1, 2, 3)array
fopen("file.txt", "r")resource
intval
$variableintval($variable)
1212
12.312
"12.3"12
"Hello"0
is_array

To check whether a given variable is an array

Database MySQLi
MySQLi extension for PHP
Connecting to DB
$mysqli = new mysqli("localhost", "username", "password", "database");
if ($mysqli->connect_error) {
    die("Connection failed: " . $mysqli->connect_error);
}
Queries
$result = $mysqli->query("SELECT * FROM table_name");
if ($result) {
    while ($row = $result->fetch_assoc()) {
        echo $row["column_name"];
    }
}
Prepared Statements
$stmt = $mysqli->prepare("SELECT * FROM table_name WHERE column_name = ?");
$stmt->bind_param("s", $value);
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
    echo $row["column_name"];
}
$stmt->close();
Inserting Data
$sql = "INSERT INTO table_name (column1, column2) VALUES ('value1', 'value2')";
if ($mysqli->query($sql) === TRUE) {
    echo "New record created successfully";
} else {
    echo "Error: " . $sql . "<br>" . $mysqli->error;
}
Updating Data
$sql = "UPDATE table_name SET column1 = 'value' WHERE condition";
if ($mysqli->query($sql) === TRUE) {
    echo "Record updated successfully";
} else {
    echo "Error: " . $sql . "<br>" . $mysqli->error;
}
Deleting Data
$sql = "DELETE FROM table_name WHERE condition";
if ($mysqli->query($sql) === TRUE) {
    echo "Record deleted successfully";
} else {
    echo "Error: " . $sql . "<br>" . $mysqli->error;
}
Closing the Connection
$mysqli->close();
Regular Expressions RegEx
RegEx syntax and functions
Syntax
$email = "admin@htmlcheatsheet.com";
if (preg_match('/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/', $email)) {
    echo "Valid email address";
} else {
    echo "Invalid email";
}
RegEx Functions
  • preg_match() - Returns 1 if the pattern was found
  • preg_match_all() - Returns the number of times the pattern was found
  • preg_replace() - Returns a new string where matched patterns have been replaced
Modifiers
  • i - Performs a case-insensitive search
  • m - Performs a multiline search
  • u - Enables correct matching of UTF-8 encoded patterns
Patterns
  • [abc] - Find one character from the options between the brackets
  • [^abc] - Find any character NOT between the brackets
  • [0-9] - Find one character from the range 0 to 9
Metacharacters
  • | - Find a match for any one of the patterns separated by |
  • . - Find just one instance of any character
  • ^ - Finds a match as the beginning of a string
  • $ - Finds a match at the end of the string
  • \d - Find a digit
  • \s - Find a whitespace character
  • \b - Find a match at the beginning or end of a word
  • \uxxxx - Find the Unicode character specified by the hexadecimal number xxxx
Quantifiers
  • n+ - Contains at least one n
  • n* - Contains zero or more occurrences of n
  • n? - Contains zero or one occurrences of n
  • n{x} - Contains a sequence of X n's
  • n{x,y} - Contains a sequence of X to Y n's
  • n{x,} - Contains a sequence of at least X n's
PHP Filters Validation
Used to validate and filter data from insecure sources
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $filters = array(
        'email' => FILTER_VALIDATE_EMAIL,
    );
    $sanitized_inputs = filter_input_array(INPUT_POST, $filters);
    if ($sanitized_inputs['email'] === false) {
        echo "Invalid email address!";
    } else {
        $email = $sanitized_inputs['email'];
        echo "Valid email address: " . $email;
    }
}
Filter Functions
  • filter_has_var() - Check if a variable of the specified type exists
  • filter_id() - Returns the ID belonging to a named filter
  • filter_input() - Retrieves a specified external variable by name
  • filter_input_array() - Pulls external variables and optionally filters them
  • filter_list() - Returns a list of all supported filters
  • filter_var_array() - Gets multiple variables and optionally filters them
  • filter_var() - Filters a variable with a specified filter
Filter Constants
  • FILTER_VALIDATE_BOOLEAN - Validates a boolean
  • FILTER_VALIDATE_EMAIL - Certifies an e-mail address
  • FILTER_VALIDATE_FLOAT - Confirms a float
  • FILTER_VALIDATE_INT - Verifies an integer
  • FILTER_VALIDATE_IP - Validates an IP address
  • FILTER_VALIDATE_REGEXP - Confirms a regular expression
  • FILTER_VALIDATE_URL - Validates a URL
  • FILTER_SANITIZE_EMAIL - Removes all illegal characters from an e-mail
  • FILTER_SANITIZE_ENCODED - Removes/Encodes special characters
  • FILTER_SANITIZE_MAGIC_QUOTES - Applies addslashes()
  • FILTER_SANITIZE_NUMBER_FLOAT - Removes all characters except digits, +- and .,eE
  • FILTER_SANITIZE_NUMBER_INT - Removes all characters except digits and + -
  • FILTER_SANITIZE_SPECIAL_CHARS - Removes special characters
  • FILTER_SANITIZE_FULL_SPECIAL_CHARS - Converts special characters to HTML entities
  • FILTER_SANITIZE_STRING - Removes tags/special characters from a string
  • FILTER_SANITIZE_URL - Removes all illegal characters from a URL
  • FILTER_UNSAFE_RAW - Do nothing, optionally strip/encode special characters
  • FILTER_CALLBACK - Call a user-defined function to filter data
Date and Time DateTime
Working with date and time in PHP
// Get current timestamp
$currentTimestamp = time();
// Format and display current date and time
echo "Current timestamp: " . $currentTimestamp . "<br>";
// Format date using date() function
echo "Current date: " . date("Y-m-d") . "<br>";
echo "Current time: " . date("H:i:s") . "<br>";
// Format date and time with specific timezone
date_default_timezone_set('America/New_York');
echo "Current date and time in New York: " . date("Y-m-d H:i:s");
Formatting
  • d - Days from 01 to 31
  • j - Days 1 to 31
  • D - Mon through Sun
  • l - Sunday through Saturday
  • N - 1 (Mon) through 7 (Sat)
  • w - 0 (Sun) through 6 (Sat)
  • m - Months, 01 through 12
  • n - Months, 1 through 12
  • F - January through December
  • M - Jan through Dec
  • Y - Four digits year (e.g. 2018)
  • y - Two digits year (e.g. 18)
  • L - Defines whether it's a leap year (1 or 0)
  • a - am and pm
  • A - AM and PM
  • g - Hours 1 through 12
  • h - Hours 01 through 12
  • G - Hours 0 through 23
  • H - Hours 00 through 23
  • i - Minutes 00 to 59
  • s - Seconds 00 to 59
Functions
checkdate, date_add, date_create_from_format, date_create, date_date_set, date_default_timezone_get, date_default_timezone_set, date_diff, date_format, date_get_last_errors, date_interval_create_from_date_string, date_interval_format, date_isodate_set, date_modify, date_offset_get, date_parse_from_format, date_parse, date_sub, date_sun_info, date_sunrise, date_sunset, date_time_set, date_timestamp_get, date_timestamp_set, date_timezone_get, date_timezone_set, date, getdate, gettimeofday, gmdate, gmmktime, gmstrftime, idate, localtime, microtime, mktime, strftime, strptime, strtotime, time, timezone_abbreviations_list, timezone_identifiers_list, timezone_location_get, timezone_name_from_abbr, timezone_name_get, timezone_offset_get, timezone_open, timezone_transitions_get, timezone_version_get
Common Errors Best Practices
Tips to keep your code error-free
  • Don't forget the semicolon!
  • Mismatched brackets ()
  • Incorrect quotes: " '
  • Undefined variables
  • Case sensitivity $Var ≠ $var
  • Incorrect function calls that does not exist or with incorrect parameters
File Inclusion Errors

Using include or require with an incorrect file path. Use absolute paths or ensure relative paths are correct.

SQL Injection

Failing to sanitize user inputs can lead to SQL injection attacks. Use prepared statements and parameterized queries.

Error Handling

Use try-catch blocks and implementing proper error handling mechanisms.

Incorrect Array Usage

Check if array keys exist before accessing them.

Session Handling

Start sessions with session_start() and handle session variables correctly.

Output Buffering

Unintentional output before headers are sent can cause "headers already sent" errors. Use output buffering or ensure no output before header() calls.

Scope Issues

Variable scope misunderstandings. Use global keyword or pass variables as function arguments.

Misconfigured php.ini

Incorrect settings in the php.ini file can lead to various issues.

Deprecated Features

Using deprecated functions or features that may be removed in future PHP versions.

Incorrect Timezone Configuration

Set the default timezone using date_default_timezone_set().

Memory Limit Issues

Increase memory limit in php.ini or optimize code to use less memory.

Best Practices to Avoid Common PHP Errors
  • Use Error Reporting: Enable error reporting during development
  • Code Reviews: Regular code reviews can catch errors early
  • Testing: Write unit tests and integration tests
  • Documentation: Keep your code well-documented
  • Stay Updated: Keep up with the latest PHP versions and best practices
ابزار درست کار نمی‌کند؟

راهنمای چیت‌شیت PHP

PHP هنوز موتور بیش از سه‌چهارم سایت‌های دنیاست — وردپرس، لاراول و هزاران سیستم دیگر با این زبان کار می‌کنند. چیت‌شیت PHP دامینز پرکاربردترین توابع و الگوهای این زبان را دسته‌بندی‌شده و با مثال قابل کپی جمع کرده تا هنگام کدنویسی سرعت‌تان افت نکند.

پوشش موضوعی چیت‌شیت

  • آرایه‌ها: توابع پرتکرار مثل array_map، array_filter و مرتب‌سازی چندبعدی.
  • رشته‌ها: برش، جایگزینی، قالب‌بندی و کار با یونیکد فارسی.
  • فایل و مسیرها: خواندن، نوشتن و مدیریت مسیرهای امن.
  • تاریخ و زمان: فرمت‌بندی تاریخ شمسی و میلادی، محاسبه فاصله روزها.
  • امنیت: فیلترکردن ورودی، escape خروجی و هش رمز عبور.

مخصوص توسعه‌دهندگان وردپرس

بخش زیادی از کار روزمره وردپرس‌کارها PHP خام است: نوشتن شورت‌کد، دستکاری کوئری‌ها و آماده‌سازی اسکریپت‌های جانوری. چیت‌شیت برای همین سناریوها تنظیم شده تا پاسخ پرتکرار در همان یک نگاه پیدا شود.

چرا امنیت در PHP جدی‌تر است؟

چون PHP مستقیماً با ورودی کاربر و دیتابیس سروکار دارد، توابع فیلتر و escape در چیت‌شیت برجسته شده‌اند. یادتان باشد: هر داده ورودی از کاربر، دشمن بالقوه است. برای اسکن فایل‌های PHP سایت‌تان از نظر بدافزار، اسکنر امنیتی وردپرس دامینز را امتحان کنید.

آخرین بروزرسانی: ۲ مهر ۱۴۰۵ ۰ بازدید★ ابزار جدید

چیت‌شیت PHP چیست و برای چه کسانی است؟

برنامه‌نویس‌ها و مدیران سایت به ابزارهای دقیق توسعه و امنیت نیاز دارند که بدون دردسر و بدون ارسال داده به سرور کار کنند. «چیت‌شیت PHP» دامینز دقیقاً برای همین ساخته شده: سریع، بی‌حاشیه و قابل اتکا.

چرا از چیت‌شیت PHP دامینز استفاده کنیم؟

  • پردازش کامل در مرورگر — داده و کد شما به جایی ارسال نمی‌شود
  • خروجی مطابق استانداردهای روز توسعه وب
  • مناسب کار روزمره روی پروژه‌های واقعی
  • رایگان، بدون ثبت‌نام و بدون محدودیت

چطور از چیت‌شیت PHP استفاده کنیم؟ (گام‌به‌گام)

  1. ورودی خود (کد، متن، فایل یا پارامترها) را در ابزار وارد کنید.
  2. گزینه‌های مربوطه را تنظیم کنید.
  3. خروجی یا نتیجه بررسی را تحلیل کنید.
  4. نتیجه را کپی و در پروژه خود استفاده کنید.
💡 نکته: این ابزار برای کارهای روزمره و بررسی سریع عالی است؛ برای ممیزی‌های امنیتی حساس همیشه یک بررسی تخصصی جداگانه هم انجام دهید.

امنیت و حریم خصوصی

این ابزار بدون ثبت‌نام و رایگان است و پردازش آن در مرورگر شما انجام می‌شود؛ متن، فایل و داده‌ای که وارد می‌کنید روی سرور ذخیره نمی‌شود. اگر سوال یا پیشنهادی برای بهتر شدن ابزار دارید، از دکمه گزارش مشکل یا صفحه تماس برای ما بنویسید — تیم دامینز معمولاً سریع پاسخ می‌دهد.

سوالات متداول

برای کدام نسخه PHP است؟
بر پایه PHP مدرن (نسخه ۸ به بالا) نوشته شده؛ اکثر موارد در نسخه‌های قدیمی‌تر هم کار می‌کنند.
کدها قابل کپی و تست هستند؟
بله، همه مثال‌ها برای کپی سریع آماده‌اند.
آیا مباحث شیءگرایی (OOP) هم هست؟
تمرکز چیت‌شیت روی کاربرد روزمره است؛ الگوهای پرکاربرد OOP هم پوشش داده شده‌اند.
برای وردپرس کاربرد دارد؟
بله، بخش قابل توجهی از سناریوهای وردپرسی با توابع استاندارد PHP حل می‌شود.
تاریخ شمسی هم پوشش داده شده؟
بله، نکات کار با تاریخ فارسی در بخش تاریخ آمده است.