Skip to content
Related Articles

Related Articles

Improve Article

Project Idea | Anonymous Message Prank Game in PHP

  • Last Updated : 20 Aug, 2021
Geek Week

In this article, we are going to learn concepts of database, how to make a simple game using PHP and MySQL, how can we implement a database in which we send secret messages for a particular user, how to arrange tables in the database and Also we learn some security issues that how can we save our web apps from these security issues. 

Domain: Web application using PHP and MySQL database.

Features:

  • Sign Up
  • Login
  • Secret Messages to a particular user by using a URL provided by Sign up user
  • Sending messages by Ajax Requests
  • Database

It is a simple game in which users send secret messages for a particular user by using a link. Through this game we learn a lot of things like how to sign up and login to a user by creating a session and destroying session, How can we store data of users and secret messages in the database for a particular user who has created a link for his name.

Tools and Technologies:



Front-End: 

  1. BOOTSTRAP CDN
  2. HTML and CSS

Back-End: 

  1. PHP
  2. JQuery
  3. Database – MySQL

Tools: 

  1. XAMP Server ( for creating server on Localhost )

Project Implementation: Make an empty Folder and create files According to this File structure   

File structure 

Assets folder: First, let us start from the assets folder. So we create this folder because of assets that we use in a project like images, videos, global CSS, and js file which is attached to all files in our project. we also create an index.php file for all folders because if someone is trying to access this folder then he sees only an index page not our directory 

if index.php file is not created then anyone can see our file structure of the whole project 

if index.php is not created in all folders 

After creating index.php in all folders 

 

assets

PHP






<!-- filename - assets/index.php -->
 
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content=
        "width=device-width, initial-scale=1.0">
    <title>Error</title>
</head>
<body>
    403 - Forbidden Error
</body>
</html>

HTML




<!-- filename - assets/css/style.css -->
 
.content {
  min-height: calc(93vh - 70px);
}
.footer {
  background-color: black;
  color: white;
  text-align: center;
  height: 40px;
}
 
.cont{
  height: 300px;
  overflow-y: auto;
}

Utils Folder – make filename as protectXss.php – This file is Basically used to protect our web App from Cross-Site Scripting attacks. 

PHP




<?php
  function protectxss($string) {
    $string=iconv(mb_detect_encoding(
          $string, mb_detect_order(), true),
        "UTF-8", $string
    );
    $string=addcslashes($string,"'");
    $string=addcslashes($string,'"');
    return htmlspecialchars($string);
}
?>

Partials Folder and make files according to file structure as shown: 

partials

Inside the partials folder make a folder named as modals to place all modals in it

Source Code 

PHP




<?php
// Filename partials/action.php
   
// Including all necessary files  
include "dbConnect.php";
include "../utils/protectXss.php";
 
// Signup handler for storing only names of users
if (isset($_POST['startBtn'])) {
    $name=protectxss($_POST['name']);
    $trimname=trim($name);
    $strreplace=str_replace(" ","_",$trimname);
 
    // Assigning them username and password
    $userName=$strreplace."@".time();
    $password = rand();
   
    // Converting to hash format
    $passhash=password_hash($password,PASSWORD_DEFAULT);
    $sql="INSERT INTO `an_users` (`an_id`, `an_name`,
        `an_username`, `an_password`, `timestamp`)
        VALUES (NULL, '$trimname', '$userName',
        '$passhash', current_timestamp())";
 
    $result=mysqli_query($conn,$sql);
 
    if ($result) {
 
        // Creating a session for a user
        session_start();
        $_SESSION['loggedinUser']=$userName;
        $_SESSION['userPass']=$password;
        $_SESSION['name']=$name;
        header("location:../welcome.php");
    }else{
        echo "error"
    }   
}
 
// Login handle
if (isset($_POST['loginBtn'])) {
    $username=protectxss($_POST['username']);
    $password=protectxss($_POST['password']);
 
    $sql="SELECT `an_password`,`an_name` FROM
        `an_users` WHERE `an_username`='$username'";
    $result=mysqli_query($conn,$sql);
    $row=mysqli_fetch_assoc($result);
      
    if (password_verify($password,$row['an_password'])) {
        session_start();
        $_SESSION['loggedinUser']=$username;
        $_SESSION['userPass']=$password;
        $_SESSION['name']=$row['an_name'];
        header("location:../welcome.php");
    } else {
        header("location:../index.php");
    
}
 
// Message Button for sending messages
if (isset($_POST['sendBtn'])) {
    $message=protectxss($_POST['message2']);
    $mycode=protectxss($_POST['mycode2']);
 
    // Inserting messages into another table
    $sql="INSERT INTO `an_messages` (`msg_id`, `msg_text`,
    `an_id`, `timestamp`) VALUES (NULL, '$message',
    '$mycode', current_timestamp())";
     
    $result=mysqli_query($conn,$sql);
 
    if ($result) {
        echo "Message sent";
    }else{
        echo "try Again Later !";
    }   
}
 
