Tuesday, December 31, 2024

Here is the simplified version of the code, with only the text chatting functionality retained.

Here is the simplified version of the code, with only the text chatting functionality retained.

Final Version: index.html
This HTML file builds the chat window and handles the user input.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Chat Room</title>
    <style>
        body { 
            font-family: Arial, sans-serif; 
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100vh;
            margin: 0;
        }
        #chat-container {
            text-align: center;
        }
        #chat { 
            height: 500px; 
            overflow-y: scroll; 
            border: 1px solid #ccc; 
            padding: 10px; 
            width: 600px; 
            margin-bottom: 10px;
        }
        #message { width: 400px; }
        #name { display: none; }
    </style>
</head>
<body>
    <div id="chat-container">
        <h1>Chat Room</h1>
        <div id="chat"></div>
        <input type="hidden" id="name" value="">
        <input type="text" id="message" placeholder="Type your message here...">
        <button onclick="sendMessage()">Send</button>
    </div>
    <script>
        let name = 'User' + Math.floor(Math.random() * 10000);
        document.getElementById('name').value = name;

        function sendMessage() {
            let message = document.getElementById('message').value;
            if (message.trim() === '') return;
            let xhr = new XMLHttpRequest();
            xhr.open('POST', 'chat.php', true);
            xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
            xhr.send('name=' + encodeURIComponent(name) + '&message=' + encodeURIComponent(message));
            document.getElementById('message').value = '';
        }

        function loadMessages() {
            let xhr = new XMLHttpRequest();
            xhr.open('GET', 'chat.php', true);
            xhr.onload = function () {
                if (xhr.status === 200) {
                    document.getElementById('chat').innerHTML = xhr.responseText;
                }
            };
            xhr.send();
        }

        document.getElementById('message').addEventListener('keydown', function(event) {
            if (event.key === 'Enter') {
                sendMessage();
                event.preventDefault(); // Prevent the Enter key from submitting the form
            }
        });

        setInterval(loadMessages, 1000);
    </script>
</body>
</html>

Final Version: chat.php
This PHP file handles the chat messages and stores them in a text file.

<?php
$chatFile = '/usr/share/nginx/mydomain.com/chat3/chat.txt';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name = htmlspecialchars($_POST['name']);
    $message = htmlspecialchars($_POST['message']);
    $time = date('H:i:s');

    $entry = "<p><strong>$name</strong> [$time]: $message</p>n";
    if (!file_exists($chatFile)) {
        file_put_contents($chatFile, $entry);
    } else {
        file_put_contents($chatFile, $entry, FILE_APPEND);
    }
    echo 'Message sent';
} else {
    if (file_exists($chatFile)) {
        echo file_get_contents($chatFile);
    } else {
        echo '<p>No messages yet.</p>';
    }
}
?>

Ensure Proper Permissions
Ensure that the chat.txt file exists and has the correct permissions:

touch /usr/share/nginx/mydomain.com/chat3/chat.txt
chmod 666 /usr/share/nginx/mydomain.com/chat3/chat.txt

With these final simplified versions of the code, you will retain a functional text chat room.

Monday, December 30, 2024

Real-time chat application using PHP, AJAX Improved version

Real-time chat application using PHP, AJAX, and file storage. This version includes the functionality of enter key to send a message and center the chat box. The chat messages are saved in a messages.txt file, and every second the chat is updated.

1. Complete Code:
Below is the updated index.php file with the enter key functionality and the chat box centered:

<?php
// index.php
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Real-time Chat</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        $(document).ready(function() {
            // Listen for the Enter key press
            $('#message').keypress(function(event) {
                if (event.which == 13) {  // 13 is the keycode for Enter
                    event.preventDefault();  // Prevent the default line break
                    $('#send').click();  // Trigger the click event of the send button
                }
            });

            // Send message when the send button is clicked
            $('#send').click(function() {
                var message = $('#message').val();
                if (message != '') {
                    $.ajax({
                        url: 'send_message.php',  // PHP file to handle the sending request
                        type: 'POST',
                        data: { message: message },
                        success: function(data) {
                            $('#message').val('');  // Clear the input field
                            loadMessages();  // Load new messages
                        }
                    });
                }
            });

            // Function to load messages
            function loadMessages() {
                $.ajax({
                    url: 'load_messages.php',  // PHP file to load messages
                    type: 'GET',
                    success: function(data) {
                        $('#chatbox').html(data);  // Update the chatbox with new messages
                    }
                });
            }

            // Reload messages every second
            setInterval(loadMessages, 1000);
        });
    </script>
