Creating a full-fledged social media application involves a
substantial amount of code and complexity.
However, I can provide you with a simple example of a PHP script
that illustrates basic user registration and login functionality.
Please note that this is a minimal example, and a real-world
application would require additional features such as user profiles, posts, and
more.
<?php
session_start();
//
Database connection parameters
$servername
= "localhost";
$username
= "your_username";
$password
= "your_password";
$dbname
= "your_database";
//
Create connection
$conn
= new mysqli($servername, $username, $password, $dbname);
//
Check connection
if
($conn->connect_error) {
die("Connection failed: " .
$conn->connect_error);
}
//
Function to create users table if not exists
function
createUsersTable($conn) {
$sql = "CREATE TABLE IF NOT EXISTS
users (
id INT(6) UNSIGNED AUTO_INCREMENT
PRIMARY KEY,
username VARCHAR(30) NOT NULL,
password VARCHAR(255) NOT NULL,
reg_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP
ON UPDATE CURRENT_TIMESTAMP
)";
if ($conn->query($sql) === FALSE) {
echo "Error creating table: "
. $conn->error;
}
}
//
Function to register a new user
function
registerUser($conn, $username, $password) {
$hashedPassword = password_hash($password,
PASSWORD_DEFAULT);
$sql = "INSERT INTO users (username,
password) VALUES ('$username', '$hashedPassword')";
if ($conn->query($sql) === TRUE) {
echo "Registration
successful!";
} else {
echo "Error: " . $sql .
"<br>" . $conn->error;
}
}
//
Function to check user credentials and log in
function
loginUser($conn, $username, $password) {
$sql = "SELECT id, password FROM users
WHERE username='$username'";
$result = $conn->query($sql);
if ($result->num_rows == 1) {
$row = $result->fetch_assoc();
if (password_verify($password,
$row["password"])) {
echo "Login successful!";
$_SESSION['user_id'] =
$row["id"];
} else {
echo "Incorrect password!";
}
} else {
echo "User not found!";
}
}
//
Example usage
createUsersTable($conn);
//
Uncomment and modify the lines below for user registration and login
//
registerUser($conn, "john_doe", "password123");
//
loginUser($conn, "john_doe", "password123");
//
Close connection
$conn->close();
?>
This
script includes functions for creating a "users" table, registering a
new user, and logging in a user. Please make sure to replace
"your_username," "your_password," and
"your_database" with your actual database credentials.
Note:
This example uses plain PHP and MySQL, which may not be suitable for a
production environment due to security concerns. A real-world social media
application would likely involve the use of a PHP framework (e.g., Laravel) and
additional security measures, such as prepared statements and input validation.
0 Comments