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

Print

The document contains code snippets for building a basic user registration and authentication system using PHP and MySQL. It includes PHP code for registration, login, logout, authentication checking, and basic profile and dashboard pages. Database tables are set up to store user accounts and other data like products.

Uploaded by

Khaijin Lim
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)
9 views

Print

The document contains code snippets for building a basic user registration and authentication system using PHP and MySQL. It includes PHP code for registration, login, logout, authentication checking, and basic profile and dashboard pages. Database tables are set up to store user accounts and other data like products.

Uploaded by

Khaijin Lim
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
You are on page 1/ 11

if ($number % 2 == 0) {

echo "<p>" . $number . " is an even number.</p>";


} else {
echo "<p>" . $number . " is an odd number.</p>";
}
case
<?php
$score = 75;
echo "<p>Student's Score: " . $score . "</p>";
echo "<p>Grade: ";
switch (true) {
case ($score >= 80):
echo 'A';
break;
case ($score >= 40):
echo 'D';
break;
default:
echo 'F';
}
echo "</p>";
?>
Get html
<body>
<h1>User Input Form</h1>
<form method="GET" action="process_form_get.php">
<label>Name:</label>
<input type="text" id="name" name="name" required>
<br>
<label>Gender:</label>
<input type="radio" id="male" name="gender" value="Male"> Male
<input type="radio" id="female" name="gender" value="Female"> Female
<br>
<label>Interests:</label>
<input type="checkbox" id="sports" name="interests[]" value="Sports"> Sports
<input type="checkbox" id="music" name="interests[]" value="Music"> Music
<br>
<input type="submit" value="Submit">
</form>
</body>
Get process
<?php
$name = $_GET['name'] ?? '';
$gender = isset($_GET['gender']) ? $_GET['gender'] : "";
$interests = isset($_GET['interests']) ? $_GET['interests'] : [];
echo "Name: $name<br>";
echo "Interests: " . implode(", ", $interests) . "<br>";
?>
POST html
<form method="POST" action="process_form_post.php">
<label>Address:</label>
<textarea id="address" name="address" required></textarea>
<label>Internet Plan:</label>
<select name="plan" required>
<option value="Unifi">Unifi</option>
</select>
Post process
<?php
$username = $_POST['username'] ?? '';
echo "Username: $username<br>";
?>
Database connection
<?php
$con = mysqli_connect("localhost","root","","product_db");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error(); } ?>
register.php
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>User Registration</title>
</head>
<body>
<?php
require('database.php');
if (isset($_REQUEST['username'])){
$username = stripslashes($_REQUEST['username']);
$username = mysqli_real_escape_string($con,$username);
$email = stripslashes($_REQUEST['email']);
$email = mysqli_real_escape_string($con,$email);
$password = stripslashes($_REQUEST['password']);
$password = mysqli_real_escape_string($con,$password);
$reg_date = date("Y-m-d H:i:s");
$query = "INSERT into `users` (username, password, email, reg_date)
VALUES ('$username', '".md5($password)."', '$email', '$reg_date')";
$result = mysqli_query($con,$query);
if($result){
echo "<div class='form'>
<h3>You are registered successfully.</h3>
<br/>Click here to <a href='login.php'>Login</a></div>";
}
}else{
?>
<div class="form">
<h1>User Registration</h1>
<form name="registration" action="" method="post">
<input type="text" name="username" placeholder="Username" required /><br>
<input type="submit" name="submit" value="Register" />
</form>
</div>
<?php } ?>
</body>
</html>
Login.php
require('database.php');
if (isset($_POST['username'])){
$username = stripslashes($_REQUEST['username']);
$username = mysqli_real_escape_string($con,$username);
$password = stripslashes($_REQUEST['password']);
$password = mysqli_real_escape_string($con,$password);
$query = "SELECT *
FROM `users`
WHERE username='$username'
AND password='".md5($password)."'"
;
$result = mysqli_query($con,$query) or die(mysqli_error($con));
$rows = mysqli_num_rows($result);
if($rows==1){
$_SESSION['username'] = $username;
header("Location: index.php");
exit();
}else{
echo "<div class='form'>
<h3>Username/password is incorrect.</h3>
<br/>Click here to <a href='login.php'>Login</a></div>";
}
}else{
?>
<div class="form">
<h1>User Log In</h1>
<form action="" method="post" name="login">
<input type="text" name="username" placeholder="Username" required /><br>
<p>
<label>Remember Me</label>
<input type="checkbox" name="remember_me" id="remember_me">
</p>
</form>
<p>Not registered yet? <a href='registration.php'>Register Here</a></p>
</div>
<?php } ?>
</body>
</html>
Auth.php
<?php
session_start();
if(!isset($_SESSION["username"])){
header("Location: login.php");
exit(); }
?>
Index.php
<?php
include("auth.php");
if (isset($_COOKIE["user"])) {
$cookie_value = $_COOKIE["user"];
echo "Welcome, " . $cookie_value . ". Your cookie is now set.";
} else {
echo "Cookie is not set!";
}
?>
<!DOCTYPE html> …..
<body>
<div class="form">
<p>Welcome <?php echo $_SESSION['username']; ?>!</p>
<p><a href="dashboard.php">User Dashboard</a></p><br>
<a href="logout.php">Logout</a>
</div>
</body>
</html>