</head>
<body>
    <!-- Center the chat box using a table layout -->
    <table width="100%" height="100%" style="border: none;">
        <tr>
            <td align="center" valign="middle">
                <div id="chat-box" style="width: 600px; background-color: white; padding: 20px; border-radius: 8px; box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);">
                    <div id="chatbox" style="height: 300px; overflow-y: scroll; margin-bottom: 10px;"></div> <!-- Display chat messages -->
                    <textarea id="message" placeholder="Type a message..." style="width: 100%; padding: 10px; font-size: 14px; border: 1px solid #ddd; border-radius: 5px; box-sizing: border-box; margin-bottom: 10px;"></textarea>
                    <button id="send" style="width: 100%; padding: 12px; background-color: #28a745; color: white; border: none; border-radius: 5px; font-size: 16px; cursor: pointer;">Send</button>
                </div>
            </td>
        </tr>
    </table>
</body>
</html>

2. PHP Files to Handle the Messages:
send_message.php – Handles sending the message:

<?php
// send_message.php
if (isset($_POST['message'])) {
    $message = $_POST['message'];
    // Save the message to the file (messages.txt)
    $file = 'messages.txt';
    $currentMessages = file_get_contents($file);
    $currentMessages .= "<p>" . htmlspecialchars($message) . "</p>";
    file_put_contents($file, $currentMessages);
}
?>

load_messages.php – Loads the saved messages:

<?php
// load_messages.php
$file = 'messages.txt';
if (file_exists($file)) {
    echo file_get_contents($file);  // Output the content of messages.txt
}
?>

3. Steps to Make it Work:
Ensure the messages are saved correctly: After sending a message, ensure that it is being saved in the messages.txt file. If the file is not created, you can manually create it:

touch messages.txt
chmod 777 messages.txt  # Give write permission

Verify the messages are displayed correctly: The load_messages.php file will be queried every second by AJAX, and it will return the contents of messages.txt to be displayed in the chat box.

File Permissions: Ensure that messages.txt is both readable and writable by your web server. Set the correct file permissions:

chmod 777 messages.txt

4. Explanation of Features:
Enter key functionality: When the user presses the Enter key in the message input field (#message), it triggers the click event for the Send button, effectively sending the message without needing to click the button manually.

AJAX to load messages: Every second, an AJAX call to load_messages.php is made, which reads the content of the messages.txt file and updates the #chatbox with the new messages.

Centered Chat Box: The entire chat box is centered using a table layout with align=”center” and valign=”middle”. The chat box itself is styled with some padding, a border radius, and a shadow to give it a neat look.

5. Directory and File Structure:
index.php: The main file with the chat interface and functionality.
send_message.php: Handles saving the sent messages.
load_messages.php: Loads and displays the messages from the file.
messages.txt: A text file where chat messages are stored.
6. Final Testing:
After uploading these files to your web server, open the index.php page.
Type a message in the text area and press Enter or click the Send button.
The message should be stored in the messages.txt file and immediately appear in the chat box.
If the chat box isn’t updating, check the browser console for JavaScript errors, and ensure that load_messages.php is returning the correct data.
This implementation provides a simple and functional real-time chat app without using WebSocket or any database, relying instead on file storage for chat history.

Real-time Chat Application using PHP and AJAX

This is a simple real-time chat application built using PHP and AJAX polling. It avoids using WebSocket or any other complex protocols, relying instead on basic HTTP requests (AJAX) to fetch and send messages.

Overview
Backend: PHP handles incoming messages and stores them in sessions.
Frontend: AJAX is used to send and fetch messages without reloading the page.
No Database: All messages are stored temporarily in PHP sessions.
Steps to Set Up
1. Install Required Environment
Make sure you have PHP 8.4 and Nginx installed. You can install them using the following commands:

sudo apt update
sudo apt install nginx php8.4-fpm php8.4-cli php8.4-mbstring

2. Create the PHP Chat Application
Create a folder for your chat application in the web directory (e.g., /var/www/html/chat_app), and create the following files:

a. index.php (Main Chat Interface)

<?php
session_start();

// Initialize session messages if not set
if (!isset($_SESSION['messages'])) {
    $_SESSION['messages'] = [];
}

?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Chat App</title>
    <style>
        #chat-box {
            width: 400px;
            height: 300px;
            border: 1px solid #ccc;
            overflow-y: scroll;
            padding: 10px;
        }
        #message {
            width: 300px;
            padding: 5px;
        }
    </style>
