Frage

Currently using a form to upload files.

The form is in index.html and looks like:

<div id="submit">
    <form action="upload.php" method="post" enctype="multipart/form-data">
    Select XML file: <input type="file" name="file"><br><br>
    <input type="submit" value="Upload">
    </form>
</div><!--end submit-->

the upload.php file looks like:

<?php
move_uploaded_file ($_FILES['file'] ['tmp_name'], "uploads/{$_FILES['file'] ['name']}");
header('Location: index.html');
exit; ?>

The file uploads to the correct location however, I need a way to alert the user that the upload was successful. Can someone provide some help on this please?

War es hilfreich?

Lösung

you try this

<?php
if(move_uploaded_file ($_FILES['file'] ['tmp_name'], "uploads/{$_FILES['file'] ['name']}"))
{
echo "file uploaded";
header( "refresh:5;url=index.html" );
exit;
}
else
{
 echo "file not uploaded";
 header( "refresh:5;url=index.html" );
 exit;
 }
 ?>

in this header will redirect you to index.html in 5 seconds

Andere Tipps

The easiest (if you wish to keep the redirection) way it to change index.html into index.php, and then with your header function, add a get parameter to the URL index.php?uploaded=1. And then in the index.php page, check for the parameter like this:

if (isset($_GET['uploaded']) && $_GET['uploaded'] === 1) echo "Your upload/move was successful!";

I'd recommend looking into implementing flash messages in PHP. Basically, store the message in a session and display it to the user.

There are examples using third party code here. Or, you could also roll your own implementation. There's a really, really simple example here.

Displaying messages based on GET parameters works, but it can get messy as simply hitting a particular URL will display the message to the user.

Here are some functions I used a very long time ago for something like this (setting and printing session messages). I'd highly recommend looking into the links before using this:

function set_session_message($type, $message) {
    $_SESSION['message'] = array('type' => $type, 'message' => $message);
}

function print_session_message() {
    $output = '';

    if (!empty($_SESSION['message'])) {            
        if ($_SESSION['message']['type'] == 'success') {
            $output = '<p class="success">' . $_SESSION['message']['message'] . '</p>';
        } elseif ($_SESSION['message']['type'] == 'error') {
            $output = '<p class="error">' . $_SESSION['message']['message'] . '</p>';
        }
    } 

    unset($_SESSION['message']);

    return $output;
}

With this, what you'd do is call set_session_message() on successful upload, redirect to your index page, and then call print_session_message().

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top