PHP

98 questions

How to install PHP on Windows?

Download PHP from php.net (Thread Safe for Apache).
Extract to C:\php.
Rename php.ini-development to php.ini.
Add C:\php to PATH.
Restart the terminal, check: php -v.
Alternative: XAMPP or Laragon.

How to install PHP on Mac?

Homebrew: brew install php.
Check: php -v.
Configuration: php --ini.
For different versions: brew install php@8.2.
Switching: brew link php@8.2.

How to install PHP on Linux?

Ubuntu/Debian: sudo apt install php.
With modules: sudo apt install php-mysql php-mbstring php-xml.
CentOS: sudo yum install php.
Check: php -v.
Configuration: /etc/php/8.x/.

What is php.ini?

Main PHP configuration file.
Location: php --ini.
Main settings: memory_limit, upload_max_filesize.
display_errors for development.
Restart the web server after changes.

How to run a PHP script?

Command line: php script.php.
Built-in server: php -S localhost:

8000.

Via Apache/Nginx.
Interactive mode: php -a.
Execute code: php -r 'echo "Hello";'.

What data types are in PHP?

Scalar: bool, int, float, string.
Compound: array, object, callable, iterable.
Special: resource, NULL.
PHP is weakly typed.
Type hints for strictness.

What is the difference between == and ===?

== is loose comparison with type juggling.
'5' == 5 returns true.
=== is strict comparison of value AND type.
'5' === 5 returns false.
It is recommended to use ===.

What is the difference between require and include?

include — Warning on error, script continues.
require — Fatal Error, script stops.
include_once/require_once — include only once.
require for critical files.
include for optional files.

What are variables in PHP?

Start with $.
Case-sensitive: $name !== $Name.
Do not require type declaration.
Can change type dynamically.
Global variables: $GLOBALS, $_GET, $_POST.

What are constants in PHP?

define('NAME', 'value') — old way.
const NAME = 'value' — modern.
Do not start with $.
Cannot be changed after definition.
Class constants: Class::CONST.

How do if/else conditions work?

if (condition) { code }.
elseif for additional conditions.
else for the rest.
Ternary: $x = $a ? $b : $c.
Null coalescing: $x = $a ?? 'default'.

What loops are available in PHP?

for ($i = 0; $i < 10; $i++).
while (condition).
do...while — at least 1 iteration.
foreach ($arr as $key => $val).
break — exit, continue — next iteration.

How to declare a function?

function name($param) { return $result; }.
Default values: function f($x = 10).
Type hints: function f(int $x): string.
Anonymous: $fn = function() {}.
Arrow functions: fn($x) => $x * 2.

What is variable scope?

Local — inside a function.
Global — outside functions.
global $var — access to global.
static — retains value between calls.
$GLOBALS['var'] — alternative to global.

How to work with strings?

Single quotes: 'text'.
Double quotes: "$var inside".
Heredoc: <<<EOT multi-line EOT;.
Concatenation: $a . $b.
Functions: strlen(), substr(), strpos().

How to work with arrays?

Indexed: [1, 2, 3].
Associative: ['key' => 'value'].
Multidimensional: array of arrays.
Functions: count(), array_push(), array_merge().
Sorting: sort(), asort(), ksort().

What are superglobal variables?

$_GET — URL parameters.
$_POST — form data.
$_SESSION — session data.
$_COOKIE — cookies.
$_FILES — uploaded files.
$_SERVER — server information.

How to process forms?

Form method: GET or POST.
$_POST['field_name'] to retrieve.
Validation: filter_var(), htmlspecialchars().
Check: isset(), empty().
CSRF tokens for security.

How do echo and print work?

echo — output, no return value.
print — returns 1, slightly slower.
echo 'a', 'b' — multiple arguments.
print only one argument.
Short tag: <?= $var ?>.

What are comments in PHP?

Single-line comments: // comment.
Single-line comments: # comment.
Multi-line comments: /* ... */.
PHPDoc: /** @param type $name */.
Comment why, not what.

How to work with JSON in PHP?

Encoding: json_encode($array, JSON_UNESCAPED_UNICODE).
Decoding: json_decode($json, true).
true for associative array.
Error checking: json_last_error().
For API: header('Content-Type: application/json').

How to work with date and time?

date('Y-m-d H:i:s') — formatting.
time() — Unix timestamp.
strtotime('next Monday').
DateTime class: new DateTime().
DateInterval for differences.

