filter_var()<\/code>, prepared statements (with PDO or MySQLi), and never trust data from users.<\/p>Working with Databases Using PDO<\/h3> PHP connects to databases using extensions like MySQLi or PDO. PDO is preferred because it supports multiple databases and offers better security.<\/p>
Basic database connection and query:<\/p>
try {\n $pdo = new PDO('mysql:host=localhost;dbname=testdb', 'username', 'password');\n $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);\n\n $stmt = $pdo->query(\"SELECT id, name FROM users\");\n while ($row = $stmt->fetch()) {\n echo $row['id'] . \" - \" . $row['name'] . \" \";\n }\n} catch (PDOException $e) {\n echo \"Connection failed: \" . $e->getMessage();\n}<\/pre>For user input in queries, always use prepared statements to prevent SQL injection:<\/p>
$stmt = $pdo->prepare(\"SELECT * FROM users WHERE email = ?\");\n$stmt->execute([$email]);\n$user = $stmt->fetch();<\/pre>Building Reusable Code: Functions and Includes<\/h3> As your scripts grow, organize code using functions and file inclusion.<\/p>
Create a function:<\/p>
function greet($name) {\n return \"Hello, $name!\";\n}\necho greet(\"Alice\");<\/pre>Split code across files:<\/p>
\/\/ header.php\necho \"My Site<\/h1><\/header>\";\n\n\/\/ index.php\ninclude 'header.php';\necho \" Welcome to the homepage.<\/p>\";\ninclude 'footer.php';<\/pre>
This modular approach is how early PHP applications were structured—before modern frameworks introduced autoloading and MVC patterns.<\/p>
Security Essentials Every PHP Developer Should Know<\/h3> PHP’s flexibility can lead to vulnerabilities if not handled carefully. Key practices:<\/p>
*Never use `mysql_<\/em>` functions** – they’re deprecated and unsafe<\/li>Use prepared statements<\/strong> for all database queries<\/li>Escape output<\/strong> with htmlspecialchars()<\/code> to prevent XSS<\/li>Validate and filter input<\/strong> using filter_input()<\/code> or validation libraries<\/li>Keep PHP updated<\/strong> to patch known vulnerabilities<\/li>Avoid eval()<\/code><\/strong>—it executes arbitrary code and is a major risk<\/li><\/ul>Also, configure php.ini<\/code> securely:<\/p>Set display_errors = Off<\/code> in production<\/li>Enable open_basedir<\/code> restrictions<\/li>Limit file uploads and execution in writable directories<\/li><\/ul>Modern PHP: Composer, Frameworks, and Beyond<\/h3> While basic PHP scripts are great for learning, real-world projects benefit from modern tools:<\/p>
Composer<\/strong>: PHP’s dependency manager (like npm for JavaScript)<\/li>Laravel, Symfony, Slim<\/strong>: Frameworks that provide routing, ORM, and structure<\/li>PSR standards<\/strong>: Coding conventions for interoperability<\/li>PHP 8 features<\/strong>: Named arguments, attributes, JIT compiler<\/li><\/ul>Example with Composer:<\/p>
composer require monolog\/monolog<\/pre>Then in your script:<\/p>
require 'vendor\/autoload.php';\nuse Monolog\\Logger;\nuse Monolog\\Handler\\StreamHandler;\n\n$log = new Logger('name');\n$log->pushHandler(new StreamHandler('app.log', Logger::WARNING));\n$log->warning('User login failed');<\/pre>These tools make PHP scalable, testable, and maintainable—far from the \"spaghetti code\" stereotype.<\/p>\n
\nPHP may not be the flashiest language today, but it’s deeply embedded in the web’s infrastructure. Whether you're customizing a WordPress plugin, building a small business site, or diving into Laravel, understanding PHP gives you direct access to how the server shapes what users see. It’s not just legacy—it’s still evolving, and still essential.<\/p>\n
Basically, if you want to understand how the web works behind the scenes, PHP is one of the best places to start.<\/p>"}
Home
Backend Development
PHP Tutorial
The Cornerstone of the Web: A Foundational Guide to PHP Scripting
The Cornerstone of the Web: A Foundational Guide to PHP Scripting
Jul 25, 2025 pm 05:09 PM
PHP Introduction
PHP still matters in modern web development because it powers over 75% of websites using server-side languages, including WordPress (43% of all websites), and remains essential for building dynamic, database-driven sites. 1) PHP is a server-side scripting language created in 1995 to make static HTML pages dynamic by processing code on the server before sending HTML to the browser. 2) It enables personalized content, form handling, session management, and database interactions securely. 3) Basic PHP syntax uses <?php ... ?> tags, loose typing, and simple structures like variables ($name), functions (echo()), and control flows (if, for). 4) Form data is processed via $GET or $_POST, but input must be sanitized and validated using filter_var() and prepared statements to prevent attacks. 5) PDO is the preferred method for secure database connectivity, supporting multiple databases and preventing SQL injection through prepared statements. 6) Code reusability is achieved with functions and file inclusion (include 'file.php'), laying the groundwork for modular design. 7) Security best practices include avoiding deprecated mysql functions, escaping output with htmlspecialchars(), validating input, disabling eval(), and securing php.ini settings like display_errors = Off. 8) Modern PHP uses Composer for dependency management, frameworks like Laravel and Symfony for structured development, and PHP 8 features such as named arguments and JIT compilation for performance. 9) PSR standards ensure code interoperability, while tools like Monolog enhance maintainability. Understanding PHP provides deep insight into server-side web mechanics, making it a vital, evolving skill for developers working with WordPress, custom sites, or modern frameworks.
Why PHP Still Matters in Modern Web Development
Even in an era dominated by JavaScript frameworks and headless CMS platforms, PHP remains a foundational force behind much of the web. It powers over 75% of all websites that use a server-side language—including giants like Facebook (in its early days), Wikipedia, and WordPress, which itself drives nearly 43% of all websites. If you're diving into web development, understanding PHP isn’t just about learning an old language—it’s about grasping the backbone of how dynamic websites work.
What Is PHP and Why Was It Built?
PHP (originally "Personal Home Page," now "PHP: Hypertext Preprocessor") is a server-side scripting language designed specifically for web development. Created by Rasmus Lerdorf in 1995, PHP was built to solve a simple problem: how to make static HTML pages dynamic.
When a user requests a PHP page, the server processes the PHP code first—running logic, connecting to databases, handling forms—then sends plain HTML back to the browser. This allows websites to:
Display personalized content (like user dashboards)
Process login forms and handle sessions
Interact with databases (MySQL, PostgreSQL, etc.)
Generate dynamic images or files
Unlike client-side languages like JavaScript, PHP runs entirely on the server, making it ideal for handling sensitive operations securely.
Getting Started: Basic Syntax and Structure
PHP code is embedded within HTML using <?php ... ?>
tags. Here's a minimal example:
<!DOCTYPE html>
<html>
<head>
<title>My First PHP Page</title>
</head>
<body>
<h1>Welcome!</h1>
<p>The time is <?php echo date('H:i:s'); ?>.</p>
</body>
</html> Key features of PHP syntax:
Statements end with a semicolon (;
) Variables start with $
(e.g., $name = "John";
) Functions are called with parentheses: echo()
, strlen()
, array_push()
Supports common control structures: if
, for
, while
, foreach
One of PHP’s strengths is its loose typing—variables don’t need predefined types, which makes it beginner-friendly but requires care to avoid bugs.
One of the most common uses of PHP is processing form data. When a user submits a form, PHP can access the data via $_GET
or $_POST
.
Example: A simple login form handler
<?php
if ($_POST['submit']) {
$username = $_POST['username'];
$password = $_POST['password'];
// In real apps: validate, sanitize, hash password, check database
if ($username === 'admin' && $password === 'secret') {
echo "Login successful!";
} else {
echo "Invalid credentials.";
}
}
?>
<form method="post">
<input type="text" name="username" placeholder="Username">
<input type="password" name="password" placeholder="Password">
<button type="submit" name="submit">Login</button>
</form> ?? Important : Always sanitize and validate user input. Use filter_var()
, prepared statements (with PDO or MySQLi), and never trust data from users.
Working with Databases Using PDO PHP connects to databases using extensions like MySQLi or PDO. PDO is preferred because it supports multiple databases and offers better security.
Basic database connection and query:
try {
$pdo = new PDO('mysql:host=localhost;dbname=testdb', 'username', 'password');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $pdo->query("SELECT id, name FROM users");
while ($row = $stmt->fetch()) {
echo $row['id'] . " - " . $row['name'] . "<br>";
}
} catch (PDOException $e) {
echo "Connection failed: " . $e->getMessage();
} For user input in queries, always use prepared statements to prevent SQL injection:
$stmt = $pdo->prepare("SELECT * FROM users WHERE email = ?");
$stmt->execute([$email]);
$user = $stmt->fetch(); Building Reusable Code: Functions and Includes As your scripts grow, organize code using functions and file inclusion.
Create a function:
function greet($name) {
return "Hello, $name!";
}
echo greet("Alice"); Split code across files:
// header.php
echo "<header><h1>My Site</h1></header>";
// index.php
include 'header.php';
echo "<p>Welcome to the homepage.</p>";
include 'footer.php'; This modular approach is how early PHP applications were structured—before modern frameworks introduced autoloading and MVC patterns.
Security Essentials Every PHP Developer Should Know PHP’s flexibility can lead to vulnerabilities if not handled carefully. Key practices:
*Never use `mysql_ ` functions** – they’re deprecated and unsafe Use prepared statements for all database queriesEscape output with htmlspecialchars()
to prevent XSSValidate and filter input using filter_input()
or validation librariesKeep PHP updated to patch known vulnerabilitiesAvoid eval()
—it executes arbitrary code and is a major riskAlso, configure php.ini
securely:
Set display_errors = Off
in production Enable open_basedir
restrictions Limit file uploads and execution in writable directories Modern PHP: Composer, Frameworks, and Beyond While basic PHP scripts are great for learning, real-world projects benefit from modern tools:
Composer : PHP’s dependency manager (like npm for JavaScript)Laravel, Symfony, Slim : Frameworks that provide routing, ORM, and structurePSR standards : Coding conventions for interoperabilityPHP 8 features : Named arguments, attributes, JIT compilerExample with Composer:
composer require monolog/monolog Then in your script:
require 'vendor/autoload.php';
use Monolog\Logger;
use Monolog\Handler\StreamHandler;
$log = new Logger('name');
$log->pushHandler(new StreamHandler('app.log', Logger::WARNING));
$log->warning('User login failed'); These tools make PHP scalable, testable, and maintainable—far from the "spaghetti code" stereotype.
PHP may not be the flashiest language today, but it’s deeply embedded in the web’s infrastructure. Whether you're customizing a WordPress plugin, building a small business site, or diving into Laravel, understanding PHP gives you direct access to how the server shapes what users see. It’s not just legacy—it’s still evolving, and still essential.
Basically, if you want to understand how the web works behind the scenes, PHP is one of the best places to start.
The above is the detailed content of The Cornerstone of the Web: A Foundational Guide to PHP Scripting. For more information, please follow other related articles on the PHP Chinese website!
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Building Your First Dynamic Web Page: A Practical PHP Primer
Jul 29, 2025 am 04:58 AM
Install XAMPP/MAMP or use PHP built-in server and make sure the file is saved as a .php extension; 2. Use display the current time in hello.php; 3. Get user input through $_GET in greet.php and use htmlspecialchars() to prevent XSS; 4. Use include'header.php'; multiplex the page header; 5. Enable error reports during development, variables start with $, use arrays to store data, and always filter user input. You have created a dynamic web page that can respond to user input, display dynamic content and reuse code. This is a key step towards a complete web application. You can connect to the database or build a login system in the future, but you should be sure of yourself at this time.
Crafting Interactive Web Experiences: An Introduction to PHP's Power
Jul 26, 2025 am 09:52 AM
PHPremainsapowerfulandaccessibleserver-sidelanguageforcreatinginteractivewebexperiencesbecauseitenablesdynamiccontentgeneration,userauthentication,andreal-timedatahandling;1)itiseasytolearnandwidelysupported,integratingdirectlywithHTMLandmosthostingp
Beyond the Basics: Unlocking Web Dynamics with PHP
Jul 25, 2025 pm 03:01 PM
PHPenablesdynamiccontentgenerationbasedonusercontextbyleveragingsessions,geolocation,andtime-basedlogictodeliverpersonalizedexperiencessecurely.2.ItmanagesstateinHTTP’sstatelessenvironmentusing$_SESSIONandcookies,withenhancedsecuritythroughsessionreg
Server-Side Scripting Demystified: A Hands-On Introduction to PHP
Jul 27, 2025 am 03:46 AM
PHPisaserver-sidescriptinglanguageusedtocreatedynamicwebcontent.1.Itrunsontheserver,generatingHTMLbeforesendingittothebrowser,asshownwiththedate()functionoutputtingthecurrentday.2.YoucansetupalocalenvironmentusingXAMPPbyinstallingit,startingApache,pl
Decoding the Server-Side: Your First Steps into PHP's Architecture
Jul 27, 2025 am 04:28 AM
PHP runs on the server side. When the user requests the page, the server executes the code through the PHP engine and returns HTML to ensure that the PHP code is not seen by the front end. 1. Request processing: Use $_GET, $_POST, $_SESSION, $_SERVER to obtain data, and always verify and filter inputs to ensure security. 2. Separation of logic and display: Separate data processing from HTML output, use PHP files to process logic, and template files are responsible for displaying, improving maintainability. 3. Automatic loading and file structure: Configure PSR-4 automatic loading through Composer, such as "App\":"src/", to automatically introduce class files. Suggested projects
The Cornerstone of the Web: A Foundational Guide to PHP Scripting
Jul 25, 2025 pm 05:09 PM
PHPstillmattersinmodernwebdevelopmentbecauseitpowersover75%ofwebsitesusingserver-sidelanguages,includingWordPress(43%ofallwebsites),andremainsessentialforbuildingdynamic,database-drivensites.1)PHPisaserver-sidescriptinglanguagecreatedin1995tomakestat
Embarking on Modern PHP: Syntax, Servers, and Composer
Jul 27, 2025 am 03:43 AM
The core of modern PHP development is the three pillars of syntax, server and Composer. 1. Use modern PHP syntax: including PHP7.4 type attributes (such as publicstring$name), PHP8.0 union type (int|float), nullsafe operator (?->), match expressions and attributes metadata to improve code safety and readability, and declare declare(strict_types=1) at the top of the file to enable strict types. 2. Choose a suitable local development server: Abandon simple php-S and use LaravelSail, SymfonyCLI or Dock instead
The Genesis of a Web Application: A Primer on PHP and MySQL
Jul 28, 2025 am 04:38 AM
To start building a web application, first use PHP and MySQL to build a local environment and create a user registration system. 1. Install XAMPP and other integrated environments, start Apache and MySQL services; 2. Create database and users table in phpMyAdmin, including fields such as id, username, password, etc.; 3. Write an HTML registration form and submit data to register.php; 4. Use PDO to connect to MySQL in register.php, insert data through prepared statement, and encrypt password with password_hash; 5. Handle errors such as duplicate username. This way you can master the server
See all articles