?>

PHP




<?php
// Filename - partials/dbConnect.php
   
$hostname="127.0.0.1";
$_username="root";
$password="";
$database="anonymousdb";
$conn=mysqli_connect($hostname,$_username,$password,$database);
?>

PHP




<!-- filename - partials/footer.php -->
   
<footer class="footer">
    <p class="mt-3">Anonymous Prank</p>
 
</footer>
 
</body>
</html>

PHP




<!-- filename - partials/header.php -->
 
<!doctype html>
<html lang="en">
 
<head>
    <meta charset="utf-8">
    <meta name="viewport" content=
        "width=device-width, initial-scale=1">
 
 
    <link href=
        rel="stylesheet" integrity=
"sha384-+0n0xVW2eSR5OomGNYDnhzAbDsOXxcvSN1TPprVMTNDbiYZCxYbOOl7+AMvyTG2x"
        crossorigin="anonymous">
    <link rel="stylesheet" href="assets/css/style.css">
    <script src=
        integrity=
"sha384-gtEjrD/SeCtmISkJkNUaaKMoLD0//ElJ19smozuHV6z3Iehds+3Ulb9Bn9Plx0x4"
        crossorigin="anonymous">
    </script>
</head>
 
<body>

PHP




<!-- filename - partials/index.php -->
   
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content=
        "width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    403 - fobidden error
</body>
</html>

PHP




<!-- filename - partials/navbar.php -->
 
<nav class="navbar navbar-expand-lg navbar-dark bg-dark">
    <div class="container-fluid">
        <a class="navbar-brand" href="index.php">
            Anonymous Prank ????????
        </a>
         
        <button class="navbar-toggler" type="button"
            data-bs-toggle="collapse"
            data-bs-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent"
            aria-expanded="false"
            aria-label="Toggle navigation">
 
            <span class="navbar-toggler-icon"></span>
        </button>
         
        <div class="collapse navbar-collapse"
            id="navbarSupportedContent">
             
            <ul class="navbar-nav me-auto mb-2 mb-lg-0"></ul>
 
            <form class="d-flex">
                <?php
                 
                // Checking a user if he is login or
                // not then showing him logout button    
                if (isset($_SESSION['loggedinUser'])) {
                    echo '<a href="logout.php"
                        class="btn btn-outline-danger">
                        Logout
                    </a>';
                }
 
                // Checking if a user is sending
                // message to other user
                else if (isset($_GET['abcNum'])) {
                    echo '<a class="btn btn-danger"
                        href="index.php">
                        Sign Up
                    </a>';
                }
           
                  // If above conditions are false
                  // then showing him login button
                else {
                    echo '<button type="button"
                        class="btn btn-outline-primary"
                        data-bs-toggle="modal"
                        data-bs-target="#loginmodal">
                        login
                    </button>';
                }
                ?>
            </form>
        </div>
    </div>
</nav>

PHP




<!-- filename - partials/modals/loginmodal.php -->
 
<div class="modal fade" id="loginmodal" tabindex="-1"
    aria-labelledby="exampleModalLabel"
    aria-hidden="true">
     
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title"
                    id="exampleModalLabel">
                    Sign In
                </h5>
                 
                <button type="button" class="btn-close"
                    data-bs-dismiss="modal"
                    aria-label="Close">
                </button>
            </div>
 
            <div class="modal-body">
                <form action="partials/action.php"
                    method="POST">
                     
                    <div class="mb-3">
                        <label for="exampleInputEmail1"
                            class="form-label">
                            Username
                        </label>
                         
                        <input type="email"
                            class="form-control"
                            id="exampleInputEmail1"
                            aria-describedby="emailHelp"
                            name="username">
                    </div>
 
                    <div class="mb-3">
                        <label for="exampleInputPassword1"
                            class="form-label">
                            Password
                        </label>
                         
                        <input type="password"
                            class="form-control"
                            id="exampleInputPassword1"
                            name="password">
                    </div>
 
                    <div class="modal-footer">
                        <button type="button"
                            class="btn btn-danger"
                            data-bs-dismiss="modal">
                            Close
                        </button>
                 
                        <button type="submit"
                            class="btn btn-primary"
                            name="loginBtn">
                            Login
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