What is the DateTime class?

new DateTime() — current time.
new DateTime('2024-01-15').
$dt->format('Y-m-d').
$dt->modify('+1 day').
$dt1->diff($dt2) — difference.

How to work with files?

file_get_contents() — read.
file_put_contents() — write.
fopen(), fread(), fwrite(), fclose().
file_exists() — check.
unlink() — delete.

How to upload a file to the server?

Form: enctype='multipart/form-data'.
$_FILES['input_name'].
Error check: $_FILES['file']['error'].
move_uploaded_file() for saving.
Validate type and size.

How to work with directories?

scandir() — list files.
mkdir() — create.
rmdir() — delete empty.
is_dir() — check.
glob('*.php') — pattern search.

What is serialization?

serialize() — object to string.
unserialize() — back.
For saving to file/DB.
JSON is preferable for exchange.
__sleep(), __wakeup() — magic methods.

How to work with regular expressions?

preg_match() — search.
preg_match_all() — all matches.
preg_replace() — replace.
preg_split() — split.
Modifiers: i, s, m, u.

How to send an email in PHP?

mail() — basic, unreliable.
PHPMailer — recommended.
composer require phpmailer/phpmailer.
SMTP configuration for reliability.
SwiftMailer/Symfony Mailer — alternatives.

How to work with cURL?

curl_init() — initialization.
curl_setopt() — options.
curl_exec() — execution.
curl_close() — closing.
CURLOPT_RETURNTRANSFER = true for getting the response.

How to send an HTTP request?

file_get_contents() with context.
cURL for complex requests.
Guzzle HTTP — popular library.
composer require guzzlehttp/guzzle.
Symfony HTTP Client — alternative.

How to parse XML?

simplexml_load_string() — simple.
simplexml_load_file().
DOMDocument — more powerful.
XMLReader — for large files.
XPath for searching.

How to parse HTML?

DOMDocument::loadHTML().
DOMXPath for searching.
libxml_use_internal_errors(true).
Simple HTML DOM Parser — library.
Symfony DomCrawler — modern.

How to generate PDF?

TCPDF — popular library.
FPDF — simple.
mPDF — supports UTF-

8.

Dompdf — HTML to PDF.
composer require dompdf/dompdf.

How to work with images?

GD library — built-in.
imagecreatefromjpeg(), imagepng().
Intervention Image — convenient wrapper.
Imagick — more powerful, requires installation.
Resize, crop, watermarks.

How to work with CSV?

fgetcsv() — read line.
fputcsv() — write line.
array_map(function($v){return str_getcsv($v);}, file('data.csv')).
League\Csv — library.
Encoding: mb_convert_encoding().

How to work with Excel?

PhpSpreadsheet — standard.
composer require phpoffice/phpspreadsheet.
Reading: IOFactory::load().
Writing: new Spreadsheet().
Support for xlsx, xls, csv.

How to generate QR codes?

chillerlan/php-qrcode.
endroid/qr-code.
composer require endroid/qr-code.
Output as PNG, SVG.
Customize size and logo.

How to work with ZIP archives?

ZipArchive class.
$zip->open('file.zip', ZipArchive::CREATE).
$zip->addFile().
$zip->extractTo().
$zip->close().

How to cache data?

APCu — in memory.
Memcached — distributed.
Redis — persistent.
File cache — simple.
Symfony Cache — abstraction.

What is OOP in PHP?

Object-oriented programming.
Classes and objects.
Encapsulation, inheritance, polymorphism.
Access modifiers.
Interfaces and abstract classes.

How to create a class?

class ClassName { }.
Properties: public $name;.
Methods: public function method() { }.
Constructor: __construct().
Creating an instance: $obj = new ClassName().

What are access modifiers?

public — accessible everywhere.
protected — class and subclasses.
private — only within the class.
PHP 8.1+: readonly properties.
Default is public.

How does inheritance work?

class Child extends Parent.
Inherits properties and methods.
parent::method() — call to parent.
Overriding methods.
PHP supports only single inheritance.

What are interfaces?

interface Name { public function method(); }.
Contract without implementation.
class X implements Interface.
Multiple implementations allowed.
All methods are public.

What are abstract classes?

abstract class Name { }.
Cannot instantiate.
Can contain implementation.
abstract function — without implementation.
Subclasses must implement abstract methods.

What are traits?

