MCA PHP Practical Programs
E1. Process a Form
<form method="post">
Name: <input type="text" name="name">
<input type="submit">
</form>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
echo "Hello, " . htmlspecialchars($_POST["name"]);
}
?>
E2. Cookies
<?php
setcookie("user", "John", time()+3600);
echo $_COOKIE["user"];
setcookie("user", "", time() - 3600); // Delete
?>
E3. Sessions
<?php
session_start();
$_SESSION["user"] = "John";
echo $_SESSION["user"];
session_destroy(); // Delete
?>
E4. Class and Object
<?php
class Car {
public $color = "red";
function drive() {
return "Driving";
}
}
$car = new Car();
echo $car->drive();
?>
E5. Create and Show MySQL Table
<?php
$conn = new mysqli("localhost", "root", "", "test");
$conn->query("CREATE TABLE IF NOT EXISTS users (id INT AUTO_INCREMENT PRIMARY
KEY, name VARCHAR(50))");
$result = $conn->query("SELECT * FROM users");
while($row = $result->fetch_assoc()) {
echo $row["name"] . "<br>";
}
?>
E6. Update Table
<?php
$conn = new mysqli("localhost", "root", "", "test");
$conn->query("UPDATE users SET name='Alice' WHERE id=1");
?>
E7. Image with Text (GD)
<?php
$image = imagecreate(200, 50);
$bg = imagecolorallocate($image, 255, 255, 255);
$text = imagecolorallocate($image, 0, 0, 0);
imagestring($image, 5, 50, 15, "Hello", $text);
header("Content-Type: image/png");
imagepng($image);
imagedestroy($image);
?>
E8. XML File
<?php
$xml = simplexml_load_file("data.xml");
foreach($xml->children() as $child) {
echo $child->name . "<br>";
}
?>
E9. Include and Require
<?php
include 'file1.php';
require 'file2.php';
?>
E10. Types of Arrays
<?php
$indexed = [1, 2, 3];
$associative = ["a" => 1, "b" => 2];
$multidimensional = [[1, 2], [3, 4]];
?>
E11. Search in Array
<?php
$arr = [1, 2, 3];
if (in_array(2, $arr)) echo "Found";
?>
E12. Print Array
<?php
$arr = [1, 2, 3];
print_r($arr);
var_dump($arr);
?>
E13. Array Sorting
<?php
$arr = [3, 1, 2];
sort($arr);
rsort($arr);
asort($arr);
ksort($arr);
?>
E14. Chunk String
<?php
$str = "abcdef";
print_r(str_split($str, 2));
?>
E15. Validate Email
<?php
$email = "
[email protected]";
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "Valid";
} else {
echo "Invalid";
}
?>