</head>
<body>
    <h1>PHP Chat App</h1>
    <div id="chat-box">
        <?php
        // Display all messages
        foreach ($_SESSION['messages'] as $message) {
            echo "<p><strong>{$message['user']}:</strong> {$message['message']}</p>";
        }
        ?>
    </div>
    <input type="text" id="message" placeholder="Enter your message..." />
    <button onclick="sendMessage()">Send</button>

    <script>
        // Send message using AJAX
        function sendMessage() {
            var message = document.getElementById("message").value;
            if (message.trim() === '') return;

            // Send message to server
            var xhr = new XMLHttpRequest();
            xhr.open('POST', 'send_message.php', true);
            xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
            xhr.onload = function() {
                if (xhr.status == 200) {
                    // Clear input and refresh chat
                    document.getElementById("message").value = '';
                    fetchMessages();
                }
            };
            xhr.send('message=' + encodeURIComponent(message));
        }

        // Fetch new messages every 2 seconds
        function fetchMessages() {
            var xhr = new XMLHttpRequest();
            xhr.open('GET', 'get_messages.php', true);
            xhr.onload = function() {
                if (xhr.status == 200) {
                    document.getElementById('chat-box').innerHTML = xhr.responseText;
                }
            };
            xhr.send();
        }

        // Poll for new messages every 2 seconds
        setInterval(fetchMessages, 2000);
    </script>
</body>
</html>

index.php serves as the main chat interface where users can type messages, and those messages are sent using AJAX to the send_message.php script.
It also periodically fetches new messages from the server every 2 seconds via the fetchMessages() function.
b. send_message.php (Handle Sending Messages)

<?php
session_start();

if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['message'])) {
    $message = $_POST['message'];
    $user = 'User ' . rand(1, 1000); // Random user for demo

    // Save the message in session
    $_SESSION['messages'][] = ['user' => $user, 'message' => $message];

    // Return a success response
    echo 'Message sent';
}
?>

send_message.php receives POST requests containing messages and stores them in PHP sessions.
c. get_messages.php (Fetch Messages)

<?php
session_start();

// Display all messages from session
if (isset($_SESSION['messages'])) {
    foreach ($_SESSION['messages'] as $message) {
        echo "<p><strong>{$message['user']}:</strong> {$message['message']}</p>";
    }
}
?>

get_messages.php returns all stored messages from the session. The client will periodically make requests to this script to display the latest messages.
3. Configure Nginx
You need to configure Nginx to serve your PHP files correctly.

1.Edit the Nginx configuration file:

sudo nano /etc/nginx/sites-available/default

2.Update the configuration to look like this:

server {
    listen 80;
    server_name your-domain.com;

    root /var/www/html/chat_app;  # Update with your chat app directory path

    index index.php index.html index.htm;

    location / {
        try_files $uri $uri/ =404;
    }

    location ~ .php$ {
        fastcgi_pass unix:/var/run/php/php8.4-fpm.sock;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
    }
}

3.Restart Nginx to apply the changes:

sudo systemctl restart nginx

4. Test the Chat Application
Now, you can access your chat application by visiting:

http://your-domain.com

You should see a simple chat interface. After entering a message and clicking the “Send” button, the message will be displayed in the chat box, and the page will automatically update every 2 seconds to show new messages.

Summary
This setup uses AJAX polling to simulate real-time chat without relying on WebSocket or other complex protocols. Every 2 seconds, the client sends a request to the server to fetch new messages. This is a simple solution ideal for small-scale chat applications and doesn’t require a database; all data is stored temporarily in PHP sessions.

If you need to scale the application, consider integrating a database to store messages persistently.

Sunday, December 29, 2024

Deploying Hiddify on Debian 12

Hiddify is a tool designed for bypassing internet censorship and typically offers a simplified deployment process. Here’s how to deploy Hiddify on Debian 12.

Prerequisites
1.A clean Debian 12 server (VPS or dedicated machine).
2.Root or a user with sudo privileges.
3.A domain name pointing to your server’s IP (optional but recommended for SSL/TLS).
Step-by-Step Guide
1. Update System and Install Required Packages
Ensure your system is up-to-date and install essential tools:

sudo apt update && sudo apt upgrade -y
sudo apt install curl wget git -y

2. Download Hiddify Installer
Clone the official Hiddify repository:

git clone https://github.com/hiddify/hiddify-config.git
cd hiddify-config

3. Configure Installation Settings
1.Run the configuration tool to set up initial options:

./hiddify_manager.py config

During this process, you’ll be prompted to set various options:

Domain name: Specify your domain or leave it blank if you don’t have one.
Admin credentials: Set a username and password for managing Hiddify.
Ports: Define ports if necessary (default ports work for most cases).
2.Save the configuration.

4. Install Hiddify
Run the installer:

./install.sh

This script will:

Install required dependencies (e.g., Docker, Python).
Configure and deploy the Hiddify server.
5. Check Installation
Once the installation is complete, the script will display:

The web panel URL for managing Hiddify.
Admin login credentials.
Access the web panel in your browser to verify that the installation was successful.

6. Secure Your Server (Optional but Recommended)
1.Enable a Firewall:

