If no attachment, then send message, otherwise, portray download button

Tags: , ,



I am trying to implement a feature which goes something like this:

  1. If textarea has content (not empty) and no attachment is added, then just display the message in the div.
  2. If textarea is empty, but an attachment is added, then display download button, which will force the message receiver to save the attachment to local disk.
  3. If textarea is not empty, and attachment is added, then display both the message and the download button.

My current situation:

Currently, I have the following code snippet for processing the attachment (which at the moment, can only be an image). Ideally, I do not want to store anything on the server:

Firstly, here are is a visual representation of my messages page and how I display my messages:

messages.php:

enter image description here

Here is my code:

<?php
/**************************************************/

// 1. My textarea form for sending a message:
echo "  <form action='messages.php?u=$user' method='post' enctype='multipart/form-data'>
            <textarea name='msg_body' rows='3' maxlength='255' cols='110' placeholder='Send message...'></textarea>
            <input type='submit' name='send' value='Send'/>
            <input id='file-input' name='attachment' type='file'/>
        </form>";
        
/*
When the above form is filled, the following states are considered valid:
   1.1. If the textarea is not empty and no attachment is added.
   1.2. If the textarea is empty but an attachment is added.
   1.3. If both textarea and attachment are empty, then DO NOT execute the INSERT query.
*/  
/**************************************************/

// 2. My approach to achieve the above and more...
if ($user != $username) {
    if (isset($_POST['send'])) {
        $msg_body = (trim(strip_tags(@$_POST['msg_body'])));
        $date_of_msg = date("Y-m-d");
        $read = "no";
        $deleted = "no";

        // check if file is added and message is placed
        if (($_FILES['attachment']['size']) == 0 && ($_FILES['attachment']['error'] == 0) && $msg_body != "") {
            // do nothing
        } else {
            if (isset($_FILES['attachment'])) {
                // check format of file
                if (((@$_FILES["attachment"]["type"] == "image/jpg") 
                        || (@$_FILES["attachment"]["type"] == "image/jpeg") 
                        || (@$_FILES["attachment"]["type"] == "image/png") 
                        || (@$_FILES["attachment"]["type"] == "image/gif")) 
                        && (@$_FILES["attachment"]["size"] < 3145728)) //3mb 
                {
                    if (file_exists("user_data/attached_files/".@$_FILES["attachment"]["name"])) {
                        // do nothing
                    } else {
                        // move temporary image files into one of the randomly generated files
                        move_uploaded_file(@$_FILES["attachment"]["tmp_name"], "user_data/attached_files/".@$_FILES["attachment"]
                            ["name"]);
                        // get name         
                        $attach_name = @$_FILES["attachment"]["name"];
                    }
                }
            }
            $send_msg = mysqli_query($connect, "INSERT INTO private_messages VALUES ('','$username','$user', '$msg_body',
                '$date_of_msg', '$read', '$deleted')
            ");
        } // 396 
        echo "<meta http-equiv='refresh' content='0'>";     
    }
}
/**************************************************/

// 3. Now to display the download button (ONLY IF AN ATTACHMENT IS ADDED):

        if ($msg_to == $user){
            echo "  <div class='parent'> 
                        <div class='msg_prof'>
                        <img class='img-rounded' src='/user_data/profile_pics/$my_pro_pic'/>
                    </div>
                    <div class='new_msg_from_user'>
                         <p><b style= 'color: red;'> You said:</b> $msg_body</p>
                         <span class='faded'>$date </span>";
                
                // check if file is empty
                if (isset ($_FILES['attachment']['size']) == 0 && (isset($_FILES['attachment']['error'])) == 0){
                    // no file attached, so do nothing
                } else {
                echo "  <form action='inc/download_attachment.php' method='post' enctype='multipart/form-data'>
                            <button type='submit' name='save'> Download</button>
                        </form>";
                }
                echo "  <a href='inc/remove_message.php?id=$message_id'> Remove </a> 
                    </div><hr/>
                    </div>";
                }

?>

My current results:

So the image below depicts my current results. The last post which is empty (You said: "") was a post with no text in the textarea, but it has an attachment added.

enter image description here

When an attachment is added, I need the download button to appear like so: enter image description here The download button, once pressed, will call download_attachment.php which will force the user to save the image to local disk.

Summary:

  • How do I only show the download button when an attachment is added?
  • How do I prevent empty messages from being sent? (i.e. no message and no attachment).

P.s. Sorry for the very long question :).

Answer

Answering your question in order:

How do I only show the download button when an attachment is added?

The challenge is, PHP get executed and generate the page once by server side. So your logic will only work when page is refreshed (re-generated). But the problem is that what you trying to achieve is happening on Client side (By clicking Browne... button) Therefore we need to use JavaScript to solve this part.

So we can by default make our button hidden, but display it the moment we interact with Browne... button.

One way to go, by adding following JavaScript at the end of your code

<script>
    document.getElementById("btnDownload").style.visibility = "hidden";
    document.getElementById("file-input").onchange = function () {
        document.getElementById("btnDownload").style.visibility = "visible";
    };
</script>

This will only work if you bring the download button out side of the if statement and give it an id like id='btnDownload'. It is also overkill putting it inside PHP, so just leave it as HTML, but if you want to leave it inside PHP, than remember as said to take it out of the any condition/statement since we need to control its appearance from Client side.

<form action='inc/download_attachment.php' method='post' enctype='multipart/form-data'>
    <button type='submit' name='save' id='btnDownload'> Download</button>
</form>

This is one way to solve it, the other way is, when the image get uploaded, you need to added a field in your database table to tell where the file/attachment location is, and if that field has file/attachment location, than you can dynamically create a download button by adding following condition.

if (!empty($attachment))
{
    // your button generation code.
}

I have tried both methods on my test environment with your code and both works.

How do I prevent empty messages from being sent? (i.e. no message and no attachment).

You can go two ways, you can added extra condition !empty($_POST['msg_body']) to check if field is not empty, so your code will look like this:

if ($user != $username)
{
    if (isset($_POST['send']) && !empty($_POST['msg_body'])){
        code inside etc.....
}

You can also do it by JavaScript following this example.

Example of What I did: enter image description here

Note: As you can see the image button appears when image available for one messages, I did it both with PHP/MySQL database Or JavaScript and both solutions works, but since I have no in depth knowledge about your final goal, therefore my solution to your question is working and conceptually correct, but you might need to work a bit more and brush it up to fit it in to your final goal.



Source: stackoverflow