Sunday, January 5, 2025

Use webpage to upload and download files

In the current code, uploaded files are not actually stored on a server. The files are just read and stored temporarily in the browser’s memory using JavaScript FileReader and Blob objects. These files are not uploaded to any server or remote storage, and are instead stored locally in the browser for temporary use.

How the file storage works:
When the user selects a file, it is read into an ArrayBuffer, then converted into a URL using Blob.
This temporary URL is saved in the browser’s memory using a Map object for easy access to the files.
When the user clicks the “Download” button, the file is downloaded using this temporary URL.
However, the file is not saved to any server, meaning if the page is refreshed, the uploaded files will be lost. If you want to save uploaded files on a server and provide download links, you’ll need to implement server-side storage.

Code Functionality:
This code implements a simple webpage file upload download and refresh functionality:

The user can select multiple files to upload, but the files are only stored in the browser’s memory and not uploaded to a server.
The uploaded files are displayed on the page, and users can download these files.
There is a “Refresh Page” button on the page that, when clicked, reloads the entire page and resets the file list.
Code Implementation:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>File Transfer Tool</title>
  <style>
    body { font-family: Arial, sans-serif; text-align: center; padding: 20px; }
    #fileList { margin-top: 20px; }
    button { margin-top: 20px; }
  </style>
</head>
<body>
  <h1>File Transfer Tool</h1>
  <p>Upload and download files using this page.</p>
  
  <!-- File Upload Section -->
  <input type="file" id="fileInput" multiple>
  <button id="uploadBtn">Upload Files</button>
  
  <!-- Refresh Button -->
  <button id="refreshBtn">Refresh Page</button>

  <!-- File List -->
  <div id="fileList">
    <h3>Uploaded Files</h3>
    <ul id="files"></ul>
  </div>

  <script>
    const fileInput = document.getElementById('fileInput');
    const uploadBtn = document.getElementById('uploadBtn');
    const refreshBtn = document.getElementById('refreshBtn');
    const fileList = document.getElementById('files');

    // Store uploaded files in memory
    const uploadedFiles = new Map();

    // File upload functionality
    uploadBtn.addEventListener('click', () => {
      const files = fileInput.files;
      if (files.length === 0) {
        alert('Please select files!');
        return;
      }

      // Store files in memory
      Array.from(files).forEach((file) => {
        const fileURL = URL.createObjectURL(file);  // Create a temporary URL
        uploadedFiles.set(file.name, { file, fileURL });
      });

      alert('Files uploaded successfully');
      // Update the file list
      updateFileList();
    });

    // Update the file list
    function updateFileList() {
      fileList.innerHTML = '';  // Clear the list
      uploadedFiles.forEach((fileData, fileName) => {
        const listItem = document.createElement('li');
        listItem.innerHTML = `
          <span>${fileName}</span>
          <a href="${fileData.fileURL}" download="${fileName}" style="margin-left: 10px;">Download</a>
        `;
        fileList.appendChild(listItem);
      });
    }

    // Refresh page functionality
    refreshBtn.addEventListener('click', () => {
      location.reload();  // Reload the entire page
    });
  </script>
</body>
</html>

Code Explanation:
File Upload Functionality:

When the user clicks the “Upload Files” button, the selected files are given a temporary URL using URL.createObjectURL() and stored in the browser’s memory.
The uploaded files will be displayed on the page by calling updateFileList().
File List Update:

After uploading files, the updateFileList() function is called to refresh the file list on the page. Files are shown with their names and a download link.
Refresh Page:

When the “Refresh Page” button is clicked, location.reload() is called to reload the entire page, simulating a browser refresh. This clears the file list and resets the page content.
—————–
How to upload files to a server
To ensure that uploaded files are stored on the server and can be downloaded, you would need both front-end and back-end implementation:

Frontend: Use the FormData object to send the file to the server.
Backend: The server will receive the file and store it at a designated location.
Example: File upload using Node.js backend
1. Frontend: Uploading files to the server
Here’s an updated version of the front-end code to handle file uploads to the server.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>File Transfer Tool</title>
  <style>
    body { font-family: Arial, sans-serif; text-align: center; padding: 20px; }
    #fileList { margin-top: 20px; }
  </style>
</head>
<body>
  <h1>File Transfer Tool</h1>
  <p>Use this page to upload and download files.</p>
  
  <!-- File upload section -->
  <input type="file" id="fileInput" multiple>
  <button id="uploadBtn">Upload File</button>

  <!-- File list -->
  <div id="fileList">
    <h3>Uploaded Files</h3>
    <ul id="files"></ul>
  </div>

  <script>
    const fileInput = document.getElementById('fileInput');
    const uploadBtn = document.getElementById('uploadBtn');
    const fileList = document.getElementById('files');

    // File upload functionality
    uploadBtn.addEventListener('click', () => {
      const files = fileInput.files;
      if (files.length === 0) {
        alert('Please select a file!');
        return;
      }

      const formData = new FormData();
      for (const file of files) {
        formData.append('files', file);  // Add the file to the FormData object
      }

      // Send the file to the server
      fetch('/upload', {
        method: 'POST',
        body: formData,
      })
      .then(response => response.json())
      .then(data => {
        alert('File uploaded successfully');
        // Update file list (show file paths or information returned from server)
        updateFileList(data.files);
      })
      .catch(error => {
        console.error('File upload failed:', error);
        alert('File upload failed');
      });
    });

    // Update file list
    function updateFileList(files) {
      fileList.innerHTML = '';
      files.forEach(file => {
        const listItem = document.createElement('li');
        listItem.innerHTML = `
          <span>${file.name}</span>
          <a href="${file.url}" download="${file.name}" style="margin-left: 10px;">Download</a>
        `;
        fileList.appendChild(listItem);
      });
    }
  </script>
