0% found this document useful (0 votes)
10 views

Codes of PHP

Uploaded by

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

Codes of PHP

Uploaded by

selinasacc190
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 7

#Using mysqli_connect

#login.php with form validation


<?php
session_start();
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$conn = mysqli_connect("localhost", "root", "", "your_database_name");
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$email = $_POST['email'];
$password = $_POST['password'];
$query = "SELECT * FROM users WHERE email='$email' AND password='$password'";
$result = mysqli_query($conn, $query);
if (mysqli_num_rows($result) == 1) {
setcookie("user_email", $email, time() + (86400 * 30), "/"); // 30-day
cookie
setcookie("loggedin", true, time() + (86400 * 30), "/");
$_SESSION['loggedin'] = true;
header("Location: form.php");
exit();
} else {
echo "Invalid email or password.";
}
mysqli_close($conn);
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Login</title>
<script>
function validateForm() {
const email = document.forms["loginForm"]["email"].value;
const password = document.forms["loginForm"]["password"].value;
if (!email || !password) {
alert("Both email and password are required.");
return false;
}
// Basic email format validation
const emailPattern = /^[^ ]+@[^ ]+\.[a-z]{2,3}$/;
if (!email.match(emailPattern)) {
alert("Please enter a valid email address.");
return false;
}
if (password.length < 6) {
alert("Password must be at least 6 characters long.");
return false;
}
return true;
}
</script>
</head>
<body>
<form name="loginForm" method="post" action="login.php" onsubmit="return
validateForm()">
<label>Email:</label><br>
<input type="email" name="email" required><br><br>
<label>Password:</label><br>
<input type="password" name="password" required><br><br>
<input type="submit" value="Login">
</form>
</body>
</html>
#Form.php
<?php
session_start();
if (!isset($_SESSION['loggedin']) || $_SESSION['loggedin'] !== true) {
header("Location: login.php");
exit();
}
$conn = mysqli_connect("localhost", "root", "", "your_database_name");
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$name = $_POST['name'];
$email = $_POST['email'];
$age = $_POST['age'];
$gender = $_POST['gender'];
$dob = $_POST['dob'];
$number = $_POST['number'];
$checkbox = isset($_POST['checkbox']) ? 1 : 0;
$query = "INSERT INTO form_data (name, email, age, gender, dob, number,
checkbox) VALUES ('$name', '$email', '$age', '$gender', '$dob', '$number',
'$checkbox')";
if (mysqli_query($conn, $query)) {
echo "Data saved successfully!";
} else {
echo "Error: " . mysqli_error($conn);
}
mysqli_close($conn);
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Form</title>
</head>
<body>
<form method="post" action="form.php">
<label>Name:</label><br>
<input type="text" name="name" required><br><br>
<label>Email:</label><br>
<input type="email" name="email" required><br><br>
<label>Age:</label><br>
<input type="number" name="age" required><br><br>
<label>Gender:</label><br>
<input type="radio" name="gender" value="Male" required> Male
<input type="radio" name="gender" value="Female" required> Female<br><br>
<label>Date of Birth:</label><br>
<input type="date" name="dob" required><br><br>
<label>Phone Number:</label><br>
<input type="number" name="number" required><br><br>
<label>Agree to Terms:</label>
<input type="checkbox" name="checkbox"><br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
#Using PDO
#login.php
<?php
session_start();
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$dsn = 'mysql:host=localhost;dbname=your_database_name';
$username = 'root';
$password = '';
try {
$pdo = new PDO($dsn, $username, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$email = $_POST['email'];
$password = $_POST['password'];
$stmt = $pdo->prepare("SELECT * FROM users WHERE email = :email AND
password = :password");
$stmt->execute(['email' => $email, 'password' => $password]);
if ($stmt->rowCount() == 1) {
setcookie("user_email", $email, time() + (86400 * 30), "/"); // 30-day
cookie
setcookie("loggedin", true, time() + (86400 * 30), "/");
$_SESSION['loggedin'] = true;
header("Location: form.php");
exit();
} else {
echo "Invalid email or password.";
}
} catch (PDOException $e) {
echo "Error: " . $e->getMessage();
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Login</title>
<script>
function validateForm() {
const email = document.forms["loginForm"]["email"].value;
const password = document.forms["loginForm"]["password"].value;
if (!email || !password) {
alert("Both email and password are required.");
return false;
}
// Basic email format validation
const emailPattern = /^[^ ]+@[^ ]+\.[a-z]{2,3}$/;
if (!email.match(emailPattern)) {
alert("Please enter a valid email address.");
return false;
}
if (password.length < 6) {
alert("Password must be at least 6 characters long.");
return false;
}
return true;
}
</script>
</head>
<body>
<form name="loginForm" method="post" action="login.php" onsubmit="return
validateForm()">
<label>Email:</label><br>
<input type="email" name="email" required><br><br>
<label>Password:</label><br>
<input type="password" name="password" required><br><br>
<input type="submit" value="Login">
</form>
</body>
</html>
#Form.php
<?php
session_start();
if (!isset($_SESSION['loggedin']) || $_SESSION['loggedin'] !== true) {
header("Location: login.php");
exit();
}
$dsn = 'mysql:host=localhost;dbname=your_database_name';
$username = 'root';
$password = '';
try {
$pdo = new PDO($dsn, $username, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$name = $_POST['name'];
$email = $_POST['email'];
$age = $_POST['age'];
$gender = $_POST['gender'];
$dob = $_POST['dob'];
$number = $_POST['number'];
$checkbox = isset($_POST['checkbox']) ? 1 : 0;
$stmt = $pdo->prepare("INSERT INTO form_data (name, email, age, gender,
dob, number, checkbox) VALUES
(:name, :email, :age, :gender, :dob, :number, :checkbox)");
$stmt->execute([
'name' => $name,
'email' => $email,
'age' => $age,
'gender' => $gender,
'dob' => $dob,
'number' => $number,
'checkbox' => $checkbox
]);
echo "Data saved successfully!";
}
} catch (PDOException $e) {
echo "Error: " . $e->getMessage();
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Form</title>
</head>
<body>
<form method="post" action="form.php">
<label>Name:</label><br>
<input type="text" name="name" required><br><br>
<label>Email:</label><br>
<input type="email" name="email" required><br><br>
<label>Age:</label><br>
<input type="number" name="age" required><br><br>
<label>Gender:</label><br>
<input type="radio" name="gender" value="Male" required> Male
<input type="radio" name="gender" value="Female" required> Female<br><br>
<label>Date of Birth:</label><br>
<input type="date" name="dob" required><br><br>
<label>Phone Number:</label><br>
<input type="number" name="number" required><br><br>
<label>Agree to Terms:</label>
<input type="checkbox" name="checkbox"><br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
#Rest API
<?php
header("Content-Type: application/json; charset=UTF-8");
// Database connection
$host = "localhost"; // Host
$db = "api_example"; // Database name
$user = "root"; // MySQL user
$pass = ""; // MySQL password (default is empty for XAMPP)
$conn = new mysqli($host, $user, $pass, $db);
// Check connection
if ($conn->connect_error) {
die(json_encode(["error" => "Connection failed: " . $conn->connect_error]));
}
// Get the user ID from query string
if (isset($_GET['id'])) {
$user_id = $_GET['id'];
// Prepare the SQL query to fetch user info by ID
$sql = "SELECT * FROM users WHERE id = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("i", $user_id); // "i" for integer
$stmt->execute();
// Get the result
$result = $stmt->get_result();
if ($result->num_rows > 0) {
// Fetch user data
$user_data = $result->fetch_assoc();
echo json_encode($user_data); // Output data in JSON format
} else {
echo json_encode(["error" => "User not found"]);
}
$stmt->close();
} else {
echo json_encode(["error" => "No user ID provided"]);
}
// Close connection
$conn->close();
?>
#Array , file function
<!DOCTYPE html>
<html>
<head>
<title>PHP Array and File/Image Handling</title>
</head>
<body>
<h1>PHP Array and File/Image Handling Demonstration</h1>
<h2>Array Handling</h2>
<pre>
<?php
// Indexed Array
$indexedArray = array("Apple", "Banana", "Cherry");
echo "Indexed Array:\n";
print_r($indexedArray);
// Associative Array
$associativeArray = array("John" => 25, "Jane" => 30, "Joe" => 35);
echo "\nAssociative Array:\n";
print_r($associativeArray);
// Multidimensional Array
$multiArray = array(
"Fruits" => array("Apple", "Banana", "Cherry"),
"Vegetables" => array("Carrot", "Broccoli", "Peas")
);
echo "\nMultidimensional Array:\n";
print_r($multiArray);
// Array Functions
echo "\nArray Functions:\n";
// array_merge
$mergedArray = array_merge($indexedArray, $associativeArray);
echo "Merged Array:\n";
print_r($mergedArray);
// array_push
array_push($indexedArray, "Date");
echo "After array_push:\n";
print_r($indexedArray);
// array_pop
array_pop($indexedArray);
echo "After array_pop:\n";
print_r($indexedArray);
// array_keys
$keys = array_keys($associativeArray);
echo "Array Keys:\n";
print_r($keys);
// array_values
$values = array_values($associativeArray);
echo "Array Values:\n";
print_r($values);
// array_unique
$uniqueArray = array_unique(array("Apple", "Banana", "Apple", "Cherry"));
echo "Unique Array:\n";
print_r($uniqueArray);
// in_array
$inArray = in_array("Apple", $indexedArray);
echo "Is 'Apple' in indexedArray? " . ($inArray ? "Yes" : "No") . "\n";
// array_search
$searchIndex = array_search("Banana", $indexedArray);
echo "Index of 'Banana' in indexedArray: " . $searchIndex . "\n";
?>
</pre>
<h2>File Handling</h2>
<pre>
<?php
// File Handling
$filename = "example.txt";
$fileContent = "Hello, this is a sample text file.";
// Write to a file using fopen, fwrite, and fclose
$file = fopen($filename, "w");
if ($file) {
fwrite($file, $fileContent);
fclose($file);
echo "File written successfully.\n";
} else {
echo "Unable to open file for writing.\n";
}
// Read from a file using fopen, fread, and fclose
$file = fopen($filename, "r");
if ($file) {
$content = fread($file, filesize($filename));
fclose($file);
echo "Content of the file:\n" . $content . "\n";
} else {
echo "Unable to open file for reading.\n";
}
// Append to a file using fopen, fwrite, and fclose
$file = fopen($filename, "a");
if ($file) {
fwrite($file, "\nThis is an appended line.");
fclose($file);
echo "Content after appending:\n" . file_get_contents($filename) . "\
n";
} else {
echo "Unable to open file for appending.\n";
}
// Delete a file
if (file_exists($filename)) {
unlink($filename);
echo "File deleted successfully.\n";
} else {
echo "File does not exist.\n";
}
?>
</pre>

You might also like