trait Name { methods }.
use TraitName; inside class.
Solve multiple inheritance problem.
Multiple traits can be used.
Conflicts are explicitly resolved.

What are static properties and methods?

static $property, static function.
Call: ClassName::method().
self:: inside class.
static:: late static binding.
Do not require object instantiation.

What are magic methods?

__construct — constructor.
__destruct — destructor.
__get, __set — access to properties.
__call — call to undefined methods.
__toString — string conversion.

What is final?

final class — cannot be inherited.
final function — cannot be overridden.
For protection against modifications.
Immutable objects are often final.
Use consciously.

What is a namespace?

namespace App\Models;.
Allows avoiding name conflicts.
use App\Models\User;.
Full name: \App\Models\User.
PSR-4 — autoloading by namespace.

How does autoloading work?

spl_autoload_register().
PSR-4 standard.
Composer autoload.
namespace = path to file.
require 'vendor/autoload.php'.

What is Dependency Injection?

Passing dependencies through constructor/methods.
Instead of creating inside the class.
Simplifies testing.
DI containers automate.
Inversion of control.

What is late static binding?

static:: instead of self::.
Uses the calling class, not the definition.
Important in inheritance.
get_called_class().
For factory methods.

How to clone an object?

$copy = clone $object.
__clone() for customization.
Shallow copy by default.
Deep — manually clone nested objects.
Difference with = (assignment by reference).

What are anonymous classes?

$obj = new class { }.
PHP 7.0+.
For one-time implementations.
Can inherit and implement interfaces.
Used in tests, mocks.

What is an enum in PHP?

PHP 8.1+.
enum Status { case Pending; case Active; }.
Backed enums: enum Status: string { case Pending = 'pending'; }.
Type-safe enumerations.
Methods can be added.

What are readonly properties?

PHP 8.1+.
readonly public string $name;.
Set only once.
PHP 8.2: readonly class.
For immutable objects.

What is constructor property promotion?

PHP 8.0+.
public function __construct(public string $name).
Declaring property in constructor.
Less boilerplate code.
Works with access modifiers.

What is the Singleton pattern?

Only one instance of the class.
private __construct().
static getInstance().
Difficult to test.
Often considered an anti-pattern.

How to connect to MySQL?

PDO: new PDO('mysql:host=localhost;dbname=test', 'user', 'pass').
MySQLi: new mysqli().
PDO is preferable.
Charset: charset=utf8mb4.
try/catch for errors.

How to execute a PDO query?

$pdo->query() — without parameters.
$pdo->prepare() + execute() — with parameters.
fetch() — one row.
fetchAll() — all rows.
Modes: FETCH_ASSOC, FETCH_OBJ.

What are prepared statements?

$stmt = $pdo->prepare('SELECT * FROM users WHERE id = ?').
$stmt->execute([$id]).
Protection against SQL injections.
Parameterized queries.
Named: :name.

How to protect against SQL injections?

ALWAYS use prepared statements.
NEVER concatenate input.
PDO or MySQLi with parameters.
Input validation.
Minimal database permissions.

How to work with transactions?

$pdo->beginTransaction().
Execute queries.
$pdo->commit() — confirm.
$pdo->rollBack() — rollback.
try/catch for error handling.

How to work with PostgreSQL?

PDO: pgsql:host=localhost;dbname=test.
Functions: JSONB, arrays.
pg_* functions (legacy).
Doctrine fully supports it.
Differences in SQL syntax.

How to work with SQLite?

PDO: sqlite:/path/to/db.sqlite.
File-based database.
For small projects.
Testing.
No server.

How to use migrations?

Doctrine Migrations.
Phinx.
Laravel Migrations.
Database schema versioning.
Command line for application.

How to optimize queries?

Indexes on WHERE, JOIN columns.
EXPLAIN for analysis.
Avoid SELECT *.
Limit for large result sets.
Caching results.

How to work with Redis in PHP?

phpredis extension or Predis.
composer require predis/predis.
$redis = new Redis(); $redis->connect().
set(), get(), expire().
Session and data caching.

How to work with MongoDB?

composer require mongodb/mongodb.
new MongoDB\Client().
Document-oriented database.
insertOne(), find(), updateOne().
BSON documents.

How to paginate results?

LIMIT offset, count.
Or LIMIT count OFFSET offset.
$page = $_GET['page'] ??

1.

