Building an Pastebin Clone with PHP , MySQL & JS

Building an Pastebin Clone with PHP , MySQL & JS

Step 01: Setting Up Environment

  1. Install XAMPP or any other PHP MySQL web server.
  2. Start the Apache and MySQL services in XAMPP.

Step 02: Database Setup

  1. Open phpMyAdmin or any other MySQL administration tool.
  2. Create a new database named “pastebin”.
  3. Create a table named “paste” with the following structure:
    • id (INT, Primary Key, Auto Increment)
    • content (TEXT)
    • created_at (TIMESTAMP
CREATE TABLE pastes (
  id INT AUTO_INCREMENT PRIMARY KEY,
  content TEXT,
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

Step 03: Frontend Setup

  1. Create an HTML file (index.html) for the frontend.
  2. Design a simple form to accept paste content and title.
  3. Include JavaScript for form validation and AJAX requests.

Index.html without any styles , we will style it later , this are the basic requirements for textarea and a submit button

<div>
<textarea id="pasteContent" placeholder="Enter hereeeeeee" >

</textarea>

<button onclick="createPaste()">Create</button>

<div id="result"> 
<!-- This is for links which will get after creation -->
</div>

<!-- Add jquery for ajax request-->

</div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>

<script src="script.js"></script>

Step 04: Database Connection

Config.php for the Sql Connection : here localhost is your sql server , root is user , blank is password and pastebin is db name

<?php

// MySQL database credentials
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "pastebin";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";

?>

In this config.php file:

  • $servername is set to “localhost” as your MySQL server is running locally.
  • $username is set to “root” as it’s the default username for MySQL in XAMPP.
  • $password is left blank as there’s no password set for the “root” user in XAMPP by default. (Note: In a production environment, you should never leave the password blank. Always use a secure password.)
  • $dbname is set to “pastebin” as that’s the name of your database.

This script establishes a connection to the MySQL database using the provided credentials. If the connection fails, it will display an error message. If the connection is successful, it will display “Connected successfully”.

Step 05 : create an file named create.php for saving content in database

<?php
 include('config.php');

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $content = $_POST['content'];

    $stmt = $conn->prepare('INSERT INTO pastes (content) VALUES (?)');
    $stmt->bind_param('s', $content);
    $stmt->execute();

    $stmt->close();
    echo json_encode(['success' => true, 'id' => $conn->insert_id]);
} else {
    echo json_encode(['error' => 'Invalid request method']);
}

$conn->close();
?>

It’s using prepared statements to prevent SQL injection vulnerabilities, which is great for security. Here’s a breakdown of what it does:

  1. It includes the config.php file to establish a connection to the database.
  2. It checks if the request method is POST.
  3. It retrieves the paste content from the POST request.
  4. It prepares an INSERT statement to insert the paste content into the “pastes” table.
  5. It binds the content parameter to the prepared statement.
  6. It executes the prepared statement.
  7. It closes the statement.
  8. If the insertion is successful, it returns a JSON response with a success message and the ID of the inserted row.
  9. If the request method is not POST, it returns a JSON response with an error message.
  10. Finally, it closes the database connection.

Step 06 : create an script.js for triggering create.php

function createPaste() {

const content = document.getElementById('pasteContent').value;
$.ajax({
 type:'POST',
 url: 'create.php',
 data: {content:content},
 dataType: 'json',
 success: function (response) {
  if (response.success) {
    const pasteId = response.id;
    const resultDiv = document.getElementById('result');
    resultDiv.innerHTML = `<p> Your Paste <a href="view.php?id=${pasteId}" >View </a></p>`;
  } else {

    alert('Error');
  }



}, 
error: function () {

    alert('Error')
}

}); 

}

Step 07 : create an view.php for retreiving saved snippets from database

<?php

include('config.php');

if (isset($_GET['id'])) {
    $id = $_GET['id'];

    $stmt = $conn->prepare('SELECT content FROM pastes WHERE id = ?');
    $stmt->bind_param('i', $id);
    $stmt->execute();
    $stmt->bind_result($content);

    if ($stmt->fetch()) {
        echo nl2br($content);
    } else {
        echo 'Paste not found';
    }

    $stmt->close();
} else {
    echo 'Invalid request';
}

$conn->close();
?>

Step 08 : open it in browser to see it in action

Step 09 : Let’s modify its frontend , update index.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Pastebin</title>
<style>
  body {
    font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
    margin: 0;
    padding: 0;
    background-color: #f6f6f6;
  }
  header {
   text-align: center;
   margin:0px;
    z-index: 1000;
     font-size:30px;   
     border-radius: 8px;
     font-weight:bold;

    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  }
  footer {
    background-color: #333;
    color: #fff;
    text-align: center;
    padding: 10px 0;
    position: fixed;
    bottom: 0;
    left: 0;
    width: 100%;
  }
  .container {
    margin-top: 70px; /* To prevent content from being hidden under fixed header */
    padding: 20px;
    text-align: center;
  }
  #pasteContent {
    width: calc(100% - 40px);
    max-width: 600px;
    height: 200px;
    padding: 15px;
    margin-bottom: 20px;
    border: 1px solid #ccc;
    border-radius: 8px;
    resize: none;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  }
  button {
    padding: 12px 24px;
    background-color: #4CAF50;
    color: #fff;
    border: none;
    cursor: pointer;
    border-radius: 8px;
    transition: background-color 0.3s;
  }
  button:hover {
    background-color: #45a049;
  }
</style>
</head>
<body>
<header>
   PasteBiN
</header>
<div class="container">
  <form id="pasteForm">
    <textarea id="pasteContent" placeholder="Enter paste content here"></textarea>
    <br>
    <button type="button" onclick="createPaste()">Create</button>
  </form>
  <div id="result"></div>
</div>
<footer>
  &copy; 2024 Pastebin
</footer>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script src="script.js"></script>
</body>
</html>

Get complete code from github : https://github.com/Ajinkgupta/pastebin-clone

Ajink Gupta
Ajink Gupta
Articles: 54