Dashboard.php
<?php
include("auth.php");
require('database.php');
?>
<!DOCTYPE html> .....
<body>
<div class="form">
<p>User Dashboard</p>
<p><a href="index.php">Home</a></p>
<a href="logout.php">Logout</a>
</div>
</body>
</html>
Logout.php
<?php
session_start(); if(session_destroy())
{
header("Location: login.php");
exit();
}
?>
Insert.php
include("auth.php");
require('database.php');
$status = "";
if(isset($_POST['new']) && $_POST['new']==1){
$product_name =$_REQUEST['product_name']; .....
$date_record = date("Y-m-d H:i:s");
$submittedby = $_SESSION["username"];
$ins_query="INSERT into products
(`product_name`,`price`,`quantity`,`date_record`,`submittedby`)values
('$product_name','$price','$quantity','$date_record','$submittedby')";
mysqli_query($con,$ins_query)
or die(mysqli_error($con));
$status = "New Product Inserted Successfully.
</br></br><a href='view.php'>View Product Record</a>";
}
?> <!DOCTYPE html> ..... <body>
<p><a href="dashboard.php">User Dashboard</a>
| <a href="logout.php">Logout</a></p>
</body>
</html>
<h1>Insert New Product</h1>
<form name="form" method="post" action="">
<input type="hidden" name="new" value="1" />
<p><input type="text" name="product_name" placeholder="Enter Product Name" required /></p>
<p><input type="number" name="price" step="0.01" min="0" placeholder="Enter Product Price (RM)" required /></p>
<p><input type="number" name="quantity" placeholder="Enter Product Quantity" required /></p>
<p><input name="submit" type="submit" value="Submit" /></p>
</form>
<p style="color:#008000;"><?php echo $status; ?></p>
</body>
</html>
View.php
?>
<!DOCTYPE html> ...... <body>
<h2>View Product Records</h2>
<table width="100%" border="1" style="border-collapse:collapse;">
<thead>
<tr>
<th><strong>No.</strong></th>
<th><strong>Product Name</strong></th>
</tr>
</thead>
<tbody>
<?php
$count=1;
$sel_query="SELECT * FROM products ORDER BY id desc;";
$result = mysqli_query($con,$sel_query);
$currencySymbol = "RM";
while($row = mysqli_fetch_assoc($result)) {
?>
<tr><td align="center"><?php echo $count; ?></td>
<td align="center"><?php echo $row["product_name"]; ?></td>
<td align="center"><?php echo $currencySymbol . $row["price"]; ?></td>
<td align="center"><?php echo $row["quantity"]; ?></td>
<td align="center"><?php echo $row["date_record"]; ?></td>
<td align="center">
<a href="update.php?id=<?php echo $row["id"]; ?>">Update</a>
</td>
<td align="center">
<a href="delete.php?id=<?php echo $row["id"]; ?>" onclick="return confirm('Are you sure
you want to delete this product record?')">Delete</a>
</td>
</tr>
<?php $count++; } ?>
</tbody>
</table>
</body>
</html>
Update.php
if(isset($_POST['new']) && $_POST['new']==1)
{
$id=$_REQUEST['id'];
$product_name =$_REQUEST['product_name'];
$price = str_replace('RM ', '', $_REQUEST['price']);
$quantity =$_REQUEST['quantity'];
$date_record = date("Y-m-d H:i:s");
$submittedby = $_SESSION["username"];
$update="UPDATE products set date_record='".$date_record."',
product_name='".$product_name."', price='".$price."', quantity='".$quantity."',
submittedby='".$submittedby."' where id='".$id."'";
mysqli_query($con, $update) or die(mysqli_error($con));
$status = "Product Record Updated Successfully. </br></br>
<a href='view.php'>View Updated Record</a>";
echo '<p style="color:#008000;">'.$status.'</p>';
}else {
?>
<form name="form" method="post" action="">
<input type="hidden" name="new" value="1" />
<input name="id" type="hidden" value="<?php echo $row['id'];?>" />
<p><input type="text" name="product_name" placeholder="Update Product Name"
required value="<?php echo $row['product_name'];?>" /></p>
<p><input type="text" name="price" placeholder="Update Product Price"
required value="RM <?php echo $row['price'];?>" /></p>
<p><input type="text" name="quantity" placeholder="Update Product Quantity"
required value="<?php echo $row['quantity'];?>" /></p>
<p><input name="submit" type="submit" value="Update" /></p>
</form>
<?php } ?>
</body>
</html>
Delete.php
<?php
require('database.php');
$id=$_GET['id'];
$query = "DELETE FROM products WHERE id=$id";
$result = mysqli_query($con,$query) or die ( mysqli_error($con));
header("Location: view.php");
exit();
?>
Delete cookie.php
<?php
$cookie_name = "user";
if (isset($_COOKIE[$cookie_name])) {
setcookie($cookie_name, "", time() - 3600, "/");
echo "<h3>Cookie deleted. Click here to <a href='logout.php'>Logout</a></h3>";
} else {
echo "<h3>Cookie not found. Click here to <a href='logout.php'>Logout</a></h3>";
}
?>
File_maneger.php
<?php
include("auth.php");
require('database.php');
//File Upload Section
if (isset($_POST['upload'])) {
$uploadedFileName = $_FILES['file']['name'];
$targetDirectory = "upload/";
$targetFilePath = $targetDirectory . $uploadedFileName;
if (move_uploaded_file($_FILES['file']['tmp_name'], $targetFilePath)) {
$userInput = $_POST['user_input'];
$insertQuery = "INSERT INTO files (filename, user_input) VALUES
('$uploadedFileName', '$userInput')";
mysqli_query($con, $insertQuery) or die(mysqli_error($con));
$status = "File uploaded successfully.";
} else {
$status = "File upload failed.";
}
$filesQuery = "SELECT * FROM files";
$filesResult = mysqli_query($con, $filesQuery);
if ($filesResult) {
while ($fileRow = mysqli_fetch_assoc($filesResult)) {
echo "<li>";
echo "<form method='post' enctype='multipart/form-data'>";
echo "<input type='hidden' name='file_id' value='" . $fileRow['id'] . "' />";
echo "<input type='text' name='user_input' value='" . $fileRow['user_input'] . "' />";
echo "<label for='reupload_file'>Re-upload File:</label>";
echo "<input type='file' name='new_file' id='reupload_file' />";
echo "<input type='submit' name='update' value='Update' />";
echo "</form>";
echo " <a href='upload/" . $fileRow['filename'] . "' target='_blank'>View</a>";
echo " | <a href='file_manager.php?delete=" . $fileRow['id'] . "' onclick=\"return
confirm('Are you sure you want to delete this file?')\">Delete</a>";
echo "</li>";
}
}
}
//file updated
if (isset($_POST['update'])) {
$fileId = $_POST['file_id'];
$userInput = $_POST['user_input'];
if ($_FILES['new_file']['size'] > 0) {
$newUploadedFileName = $_FILES['new_file']['name'];
$targetDirectory = "upload/";
$targetFilePath = $targetDirectory . $newUploadedFileName;
if (move_uploaded_file($_FILES['new_file']['tmp_name'], $targetFilePath)) {
$selectQuery = "SELECT filename FROM files WHERE id = $fileId";
$result = mysqli_query($con, $selectQuery);
$row = mysqli_fetch_assoc($result);
$oldFilename = $row['filename'];

$oldFilePath = "upload/" . $oldFilename;


if (file_exists($oldFilePath) && !is_dir($oldFilePath)) {
unlink($oldFilePath);
}

$updateFileQuery = "UPDATE files SET filename = '$newUploadedFileName',


user_input = '$userInput' WHERE id = $fileId";
mysqli_query($con, $updateFileQuery) or die(mysqli_error($con));

$status = "File re-uploaded successfully.";


} else {
$status = "File re-upload failed.";
}
} else {
$updateQuery = "UPDATE files SET user_input = '$userInput' WHERE id = $fileId";
mysqli_query($con, $updateQuery) or die(mysqli_error($con));
$status = "File details updated successfully.";
}
}
//File Delete Section
if (isset($_GET['delete'])) {
$fileId = $_GET['delete'];
$selectQuery = "SELECT filename FROM files WHERE id = $fileId";
$result = mysqli_query($con, $selectQuery);
$row = mysqli_fetch_assoc($result);
$filename = $row['filename'];
$filePath = "upload/" . $filename;
if (file_exists($filePath) && !is_dir($filePath)) {
unlink($filePath);
}
$deleteQuery = "DELETE FROM files WHERE id = $fileId";
mysqli_query($con, $deleteQuery);
$status = "File deleted successfully.";
}
?>
<!DOCTYPE html> …..<body>
<p><a href="dashboard.php">User Dashboard</a> |
<a href="logout.php">Logout</a></p>
<h1>File Manager</h1>
<!-- Form for File Upload section -->
<form enctype="multipart/form-data" method="post" action="">
<input type="text" name="user_input" placeholder="Add comment or note" required />
<input type="file" name="file" required /><br><br>
<input type="submit" name="upload" value="Upload File" /> </form> </body> </html>
Test error
<?php
session_start();
// include("auth.php");
require('database.php');
$status = "";
session_start();
var_dump($_SESSION);
if(isset($_POST['new']) && $_POST['new'] == 1) {
$message = $_REQUEST['message'];
$phone_no = $_REQUEST['phone_no'];
$email = $_REQUEST['email'];
$userId = $_SESSION['user_id'] ?? 0;
if (empty($message) || empty($phone_no) || empty($email) || $userId === 0) {
$errors = array();
if (empty($message)) {
$errors[] = "Message is required.";
}
if (empty($phone_no)) {
$errors[] = "Phone number is required.";
}
if (empty($email)) {
$errors[] = "Email address is required.";
}
if ($userId === 0) {
$errors[] = "User ID is not set properly.";
}
foreach ($errors as $error) {
echo $error . "<br>";
}
} else {
$ins_query = "INSERT INTO test_error (`message`, `phone_no`, `email`, `user_id`)
VALUES ('$message', '$phone_no', '$email', '$userId')";
mysqli_query($con, $ins_query) or die(mysqli_error($con));
$status = "Data has been inserted successfully.";
}
}
?>
<!DOCTYPE html> .....<body>
<p>
<a href="dashboard.php">User Dashboard</a> |
<a href="logout.php">Logout</a>
</p>