</body>
</html>

2. Backend: Using Node.js to handle file storage
You can use Node.js with Express and the Multer library to handle the file upload and storage on the server.

First, install the necessary packages:

npm install express multer

Then, set up the Node.js server:

const express = require('express');
const multer = require('multer');
const path = require('path');
const app = express();

// Configure storage settings for uploaded files
const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    cb(null, 'uploads/');  // Folder where the files will be stored
  },
  filename: (req, file, cb) => {
    cb(null, Date.now() + path.extname(file.originalname));  // Filename format
  }
});

const upload = multer({ storage: storage });

// File upload route
app.post('/upload', upload.array('files'), (req, res) => {
  const files = req.files.map(file => ({
    name: file.originalname,
    url: `http://localhost:3000/uploads/${file.filename}`,  // URL to access the file
  }));

  res.json({ files });  // Return file information to the frontend
});

// Serve static files (uploaded files)
app.use('/uploads', express.static('uploads'));

// Start the server
app.listen(3000, () => {
  console.log('Server is running on http://localhost:3000');
});

Explanation:
Frontend: Sends the file to the server using FormData. Upon successful upload, the server returns the file information (name and URL), which is then displayed on the webpage.
Backend: The multer library handles file uploads, stores the files in the uploads/ folder, and generates a URL to access each uploaded file.
How to Test:
1.Start the Node.js server.
2.Open the HTML page and upload a file.
3.Once the file is uploaded, it will be stored on the server in the uploads/ directory, and you can download it by clicking the download link.
This method will actually store the uploaded files on the server, allowing them to be accessed and downloaded by the user.

Saturday, January 4, 2025

How to Check if Sleep Mode is Enabled on Windows 11 Using Command Line

You can use the powercfg command to check the status of sleep mode in Windows 11. Here’s how:

Steps to Check Sleep Mode Status
1.Open Command Prompt as Administrator

Press Win + S, search for Command Prompt.
Right-click on Command Prompt and select Run as administrator.
2.View Power Plan and Sleep Settings Run the following command to view the detailed power plan settings, including sleep mode:

powercfg /query

This will display all current settings, including the timeout for sleep mode under both plugged-in and battery conditions.

3.Check Specific Sleep Timeout To check the specific sleep timeout values:

For sleep timeout on AC power:

powercfg -query SCHEME_CURRENT SUB_SLEEP STANDBYIDLE

For sleep timeout on battery power:

powercfg -query SCHEME_CURRENT SUB_SLEEP STANDBYIDLE

4.Check Hibernate (Standby) Mode Use the following command to see if hibernation is enabled and supported on your system:

powercfg /a
or
powercfg -a

This will list the available power states, including Standby (S3) and Hibernate, if enabled.

Example Output
Example 1: Output for powercfg /query

Power Setting GUID: SUB_SLEEP
Power Setting Name: Sleep idle timeout (AC)
Possible Settings: ...
Current AC Power Setting Index: 30 (minutes)

Example 2: Output for powercfg /a

The following sleep states are available on this system:
    Standby (S3)
    Hibernate

Summary
Sleep Mode Timeout: Use powercfg -query to check sleep mode timeout settings.
Hibernate Mode: Use powercfg /a to verify if hibernation is enabled.
Adjust Settings: If necessary, modify sleep settings using powercfg -change.

How to Disable Sleep and Standby Modes on Windows 11 Using Command Line

Here’s how you can turn off sleep and standby modes using the PowerCfg command on Windows 11:

Steps:
1. Open Command Prompt (Run as Administrator)
Press Win + S and search for “cmd”.
Right-click on “Command Prompt” and select Run as administrator.
2. Disable Sleep Mode
Run the following commands to disable sleep mode:

powercfg -change -standby-timeout-ac 0
powercfg -change -standby-timeout-dc 0

-standby-timeout-ac: Disables sleep mode when plugged into AC power.
-standby-timeout-dc: Disables sleep mode when on battery power.
0: Sets the timeout to 0, effectively disabling sleep mode.
3. Disable Hibernate (Standby) Mode
Run the following command to turn off hibernation:

powercfg -hibernate off

Restore Settings (Optional)
To re-enable sleep or standby modes, use these commands:

To enable sleep mode (e.g., set to 30 minutes):

powercfg -change -standby-timeout-ac 30
powercfg -change -standby-timeout-dc 30

To enable hibernation:

powercfg -hibernate on

Verify the Settings
Run this command to view the current power plan settings:

powercfg /query

Check if the changes have been applied successfully.

With these steps, you can manage sleep and standby modes on your Windows 11 system easily.

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.