Sure, here's an example code for a simple chat app that uses PHP, MySQL, and JavaScript. This app will allow users to register, login, and send messages to each other.
- Create a MySQL database called "chatdb" and a table called "users". The table should have three columns: id (INT, auto-increment), username (VARCHAR(255)), and password (VARCHAR(255)).
- Create a second table called "messages". The table should have four columns: id (INT, auto-increment), sender (VARCHAR(255)), receiver (VARCHAR(255)), and message (TEXT).
index.php:
<?php
session_start();
if (isset($_SESSION['username'])) {
// Redirect to chat page if user is logged in
header('Location: chat.php');
exit;
}
$errors = array();
if (isset($_POST['register'])) {
// Handle registration form
$username = $_POST['username'];
$password = $_POST['password'];
// Connect to database
$conn = mysqli_connect('localhost', 'root', '', 'chatdb');
// Check if username already exists
$checkQuery = "SELECT * FROM users WHERE username='$username'";
$result = mysqli_query($conn, $checkQuery);
if (mysqli_num_rows($result) > 0) {
$errors[] = 'Username already exists';
}
if (count($errors) == 0) {
// Insert new user into database
$passHash = password_hash($password, PASSWORD_DEFAULT);
$insertQuery = "INSERT INTO users (username, password) VALUES ('$username', '$passHash')";
mysqli_query($conn, $insertQuery);
$_SESSION['username'] = $username;
header('Location: chat.php');
exit;
}
}
if (isset($_POST['login'])) {
// Handle login form
$username = $_POST['username'];
$password = $_POST['password'];
$conn = mysqli_connect('localhost', 'root', '', 'chatdb');
// Check if username and password combination exists
$checkQuery = "SELECT * FROM users WHERE username='$username'";
$result = mysqli_query($conn, $checkQuery);
$user = mysqli_fetch_assoc($result);
if (mysqli_num_rows($result) == 1 && password_verify($password, $user['password'])) {
$_SESSION['username'] = $username;
header('Location: chat.php');
exit;
} else {
$errors[] = 'Invalid username or password';
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Chat App</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div class="container">
<h1>Welcome to the Chat App</h1>
<?php if (count($errors) > 0): ?>
<div class="errors">
<?php foreach ($errors as $error): ?>
<p><?php echo $error; ?></p>
<?php endforeach; ?>
</div>
<?php endif; ?>
<div class="auth-form">
<h2>Register</h2>
<form method="post" action="index.php">
<label>Username</label>
<input type="text" name="username" required>
<label>Password</label>
<input type="password" name="password" required>
<button type="submit" name="register">Register</button>
</form>
</div>
<div class="auth-form">
<h2>Login</h2>
<form method="post" action="index.php">
<label>Username</label>
<input type="text" name="username" required>
<label>Password</label>
<input type="password" name="password" required>
<button type="submit" name="login">Login</button>
</form>
</div>
</div>
</body>
</html>
chat.php:
<?php
session_start();
if (!isset($_SESSION['username'])) {
// Redirect to login page if user is not logged in
header('Location: index.php');
exit;
}
$conn = mysqli_connect('localhost', 'root', '', 'chatdb');
// Get list of users (excluding the current user)
$userQuery = "SELECT username FROM users WHERE username != '{$_SESSION['username']}'";
$usersResult = mysqli_query($conn, $userQuery);
// Handle message sending
if (isset($_POST['sendBtn'])) {
$sender = $_SESSION['username'];
$receiver = $_POST['receiver'];
$message = $_POST['message'];
// Insert new message into database
$insertQuery = "INSERT INTO messages (sender, receiver, message) VALUES ('$sender', '$receiver', '$message')";
mysqli_query($conn, $insertQuery);
}
// Get list of messages between current user and selected user
if (isset($_GET['user'])) {
$receiver = $_GET['user'];
$messageQuery = "SELECT * FROM messages WHERE (sender='{$_SESSION['username']}' AND receiver='$receiver') OR (sender='$receiver' AND receiver='{$_SESSION['username']}') ORDER BY id ASC";
$messageResult = mysqli_query($conn, $messageQuery);
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Chat App</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div class="container">
<h1>Welcome to the Chat App, <?php echo $_SESSION['username']; ?>!</h1>
<div class="users">
<h2>Users</h2>
<ul>
<?php while ($user = mysqli_fetch_assoc($usersResult)): ?>
<li><a href="?user=<?php echo $user['username']; ?>"><?php echo $user['username']; ?></a></li>
<?php endwhile; ?>
</ul>
</div>
<?php if (isset($_GET['user'])): ?>
<div class="chat">
<h2>Chatting with <?php echo $_GET['user']; ?></h2>
<div class="messages">
<?php while ($message = mysqli_fetch_assoc($messageResult)): ?>
<div class="message <?php echo $message['sender'] == $_SESSION['username'] ? 'sent' : 'received'; ?>">
<p><?php echo $message['message']; ?></p>
</div>
<?php endwhile; ?>
</div>
<form method="post" action="">
<input type="hidden" name="receiver" value="<?php echo $_GET['user']; ?>">
<input type="text" name="message" required>
<button type="submit" name="sendBtn">Send</button>
</form>
</div>
<?php endif; ?>
<a href="logout.php">Logout</a>
</div>
</body>
</html>
styles.css:
* {
box-sizing: border-box;
margin: 0;
padding: 0;
}
body {
font-family: Arial, sans-serif;
}
.container {
max-width: 800px;
margin: 0 auto;
padding: 20px;
}
.errors {
background-color: #fcc;
padding: 10px;
margin: 10px 0;
}
.auth-form {
background-color: #f2f2f2;
border-radius: 5px;
padding: 20px;
margin: 10px 0;
}
.auth-form h2 {
margin-top: 0;
}
.auth-form label {
display: block;
margin-bottom: 5px;
}
.auth-form input[type="text"],
.auth-form input[type="password"] {
width: 100%;
padding: 10px;
border-radius: 5px;
border: none;
margin-bottom: 10px;
}
.auth-form button[type="submit"] {
background-color: #1c1c1c;
color: #fff;
padding: 10px 20px;
border: none;
border-radius: 5px;
cursor: pointer;
}
.users {
background-color: #f2f2f2;
border-radius: 5px;
padding: 20px;
margin: 10px 0;
}
.users h2 {
margin-top: 0;
}
.users ul {
list-style: none;
padding: 0;
margin: 0;
}
.users a {
display: block;
padding: 10px;
text-decoration: none;
color: #000;
border-radius: 5px;
margin-bottom: 10px;
}
.users a:hover {
background-color: #eee;
}
.chat {
background-color: #f2f2f2;
border-radius: 5px;
padding: 20px;
margin: 10px 0;
}
.chat h2 {
margin-top: 0;
}
.chat .messages {
height: 400px;
overflow-y: scroll;
}
.chat .message {
padding: 10px;
border-radius: 5px;
margin-bottom: 10px;
}
.chat .message.sent {
background-color: #b3ddef;
text-align: right;
}
.chat .message.received {
background-color: #c1e8c1;
text-align: left;
}
.chat input[type="text"] {
padding: 10px;
border-radius: 5px;
width: 80%;
margin-right: 10px;
}
.chat button[type="submit"] {
background-color: #1c1c1c;
color: #fff;
padding: 10px 20px;
border: none;
border-radius: 5px;
cursor: pointer;
}
a {
display: block;
margin-top: 10px;
color: blue;
}
logout.php:
<?php
session_start();
session_unset();
session_destroy();
header('Location: index.php');
exit;
?>
Please note that this is just an example code and may need to be modified and optimized based on your specific requirements.