sudo apt install ufw -y
sudo ufw allow OpenSSH
sudo ufw allow 443/tcp
sudo ufw allow 80/tcp
sudo ufw enable

2.Use SSL/TLS: If you didn’t configure a domain during installation, you can add it now and generate a Let’s Encrypt SSL certificate:

./hiddify_manager.py add-domain yourdomain.com

7. Update and Maintenance
To update Hiddify, pull the latest repository changes and run the update script:

git pull
./update.sh

Access and Usage
Client Configuration: The Hiddify web panel provides client configuration files for easy setup.
Admin Panel: Access the admin panel via the displayed URL after installation to manage users, monitor traffic, and adjust settings.
Notes
System Requirements: Hiddify works best with servers that have at least 1GB of RAM and sufficient bandwidth.
Legal Disclaimer: Ensure that you use Hiddify in compliance with your local laws and regulations.
This setup should provide a fully functional Hiddify deployment on Debian 12.

Deploying Nextcloud on Debian 12 with PHP 7.4 or 8.4, Nginx 1.27, and MariaDB 11

This guide outlines the process to deploy Nextcloud on the specified environment.

Steps Overview
Install required dependencies.
Configure the MariaDB database.
Download and set up Nextcloud.
Configure Nginx.
Adjust permissions and folders.
Complete the Nextcloud web installer.
Detailed Steps
1. Update System and Install Required Dependencies
Update your system and install necessary packages:

sudo apt update && sudo apt upgrade -y
sudo apt install nginx mariadb-server php7.4-fpm php7.4-mysql php7.4-xml php7.4-mbstring php7.4-curl php7.4-zip php7.4-intl php7.4-gd php7.4-bcmath php7.4-imagick unzip curl wget -y

For PHP 8.4, replace php7.4 with php8.4.

Additionally, install Redis for caching:

sudo apt install redis-server php7.4-redis -y

2. Configure MariaDB Database
1.Log in to MariaDB:

sudo mysql -u root -p

2.Create a database and user:

CREATE DATABASE nextcloud CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci;
CREATE USER 'nextclouduser'@'localhost' IDENTIFIED BY 'yourpassword';
GRANT ALL PRIVILEGES ON nextcloud.* TO 'nextclouduser'@'localhost';
FLUSH PRIVILEGES;
EXIT;

3. Download and Set Up Nextcloud
1.Download the latest Nextcloud release:

wget https://download.nextcloud.com/server/releases/latest.zip

2.Extract the files to the target directory:

unzip latest.zip -d /var/www/
mv /var/www/nextcloud /var/www/html/

3.Set proper permissions:

sudo chown -R www-data:www-data /var/www/html/nextcloud
sudo chmod -R 750 /var/www/html/nextcloud

4. Configure Nginx
1.Create an Nginx configuration file:

sudo nano /etc/nginx/sites-available/nextcloud

2.Add the following configuration:

server {
    listen 80;
    server_name yourdomain.com;

    root /var/www/html/nextcloud;
    index index.php;

    client_max_body_size 512M;
    fastcgi_buffers 64 4K;

    location / {
        rewrite ^ /index.php;
    }

    location ~ .php$ {
        include snippets/fastcgi-php.conf;
        fastcgi_pass unix:/var/run/php/php7.4-fpm.sock;  # Adjust for your PHP version
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
    }

    location ~ /. {
        deny all;
    }
}

3.Enable the configuration and restart Nginx:

sudo ln -s /etc/nginx/sites-available/nextcloud /etc/nginx/sites-enabled/
sudo systemctl restart nginx

5. Adjust Permissions and Folders
Ensure proper permissions for Nextcloud data:

sudo mkdir -p /var/www/html/nextcloud/data
sudo chown -R www-data:www-data /var/www/html/nextcloud/data
sudo chmod -R 750 /var/www/html/nextcloud/data

6. Complete the Web Installation
1.Open a browser and navigate to your server’s IP or domain:

http://yourdomain.com

2.In the installation page, provide the following details:

Admin Username and Password.
Database Information:
Database user: nextclouduser
Database password: yourpassword
Database name: nextcloud
Database host: localhost
3.Click Finish Installation, and wait for the setup to complete.

7. (Optional) Enable HTTPS
To secure your Nextcloud, enable HTTPS using Let’s Encrypt:

sudo apt install certbot python3-certbot-nginx -y
sudo certbot --nginx -d yourdomain.com

Follow the prompts to configure the SSL certificate.

Testing and Optimization
Test Nextcloud: Ensure file uploads, user creation, and basic features work.
Enable Caching: Configure Redis caching in Nextcloud for better performance.
By following these steps, you can successfully deploy Nextcloud on Debian 12 with PHP 7.4 or 8.4, Nginx 1.27, and MariaDB 11.