0% found this document useful (0 votes)
10 views16 pages

PHP Programming Guide: Basics to APIs

The document serves as a comprehensive guide to PHP programming, covering essential topics such as setup, syntax, data types, control structures, functions, and object-oriented programming. It also includes practical examples for building a simple API, connecting to a MySQL database, and handling forms, files, sessions, and errors. Key takeaways emphasize security practices, validation, and the use of Composer for package management.

Uploaded by

mmbruno
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views16 pages

PHP Programming Guide: Basics to APIs

The document serves as a comprehensive guide to PHP programming, covering essential topics such as setup, syntax, data types, control structures, functions, and object-oriented programming. It also includes practical examples for building a simple API, connecting to a MySQL database, and handling forms, files, sessions, and errors. Key takeaways emphasize security practices, validation, and the use of Composer for package management.

Uploaded by

mmbruno
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Contents

1. Setup & Basic Syntax..............................................................................................2


2. Variables & Data Types..........................................................................................2
3. Operators & Control Structures............................................................................3
4. Functions..................................................................................................................3
5. Arrays.......................................................................................................................4
6. Classes & OOP........................................................................................................ 5
7. Building a Simple API.............................................................................................6
8. Database Connection (MySQL with PDO)............................................................7
Key Concepts to Explore Next:..................................................................................8
9. Form Handling with Validation.............................................................................9
10. File Handling....................................................................................................... 10
11. Sessions & Cookies..............................................................................................10
12. Error Handling....................................................................................................11
13. Composer & Package Management...................................................................12
14. REST API Best Practices....................................................................................13
15. Security Essentials...............................................................................................14
Final Project: User Authentication System.............................................................14
Key Takeaways:.........................................................................................................15
1. Setup & Basic Syntax

Install XAMPP/MAMP/WAMP and create a file in htdocs folder (e.g., [Link]):

php

Copy code
<?php
// Single-line comment
/*
Multi-line comment
*/
echo "Hello World!";
?>

2. Variables & Data Types


php

Copy code
$string = "Hello PHP";
$int = 42;
$float = 3.14;
$bool = true;
$array = [1, 2, 3];
$null = null;

var_dump($string); // Check variable type and value


3. Operators & Control Structures
php

Copy code
$a = 10;
$b = 5;

// Arithmetic
echo $a + $b; // 15

// Comparison
if ($a > $b) {
echo "A is larger";
} elseif ($a == $b) {
echo "Equal";
} else {
echo "B is larger";
}

// Loops
for ($i = 0; $i < 5; $i++) {
echo $i;
}

$arr = ["apple", "banana"];


foreach ($arr as $fruit) {
echo $fruit;
}

4. Functions
php

Copy code
function greet($name = "Guest") {
return "Hello, $name!";
}

echo greet(); // Hello, Guest!


echo greet("John"); // Hello, John!
5. Arrays
php

Copy code
// Indexed array
$fruits = ["Apple", "Banana"];

// Associative array
$user = [
"name" => "John",
"age" => 30
];

// Multidimensional array
$users = [
["name" => "Alice", "age" => 25],
["name" => "Bob", "age" => 35]
];

echo $user["name"]; // John


6. Classes & OOP
php

Copy code
class User {
// Properties
public $name;
private $email;

// Constructor
public function __construct($name, $email) {
$this->name = $name;
$this->email = $email;
}

// Method
public function getEmail() {
return $this->email;
}
}

// Inheritance
class Admin extends User {
public $role = "Admin";

public function getEmail() {


return "Admin email: " . parent::getEmail();
}
}

// Usage
$user = new User("John", "john@[Link]");
echo $user->name; // John
echo $user->getEmail(); // john@[Link]

$admin = new Admin("Alice", "alice@[Link]");


echo $admin->role; // Admin
7. Building a Simple API

Create [Link]:

php

Copy code
<?php
header('Content-Type: application/json');

$request = $_SERVER['REQUEST_METHOD'];

switch ($request) {
case 'GET':
// Handle GET request
echo json_encode(["message" => "GET request received"]);
break;

case 'POST':
// Handle POST request
$data = json_decode(file_get_contents('php://input'), true);
echo json_encode(["received_data" => $data]);
break;

default:
http_response_code(405);
echo json_encode(["error" => "Method not allowed"]);
}
8. Database Connection (MySQL with PDO)
php

Copy code
$host = 'localhost';
$db = 'test';
$user = 'root';
$pass = '';

try {
$pdo = new PDO("mysql:host=$host;dbname=$db", $user, $pass);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

// Create table
$pdo->exec("CREATE TABLE IF NOT EXISTS users (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(50) NOT NULL,
email VARCHAR(50) NOT NULL
)");

// Insert data
$stmt = $pdo->prepare("INSERT INTO users (name, email) VALUES (?, ?)");
$stmt->execute(["John", "john@[Link]"]);

// Fetch data
$stmt = $pdo->query("SELECT * FROM users");
$users = $stmt->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($users);

} catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
Key Concepts to Explore Next:

1. Form handling (_POST)


2. File handling (fopen/fwrite)
3. Sessions & Cookies
4. Error handling
5. Composer & package management
6. REST API best practices
7. Security (SQL injection, XSS protection)