Root Folder: Make files according to this structure.

Root folder

Filename – index.php

Create index.php which is the main page of the web app. In this page, we are creating a form that takes the name of the user as input to start the game.

PHP






<?php
session_start();
 
// Checking if a user is logged in or not
if (isset($_SESSION['loggedinUser'])) {
    header("location:welcome.php");
}
  
  
// Including header and dbConnect
include "partials/header.php";
include "partials/dbConnect.php";
  
?>
  
    
// Navbar and login modal  
<?php include "partials/navbar.php" ?>
<?php include "partials/modals/loginmodal.php" ?>
    
    
// Container  
<div class="content">
    <div class="container">
        <div class="p-5 mb-4 bg-light rounded-3 my-3">
            <div class="container-fluid py-5 text-center">
                <h1 class="display-5 fw-bold">
                    Anonymous message Prank Game
                </h1>
                 
                <p class="fs-4">
                    Prank Your Friends by Sending Secret
                    Messages to them They dont able to
                    know who send message to them ????????
                    Enter Your Name to get Started
                </p>
 
  
  
                <div class="container">
 
                <!-- Form to submit the name of a user
                    who is creating quiz for him -->
                    <form class="row" style="float:right;"
                        action="partials/action.php"
                        method="POST">
                         
                        <div class="col-auto">
                            <label for="staticEmail2"
                                class="visually-hidden">
                                Name
                            </label>
                             
                            <label readonly
                                class="form-control-plaintext">
                                Your Name to Get started
                            </label>
                        </div>
 
                        <div class="col-auto">
                            <label for="inputPassword2"
                                class="visually-hidden">
                                Name
                            </label>
                             
                            <input type="text" class="form-control"
                                name="name" placeholder="Name..">
                        </div>
 
                        <div class="col-auto">
                            <button type="submit"
                                class="btn btn-primary mb-3"
                                name="startBtn">
                                Start
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>
  
// Including footer
<?php include "partials/footer.php" ?>

File name – welcome.php 

We are creating this file for seeing messages that are come from other users and providing username and password to the signup user. Along with the username and password a link is also provided so that the signup user shares it with others and others send him anonymous messages. 

welcome.php

PHP




<?php
include "partials/dbConnect.php";
session_start();
  
// Checking for a user if he is login or not
if (!isset($_SESSION['loggedinUser'])) {
    header("location:index.php");
}else{
    $user_name=$_SESSION['loggedinUser'];
}
  
include "partials/header.php";
?>
  
<?php include "partials/navbar.php" ?>
  
<!-- Main Content --> 
<div class="content">
    <div class="container">
        <div class="p-5 mb-4 bg-light rounded-3 my-3">
            <div class="container-fluid py-5 text-center">
 
                <!-- All these values are coming from
                    index.php when user sign up -->
                <h1 class="display-5 fw-bold">
                    Hey????????, <?php echo $_SESSION['name'] ?>
                </h1>
                <h4 class="fw-bold">
                    Your Username - <?php echo $_SESSION['loggedinUser'] ?>
                </h4>
                 
                <h4 class="fw-bold">
                    Password - <?php echo $_SESSION['userPass'] ?>
                </h4>
                 
                <p class="fs-4">
                    Use these crediantials when you login
                    again save them for future reference
                </p>
 
  
                <p class="fs-5 text-info">
                    Reload the page to Load new messages
                </p>
 
  
                <p class="fs-6">
                    Share this URL with your friends so
                    that they can send you messages
                </p>
 
  
                <!-- Creating a Link for other so that
                    others send messages to this user
                    through this Link using base 64
                    encoding to encode username of user
                    in Link -->
                <p class="fs-6 text-success">
                    Link - <?php echo $_SERVER['HTTP_HOST']
                    . "/anonymousprank/anonymous.php?abcNum="
                    . base64_encode($user_name) ?>
                </p>
 
            </div>
        </div>
    </div>
  
    <h4 class="fw-bold container">Messages</h4>
  
    <div class="container cont">
        <div class="row">
            <?php
  
            // Fetching all the messages from the
            // messages table for this particular
            // user only          
            $__username=$_SESSION['loggedinUser'];
            $_sql="SELECT `an_id` FROM `an_users`
                WHERE `an_username`='$__username'";
            $_result = mysqli_query($conn, $_sql);
            $_row = mysqli_fetch_assoc($_result);
     
            $an_u_id=$_row['an_id'];
     
            $sql = "SELECT `msg_text`,`timestamp` FROM
                `an_messages` WHERE `an_id`='$an_u_id'";
            $result = mysqli_query($conn, $sql);
         
            // displaying messages on the page
            while($row = mysqli_fetch_assoc($result)){
            echo '
            <div class="card mx-3 my-2"
                style="width: 18rem;border-radius:21px;
                border: solid aqua 6px;">
                <div class="card-body">
                <p class="card-text">'.$row['msg_text'].'</p>
 
  
                <p class="card-text" style="float:right">
                    '.$row['timestamp'].'
                </p>
 
            </div>
        </div>';       
        }
    ?>
  
    </div>
    </div>