$offset = ($page -
* $perPage.
Total count for navigation.

How to implement full-text search?

MySQL FULLTEXT indexes.
MATCH...AGAINST.
Elasticsearch for scale.
Algolia — SaaS.
Meilisearch — lightweight.

How to store passwords?

password_hash($password, PASSWORD_DEFAULT).
password_verify() for checking.
NEVER md5/sha1.
Bcrypt used by default.
PASSWORD_ARGON2ID is even better.

How to protect against XSS?

htmlspecialchars($data, ENT_QUOTES, 'UTF-8').
When outputting user data.
Content-Security-Policy header.
HTTPOnly cookies.
Use templating engines with auto-escaping.

How to protect against CSRF?

CSRF token in form.
Generation: bin2hex(random_bytes(32)).
Save in session.
Check upon receipt.
Frameworks do it automatically.

How to securely work with sessions?

session.cookie_httponly =

1.

session.cookie_secure = 1 (HTTPS).
session.cookie_samesite = 'Strict'.
session_regenerate_id() on login.
Session timeout.

How to validate input data?

filter_var() for basic validation.
filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL).
Custom validation.
Symfony Validator.
Respect/Validation library.

What security headers should be set?

Strict-Transport-Security.
Content-Security-Policy.
X-Content-Type-Options: nosniff.
X-Frame-Options: DENY.
X-XSS-Protection: 1; mode=block.

How to securely upload files?

Check MIME type (finfo).
Do not trust the extension.
Store outside webroot.
Generate new names.
Limit size.

What is HTTPS and how to set it up?

Encrypted connection.
Let's Encrypt — free certificates.
Certbot for automation.
Redirect HTTP → HTTPS.
HSTS header.

How to store configuration securely?

.env files (not in git).
vlucas/phpdotenv.
Environment variables.
.gitignore for secrets.
Vault for production.

How to log securely?

Do not log passwords, tokens.
Mask sensitive data.
Monolog for structured logging.
Levels: debug, info, warning, error.
Log rotation.

What is Composer?

PHP dependency manager.
composer init — create a project.
composer require vendor/package.
composer.lock locks versions.
require 'vendor/autoload.php'.

How to work with Composer?

composer install — from lock file.
composer update — update dependencies.
composer require --dev — for development.
composer dump-autoload — regenerate autoload files.
scripts in composer.json.

What are PSR standards?

PSR-1, PSR-12 — coding style.
PSR-4 — autoloading.
PSR-7 — HTTP messages.
PSR-11 — container interface.
PSR-15 — middleware.

Which PHP framework to choose?

Laravel — the most popular.
Symfony — enterprise, modular.
Slim, Lumen — microframeworks.
Yii — full-featured.
Choice depends on the task.

What is Laravel?

The most popular framework.
Eloquent ORM.
Blade templating engine.
Artisan CLI.
Ecosystem: Forge, Vapor, Nova.

What is Symfony?

Enterprise framework.
Component-based approach.
Doctrine ORM.
Twig templating engine.
Many components in Laravel.

How to test PHP code?

PHPUnit — the standard.
composer require --dev phpunit/phpunit.
TestCase classes.
Assertions: assertEquals, assertTrue.
./vendor/bin/phpunit.

What is PHP-FPM?

FastCGI Process Manager.
For working with Nginx.
Process pool.
Better performance.
Configuration: www.conf.

How to use Docker with PHP?

Official images: php:8.2-fpm.
Dockerfile for extensions.
docker-compose: php + nginx + mysql.
Volumes for code.
Xdebug for debugging.

What’s new in PHP 8?

JIT compilation.
Named arguments.
Attributes.
Match expression.
Constructor promotion.
Union types.

What’s new in PHP 8.1/8.2/8.3?

Enums (8.1).
Readonly properties/classes.
Fibers (8.1).
Disjunctive Normal Form types (8.2).
json_validate() (8.3).

How to debug PHP code?

var_dump(), print_r().
error_log().
Xdebug — step debugging.
IDE: PhpStorm with Xdebug.
dd() in Laravel.

How to profile PHP?

Xdebug profiler.
Blackfire — advanced.
Tideways — monitoring.
XHProf — Facebook.
Bottleneck analysis.

What is Swoole?

Asynchronous PHP server.
Coroutines.
Built-in WebSockets.
High performance.
Laravel Octane uses it.

How to deploy a PHP application?

Git on the server.
composer install --no-dev.
Database migrations.
.env configuration.
Nginx + PHP-FPM.
CI/CD automation.