To run PHP scripts:

1. Save files with .php extension


2. Place in web server directory (htdocs for XAMPP)
3. Access via [Link]

Practice by building:

 Contact form with validation


 User registration system
 Simple blog with CRUD operations
 REST API with authentication
9. Form Handling with Validation

Explanation: PHP handles HTML form data through $_GET and $_POST superglobals.
Always validate and sanitize user input.

php

Copy code

<form method="POST" action="process_form.php">


Name: <input type="text" name="name" required>
Email: <input type="email" name="email" required>
Message: <textarea name="message"></textarea>
<button type="submit">Send</button>
</form>

<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$name = htmlspecialchars($_POST['name']);
$email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);

if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
die("Invalid email format");
}

// Process valid data


echo "Thank you, $name! We received your message.";
}
?>
10. File Handling

Explanation: PHP provides functions for reading/writing files. Always check file
permissions.

php

Copy code
<?php
// Write to file
$file = '[Link]';
$content = "[" . date('Y-m-d H:i:s') . "] User logged in\n";
file_put_contents($file, $content, FILE_APPEND);

// Read file
if (file_exists($file)) {
$logs = file_get_contents($file);
echo "<pre>$logs</pre>";
} else {
echo "No logs found";
}
?>

11. Sessions & Cookies

Explanation: Sessions maintain user state across pages. Cookies store data client-side.

php

Copy code
<?php
// Start session
session_start();

// Session example
if ($_POST['login']) {
$_SESSION['user'] = [
'id' => 123,
'name' => 'John'
];
}

// Cookie example
setcookie('theme', 'dark', time() + (86400 * 30), "/"); // 30 days
?>

12. Error Handling


Explanation: Use try/catch blocks and custom exceptions for robust error handling.

php

Copy code
<?php
function divide($a, $b) {
if ($b === 0) {
throw new Exception("Division by zero");
}
return $a / $b;
}

try {
echo divide(10, 0);
} catch (Exception $e) {
error_log("Error: " . $e->getMessage());
echo "Something went wrong!";
}
?>
13. Composer & Package Management

Explanation: Composer is PHP's dependency manager. Create [Link]:

json

Copy code
{
"require": {
"guzzlehttp/guzzle": "^7.0"
}
}

Install packages:

bash

Copy code
composer install

Use in code:

php

Copy code
<?php
require 'vendor/[Link]';

$client = new GuzzleHttp\Client();


$response = $client->get('[Link]
echo $response->getBody();
?>
14. REST API Best Practices

Explanation: Use proper HTTP status codes and JSON responses.

php

Copy code
<?php
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');

$data = [];

switch ($_SERVER['REQUEST_METHOD']) {
case 'GET':
$data = ['status' => 'success', 'data' => get_records()];
http_response_code(200);
break;
case 'POST':
$input = json_decode(file_get_contents('php://input'), true);
// Validate and process
$data = ['status' => 'created', 'id' => 123];
http_response_code(201);
break;
default:
http_response_code(405);
$data = ['error' => 'Method not allowed'];
}

echo json_encode($data);
?>
15. Security Essentials

Explanation: Critical security practices every PHP developer must implement.

SQL Injection Prevention:

php

Copy code
$stmt = $pdo->prepare("SELECT * FROM users WHERE email = :email");
$stmt->execute(['email' => $email]);
$user = $stmt->fetch();

XSS Prevention:

php

Copy code
echo htmlspecialchars($user_input, ENT_QUOTES, 'UTF-8');

Password Handling:

php

Copy code
$hash = password_hash($password, PASSWORD_DEFAULT);
if (password_verify($input_password, $hash)) {
// Valid
}

CSRF Protection:

php

Copy code
session_start();
if (empty($_POST['csrf_token']) || $_POST['csrf_token'] !== $_SESSION['csrf_token']) {
die("Invalid CSRF token");
}

Final Project: User Authentication System

Combine all concepts into a working example:

1. Registration form with validation


2. Secure password storage
3. Session management
4. Remember me cookies
5. Profile management
6. Logout functionality

php

Copy code
<?php
session_start();

// Database configuration
$pdo = new PDO('mysql:host=localhost;dbname=auth', 'root', '');

// Login handler
if (isset($_POST['login'])) {
$stmt = $pdo->prepare("SELECT * FROM users WHERE email = ?");
$stmt->execute([$_POST['email']]);
$user = $stmt->fetch();

if ($user && password_verify($_POST['password'], $user['password'])) {


$_SESSION['user'] = $user;
// Set remember me cookie
if (isset($_POST['remember'])) {
$token = bin2hex(random_bytes(32));
setcookie('remember_token', $token, time() + 86400 * 30, '/');
// Store token in database
}
header('Location: [Link]');
}
}
?>
Key Takeaways:

1. Always validate and sanitize user input


2. Use prepared statements for database queries
3. Store passwords using password_hash()
4. Implement CSRF protection for forms
5. Handle errors gracefully
6. Follow REST principles for APIs
7. Keep dependencies updated with Composer

Next steps: Build a blog system with:

 User authentication
 CRUD operations for posts
 File uploads for images
 Search functionality
 REST API endpoints

You might also like