</div>
<?php include "partials/footer.php" ?>

Filename – anonymous.php

We are creating this file for URL which we provided to our sign up users so that they share that URL with their friends and directing friends to this file using that URL

anonymous.php

PHP




<?php
include "partials/dbConnect.php";
include "partials/header.php";
  
if (isset($_GET['abcNum'])) {
 
    // Decoding username of signup
    // user passed inside the url
    $_username = base64_decode($_GET['abcNum']);
}
  
?>
<?php include "partials/navbar.php" ?>
  
<div class="content">
    <div class="container">
        <div class="p-5 mb-4 bg-light rounded-3 my-3">
            <div class="container-fluid py-5 text-center">
                <h1 class="display-5 fw-bold">
                    Hey ????, Anonymous Send a Secret
                    message to
                    <?php
                     
                    // Fetching the name of the user from database
                    $sql = "SELECT `an_name`,an_id FROM `an_users`
                        WHERE `an_username`='$_username'";
                    $result = mysqli_query($conn, $sql);
                    $record = mysqli_num_rows($result);
                      
                    // If find then showing page otherwise
                    // redirecting to main page
                    if ($record>0) {
                        $row = mysqli_fetch_assoc($result);
                        echo $row['an_name'];   
                    }else {
                        header("location:index.php");
                    }
                    ?>
                </h1>
 
                <h3 id="log" class="my-4 text-success"></h3>
  
                <div class="mb-3">
                    <!-- form to send messages to the
                        sign up user  -->
                    <form method="POST" id="sendForm">
                        <textarea class="form-control" id="message"
                            rows="3" name="message" required>
                        </textarea>
                         
                        <input type="hidden" value=
                            <?php echo $row['an_id']?>
                            name="mycode" id="mycode">
                        <button type="submit"
                            class="btn btn-primary my-4 btn-lg"
                            name="sendBtn" id="sendBtn">
                            Send
                        </button>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>
  
                        
<!-- including jquery -- >                      
    integrity=
"sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4="
    crossorigin="anonymous">
</script>
   
<?php include "partials/footer.php" ?>
 
<script>
 
// jQuery                      
$(document).ready(function() {
     
    /* Targetting form to send a message using
    ajax and pass data in the form of object
    and getting response*/
                        
    $("#sendForm").submit(function(e){
        e.preventDefault();   
        let mycode = $("#mycode").val();
        let message = $("#message").val();
     
        $.post("partials/action.php", {
            sendBtn:true,
            mycode2: mycode,
            message2: message
        },
        (data)=>{
            $("#log").html(data)
            setTimeout(() => {
                $("#log").html("")
            }, 2000);
         
            $("#message").val("")
        });
    });
});
 
</script>

Filename – logout.php

To logout users and destroying sessions.

PHP




<?php
session_start();
session_destroy();
session_unset();
 
header("location:index.php")
?>

Database: Start XAMP Server

Xamp Server Strat apache and mySQL

Go to browser and type 127.0.0.1 in the addressbar

Go to phpmyadmin and create a new database named as “anonymousdb” 

Database Structure 

Make tables according to this below structures shown 

Table name – “an_users”

To make a column unique click on “more” near “drop” and select “unique”

an_users

Table name –  “an_messages”

an_messages

Output




My Personal Notes arrow_drop_up
Recommended Articles
Page :