Why in my site i can't put information into txt files

Website URL

schats.rf.gd
(please specify the URL of the site on which you are experiencing the problem)

Error Message

no error message
(please share the FULL error message you see, if applicable)

Other Information

you know topic name says that
(other information and details relevant to your question)

code that crahes:

<?php
session_start();

// Patikriname, ar naudotojas prisijungęs
if (!isset($_SESSION['username'])) {
    header("Location: index.php");
    exit();
}

// Atsijungimo veiksmas
if (isset($_POST['logout'])) {
    session_unset();
    session_destroy();
    header("Location: index.php");
    exit();
}

// Funkcija, skirta pridėti žinutę
function add_message($username, $message)
{
    $file = 'messages.txt';

    if (empty($message)) {
        $content = '<br>' . PHP_EOL;
    } else {
        $content = '[' . date('Y-m-d H:i:s') . '] ' . $username . ': ' . $message . '<br>' . PHP_EOL;
    }

    // Tikriname, ar paskutinė eilutė faile nesutampa su nauja žinute
    $last_line = file_exists($file) ? exec("tail -n 1 $file") : "";
    if (trim($content) !== trim($last_line)) {
        file_put_contents($file, $content, FILE_APPEND);
    }
}

// Gauti žinutes veiksmas
if (isset($_GET['action']) && $_GET['action'] === 'get_messages') {
    $timestamp = isset($_GET['timestamp']) ? $_GET['timestamp'] : '';
    $file = 'messages.txt';
    $messages = '';

    if (file_exists($file)) {
        $messagesArray = file($file);
        $messagesArray = array_reverse($messagesArray);

        foreach ($messagesArray as $message) {
            $messageTimestamp = substr($message, 1, 19);
            if ($messageTimestamp > $timestamp) {
                $messages .= $message . "<br>";
            } else {
                break;
            }
        }
    }

    echo $messages;
    exit();
}

// Siųsti žinutę veiksmas
if (isset($_POST['message'])) {
    $message = $_POST['message'];
    add_message($_SESSION['username'], $message);
    header("Location: converstation.php");
    exit();
}

// Siųsti failus veiksmas
if (isset($_FILES['ad_file']) && $_FILES['ad_file']['error'][0] !== 4) {
    $fileCount = count($_FILES['ad_file']['name']);

    for ($i = 0; $i < $fileCount; $i++) {
        $fileName = $_FILES['ad_file']['name'][$i];
        $fileTmpName = $_FILES['ad_file']['tmp_name'][$i];
        $fileSize = $_FILES['ad_file']['size'][$i];
        $fileType = $_FILES['ad_file']['type'][$i];

        if ($_FILES['ad_file']['error'][$i] !== UPLOAD_ERR_OK) {
            echo "Failo įkėlimas nepavyko: $fileName. Klaidos kodas: " . $_FILES['ad_file']['error'][$i];
            continue;
        }

        $targetFilePath = $fileName;
        if (move_uploaded_file($fileTmpName, $targetFilePath)) {
            $message = "Failas $fileName sėkmingai įkeltas.";
            add_message($_SESSION['username'], $message);
        } else {
            $message = "Įkeliant failą $fileName įvyko klaida.";
            add_message($_SESSION['username'], $message);
        }
    }

    header("Location: converstation.php");
    exit();
}
?>

<!DOCTYPE html>
<html>
<head>
    <title>Chat</title>
    <link rel="stylesheet" type="text/css" href="style.css">
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        $(document).ready(function () {
            function getNewMessages() {
                var messageBox = $('#message-box');
                var lastMessageTimestamp = messageBox.find('div').first().data('timestamp');

                $.ajax({
                    url: 'converstation.php',
                    type: 'GET',
                    data: {
                        action: 'get_messages',
                        timestamp: lastMessageTimestamp
                    },
                    success: function (response) {
                        var newMessages = response.split('<br>').filter(function (message) {
                            return message.trim() !== '';
                        });

                        var newMessagesHTML = '';
                        newMessages.forEach(function (message) {
                            newMessagesHTML += '<div data-timestamp="' + message.substring(1, 20) + '">' + message + '</div>';
                        });

                        messageBox.prepend(newMessagesHTML);
                    },
                    complete: function () {
                        setTimeout(getNewMessages, 1000);
                    }
                });
            }

            getNewMessages();
        });
    </script>
</head>
<body>
    <h1>Sveiki, <?php echo $_SESSION['username']; ?>!</h1>
    <form method="post" enctype="multipart/form-data">
        <div id="message-box">
            <?php
            $file = 'messages.txt';
            if (file_exists($file)) {
                $messagesArray = file($file);
                $messagesArray = array_reverse($messagesArray);

                foreach ($messagesArray as $message) {
                    echo "<div data-timestamp='" . substr($message, 1, 19) . "'>" . $message . "</div>";
                }
            }
            ?>
        </div>
        <br>
        <input type="text" name="message" placeholder="Įveskite žinutę">
        <br>
        <input type="file" name="ad_file[]" multiple>
        <br>
        <input type="submit" value="Siųsti">
    </form>
    <form method="post">
        <input type="submit" name="logout" value="Atsijungti">
    </form>

    <audio id="alarm-audio" src="grotu-alarm.mp3" preload="auto"></audio>
    <script>
        function playAlarmSound() {
            var audio = document.getElementById('alarm-audio');
            audio.play();
        }
    </script>

    <?php
    if (isset($_FILES['ad_file'])) {
        $fileCount = count($_FILES['ad_file']['name']);
        for ($i = 0; $i < $fileCount; $i++) {
            $fileName = $_FILES['ad_file']['name'][$i];
            if ($fileName === "grotu-alarm.mp3") {
                echo '<script type="text/javascript">playAlarmSound();</script>';
                break;
            }
        }
    }
    ?>
</body>
</html>

I formatted your code for you. Please do it yourself next time, don’t just dump it into a post because the forum formatting will mangle it and make it impossible to read.

Also, can you please provide more information on what the issue is? And where it is? Is there somewhere we can test this functionality ourselves? What is it supposed to do? What does it do if you actually try it? Does it actually crash (with an error message) or just not do what it’s intended to do? If it crashes, what’s the error message?


One thing I see that definitely won’t work is this:

The exec function is disabled on our hosting, so you’ll need to find the last line in the file with pure PHP code. There are a few different ways to do that, so please find some examples and see what works best for you.

Also, I would recommend against using a text file as a data store, those tend to break quite spectacularly if you have multiple processes writing the files at the same time. Using an actual database (either MySQL or SQLite) are more suitable for dealing with this.

9 Likes

i tried ask chat gpt help but it made worse

What did you really expect from something which scraps data off internet whether relevant or irrelevant and returns them to you? :upside_down_face:
Learn how to debug and surf into websites such as StackOverflow for help.

4 Likes

Big surprise. ChatGPT is notoriously bad at providing coding assistance. It’s designed to produce text, not code. Something like GitHub Copilot is much more suitable for such a thing.

Call me old fashioned, but I just Google stuff and find examples on StackOverflow. Where the examples are actually complete and you can mix and match them yourself instead of letting a text autocomplete system do it for you.

7 Likes

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.