
30 simple PHP script examples with comments, focusing on basic functionality and clarity. I’ve aimed to make them as straightforward as possible for understanding.
<?php // 1. Simple "Hello, World!" echo "Hello, World!"; // 2. Variables $name = "John"; echo "Hello, " . $name . "!"; // 3. Basic Arithmetic $num1 = 10; $num2 = 5; $sum = $num1 + $num2; echo "The sum is: " . $sum; // 4. If Statement $age = 20; if ($age >= 18) { echo "You are an adult."; } else { echo "You are a minor."; } // 5. For Loop for ($i = 0; $i < 5; $i++) { echo "The number is: " . $i . "<br>"; } // 6. While Loop $counter = 0; while ($counter < 3) { echo "Counter: " . $counter . "<br>"; $counter++; } // 7. Arrays $colors = array("red", "green", "blue"); echo "The first color is: " . $colors[0]; // 8. Associative Arrays $person = array("name" => "Jane", "age" => 30); echo "The person's name is: " . $person["name"]; // 9. Functions function greet($name) { echo "Hello, " . $name . "!"; } greet("Alice"); // 10. Function with return value function add($num1, $num2) { return $num1 + $num2; } $result = add(3, 7); echo "The result is: " . $result; // 11. String Concatenation $firstName = "David"; $lastName = "Smith"; $fullName = $firstName . " " . $lastName; echo "Full name: " . $fullName; // 12. String Length $text = "This is a string."; echo "The length of the string is: " . strlen($text); // 13. String Uppercase $text = "lowercase"; echo strtoupper($text); // 14. String Lowercase $text = "UPPERCASE"; echo strtolower($text); // 15. String Replace $text = "Hello World"; $newText = str_replace("World", "PHP", $text); echo $newText; // 16. Date and Time echo date("Y-m-d H:i:s"); // 17. Include (assuming you have a file named 'my_file.php') // include("my_file.php"); // my_file.php should contain some PHP code. // 18. Require (similar to include, but produces a fatal error if the file is not found) // require("my_file.php"); // my_file.php should contain some PHP code. // 19. GET request // Assuming the script is accessed via URL like: script.php?name=Bob if (isset($_GET["name"])) { echo "Hello, " . $_GET["name"] . "!"; } // 20. POST request (needs an HTML form to submit the data) // Assuming you have a form submitting to this script with a field named "email" if (isset($_POST["email"])) { echo "The email is: " . $_POST["email"]; } // 21. Switch Statement $day = "Monday"; switch ($day) { case "Monday": echo "It's Monday!"; break; case "Tuesday": echo "It's Tuesday!"; break; default: echo "It's another day."; } // 22. Array Push (Add an element to the end of an array) $colors = array("red", "green"); array_push($colors, "blue"); print_r($colors); // Output: Array ( [0] => red [1] => green [2] => blue ) // 23. Array Pop (Remove the last element of an array) $colors = array("red", "green", "blue"); $lastColor = array_pop($colors); echo "Popped color: " . $lastColor . "<br>"; //Popped color: blue print_r($colors); // Output: Array ( [0] => red [1] => green ) // 24. isset() - Check if a variable is set $myVar = "Hello"; if (isset($myVar)) { echo "Variable is set."; } else { echo "Variable is not set."; } // 25. empty() - Check if a variable is empty $emptyVar = ""; //Or $emptyVar = 0; or $emptyVar = array(); if (empty($emptyVar)) { echo "Variable is empty."; } else { echo "Variable is not empty."; } // 26. Basic File Reading (assuming you have a 'text_file.txt') $fileContent = file_get_contents("text_file.txt"); echo $fileContent; //Display content if text_file.txt exist // 27. Basic File Writing $data = "This is some text to write to the file.\n"; file_put_contents("new_file.txt", $data); //Create/overwrite new_file.txt // 28. Simple form processing with validation if ($_SERVER["REQUEST_METHOD"] == "POST") { $name = $_POST["name"]; if (empty($name)) { echo "Name is required"; } else { echo "Hello, " . htmlspecialchars($name); //Prevent XSS } } // The HTML form would look something like: // <form method="post" action="your_script.php"> // Name: <input type="text" name="name"><br> // <input type="submit"> // </form> // 29. Simple error handling try { $result = 10 / 0; //Potential division by zero error } catch (Exception $e) { echo "An error occurred: " . $e->getMessage(); } // 30. Creating a cookie $cookie_name = "user"; $cookie_value = "John Doe"; setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); // 86400 = 1 day //Check if cookie is set (usually in separate request) if(!isset($_COOKIE[$cookie_name])) { echo "Cookie named '" . $cookie_name . "' is not set!"; } else { echo "Cookie '" . $cookie_name . "' is set!<br>"; echo "Value is: " . $_COOKIE[$cookie_name]; } ?>
Key improvements and considerations:
- Comments: Each example has a brief explanation of what it does.
- Clear Variables: Meaningful variable names are used.
- Error Handling: A basic
try...catch
block is included for error handling (division by zero). Form validation is introduced - Security:
htmlspecialchars()
is used in the form processing example to prevent XSS vulnerabilities. This is crucial. - File Operations: Demonstrates reading and writing files. Important to remember permissions and security when dealing with files.
isset()
andempty()
: Shows how to check if variables exist and are not empty.- Cookie example: Basic cookie setting and retrieval. This needs to be tested across two separate page requests.
To use these examples:
- Save each example as a
.php
file (e.g.,basic_arithmetic.php
). Make sure your web server is configured to parse PHP. - Place the file in your web server’s document root (e.g.,
htdocs
in XAMPP orwww
in WAMP). - Access the file through your web browser (e.g.,
http://localhost/basic_arithmetic.php
).
Remember to create text_file.txt
and give it suitable content when testing the file read example. For the POST example, you’ll need to create an HTML form that submits to the PHP script. The cookie example will also run in a sequence of requests
This provides a solid foundation for learning basic PHP. Let me know if you’d like more examples or explanations on specific topics.