<h1>Example Test Error - Insert Data</h1>


<form name="form" method="post" action="">
<input type="hidden" name="new" value="1" />
<p><input type="text" name="message" placeholder="Enter Your Message" required
/></p>
<p><input type="text" name="phone_no" placeholder="Enter Your Phone Number"
required /></p>
<p><input type="text" name="email" placeholder="Enter Your Email Address"
required /></p>
<p><input name="submit" type="submit" value="Submit" /></p>
</form>
<p style="color:#008000;"><?php echo $status; ?></p> </body> </html>
Footer.php
</div>
<footer class="page-footer">
<p>&copy; <?php echo date("Y"); ?> UCCD3243 Server-Side Web Applications Development</p>
</footer> </body></html>
Header.php <!DOCTYPE html>
<html>
<head>
<title>Content-Presentation Separation</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<header class="page-header">
<nav>
<ul>
<li><a href="#">Sample Page</a></li>
<li><a href="index.php">About Us</a></li>
<li><a href="admin_info.php">Update About Us</a></li>
</ul></nav></header> <div class="container">
Mvc folder Config.php
<?php
define('BASE_PATH', dirname(__DIR__) . '/');
define('CONTROLLER_PATH', BASE_PATH . 'mvc/controller/');
define('MODEL_PATH', BASE_PATH . 'mvc/model/');
define('VIEW_PATH', BASE_PATH . 'mvc/view/');
?>
Mvc folder index.php
<?php
require_once 'config.php';
require_once CONTROLLER_PATH . 'HomeController.php';
$homeController = new HomeController();
$content = $homeController->getContent();
include VIEW_PATH . 'home.php';?>
controller folder HomeController.php
<?php
require_once MODEL_PATH . 'content.php';
class HomeController {
public function getContent() {
$contentModel = new Content();
return $contentModel->getContent();
} } ?>
Model folder content.php
<?php
class content {
public function getContent() {
return "Practical 8 - Content-Presentation Separation (MVC - Example)"; } } ?>
view folder home.php
<?php
require_once __DIR__ . '/../config.php';
require_once __DIR__ . '/../controller/HomeController.php';
$homeController = new HomeController();
$content = $homeController->getContent();
?>
<!DOCTYPE html>
<html lang="en"> .....<body> <header>
<h1>Model-View-Controller (MVC)</h1>
</header> <main>
<section>
<h2>Home Page</h2>
<?php
if (!empty($content)) {
echo "<p>$content</p>";
} else {
echo "<p>Content not available.</p>";
}
?> </section> </main> <footer>
<p>&copy; <?php echo date("Y"); ?> UCCD3243 Server-Side Web Applications
Development</p> </footer> </body> </html>
Index.html
<!DOCTYPE html>
<html>
<head>
<title>AJAX CRUD and Live Search</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<h1>AJAX CRUD Application</h1>
<form id="userForm">
<input type="text" id="name" placeholder="Name">
<input type="text" id="email" placeholder="Email">
<button type="button" onclick="addUser()">Add User</button>
</form>
<table id="userTable">
<thead>
<tr>
<th>Name</th>
<th>Email</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<input type="text" id="search" placeholder="Live Search" onkeyup="liveSearch()">
<div id="searchResults">
</div>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="script.js"></script>
</body>
</html>
Script.js
function addUser() {
var name = $('#name').val();
var email = $('#email').val();
$.post('server.php', { action: 'add', name: name, email: email }, function(response) {
displayUsers();
});
}
function displayUsers() {
$.get('server.php', { action: 'display' }, function(response) {
$('#userTable').html(response);
});
}
function liveSearch() {
var searchValue = $('#search').val();
$.get('server.php', { action: 'search', search: searchValue }, function(response) {
$('#searchResults').html(response);
});
}
$(document).ready(function() {
displayUsers();
});
function editUser(userId) {
$.get('server.php', { action: 'getSingleUser', id: userId }, function(response) {
var user = JSON.parse(response);
var updatedName = prompt("Enter updated name:", user.name);
var updatedEmail = prompt("Enter updated email:", user.email);
if (updatedName !== null || updatedEmail !== null) {
$.post('server.php', { action: 'edit', id: userId, name: updatedName, email:
updatedEmail }, function(response) {
displayUsers();
}); } }); }
function deleteUser(userId) {
if (confirm("Are you sure you want to delete this user?")) {
$.post('server.php', { action: 'delete', id: userId }, function(response) { displayUsers(); }); } }
Server.php
<?php
$con = mysqli_connect("localhost", "root", "", "ajax_demo");
if (!$con) {
die("Connection failed: " . mysqli_connect_error());
}
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
if (isset($_GET['action']) && $_GET['action'] === 'display') {
$sql = "SELECT * FROM users";
$result = mysqli_query($con, $sql);
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
echo "<tr><td>" . $row["name"] . "</td><td>" . $row["email"] . "</td>
<td>
<button onclick='editUser(" . $row['id'] . ")'>Edit</button>
<button onclick='deleteUser(" . $row['id'] . ")'>Delete</button>
</td></tr>";
}
} else {
echo "<tr><td colspan='3'>No users found</td></tr>";
}
} elseif (isset($_GET['action']) && $_GET['action'] === 'search') {
$search = $_GET['search'];
$sql = "SELECT * FROM users WHERE name LIKE '%$search%' OR email LIKE
'%$search%'";
$result = mysqli_query($con, $sql);
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
echo "<tr><td>" . $row["name"] . "</td><td>" . $row["email"] . "</td></tr>";
}
} else {
echo "<tr><td colspan='2'>No results found</td></tr>";
}
} elseif (isset($_GET['action']) && $_GET['action'] === 'getSingleUser') {
$userId = $_GET['id'];
$sql = "SELECT * FROM users WHERE id = $userId";
$result = mysqli_query($con, $sql);
if (mysqli_num_rows($result) > 0) {
$user = mysqli_fetch_assoc($result);
echo json_encode($user);
} else {
echo "User not found";
}
}
} elseif ($_SERVER['REQUEST_METHOD'] === 'POST') {
if (isset($_POST['action']) && $_POST['action'] === 'add') {
$name = $_POST['name'];
$email = $_POST['email'];
$sql = "INSERT INTO users (name, email) VALUES ('$name', '$email')";
if (mysqli_query($con, $sql)) {
echo "User added successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($con);
} } elseif (isset($_POST['action']) && $_POST['action'] === 'edit') {
$userId = $_POST['id'];
$name = $_POST['name'];
$email = $_POST['email'];
$sql = "UPDATE users SET name='$name', email='$email' WHERE id=$userId";
if (mysqli_query($con, $sql)) {
echo "User updated successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($con);
}
} elseif (isset($_POST['action']) && $_POST['action'] === 'delete') {
$userId = $_POST['id'];
$sql = "DELETE FROM users WHERE id=$userId";
}
if (mysqli_query($con, $sql)) {
echo "User deleted successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($con); } } ?>
style.css
body {
text-align: center;
font-family: Arial, sans-serif;
}
h1 {
margin-top: 20px;
}
form {
margin-top: 20px;
}
table {
margin: 20px auto;
border-collapse: collapse;
width: 70%;
}
table, th, td {
border: 1px solid #000;
}
th, td {
padding: 10px;
text-align: left;
}
#search, #searchResults {
margin-top: 20px;
}
#search {
width: 50%;
padding: 8px;
}
#searchResults {
border: 1px solid #ccc;
padding: 10px;
width: 50%;
margin: 20px auto;
}
input, button {
padding: 8px;
margin: 5px;
border-radius: 4px;
border: 1px solid #ccc;
}

You might also like