PHP (Hypertext Preprocessor) is a powerful server-side scripting language widely used to build dynamic websites, APIs, and web applications. From WordPress to Facebook’s early days, PHP has powered some of the biggest sites in the world.
Why Learn PHP?
- Server-side → Runs on the server, generates HTML for the browser.
- Easy to Learn → Beginner-friendly syntax.
- Widely Used → Powers CMSs like WordPress, Drupal, Joomla.
- Frameworks → Laravel, Symfony, CodeIgniter make development faster.
Hello World
<?php
echo "Hello, PHP!";
?>
Variables
<?php
$name = "Alice";
$age = 25;
echo "My name is $name and I am $age years old.";
?>
Data Types
- String →
"Hello"
- Integer →
42
- Float →
3.14
- Boolean →
true
- Array →
[1, 2, 3]
- Object → Instances of classes
Conditionals
<?php
$age = 18;
if ($age >= 18) {
echo "Adult";
} else {
echo "Minor";
}
?>
Loops
<?php
for ($i = 1; $i <= 5; $i++) {
echo $i;
}
$x = 0;
while ($x < 3) {
echo $x;
$x++;
}
?>
Arrays
<?php
$fruits = ["Apple", "Banana", "Cherry"];
foreach ($fruits as $fruit) {
echo $fruit . "<br>";
}
?>
Functions
<?php
function greet($name) {
return "Hello, $name!";
}
echo greet("Alice");
?>
Forms and $_POST
<!-- form.html -->
<form method="post" action="submit.php">
<input type="text" name="username">
<input type="submit" value="Submit">
</form>
<?php
// submit.php
$username = $_POST['username'];
echo "Welcome, $username!";
?>
Connecting to a Database (MySQL)
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM users";
$result = $conn->query($sql);
while($row = $result->fetch_assoc()) {
echo $row["name"] . "<br>";
}
$conn->close();
?>
Mini Project: Simple Login
<?php
$user = "admin";
$pass = "1234";
if ($_POST["username"] == $user && $_POST["password"] == $pass) {
echo "Login successful!";
} else {
echo "Invalid credentials.";
}
?>
Best Practices
- Always validate and sanitize user input.
- Use
PDO
orMySQLi
for secure database queries. - Separate logic (PHP) from presentation (HTML).
- Learn a framework like Laravel for real projects.
Next Steps
- PHP OOP → Learn classes, objects, inheritance.
- Sessions & Cookies → Manage logins and state.
- Laravel → Build powerful apps quickly.
- APIs → Create REST APIs with PHP.
Conclusion
PHP is a practical, fast, and widely used language for web development. It powers millions of websites, from blogs to enterprise apps. Learning PHP opens doors to backend development, CMS customization, and API building.
Practice daily, build small projects, and grow into PHP frameworks like Laravel 🚀🔥
No comments:
Post a Comment