AdamGold
AdamGold

Reputation: 5051

PHP Upload Progress Session

I am trying to create an upload progress bar with PHP. I saw the new feature of PHP 5.4: upload progress session.

This is my HTML code:

<form id="upload" action="ajax/progress.php" method="POST" enctype="multipart/form-data">
    <input type="hidden" name="<?php echo ini_get("session.upload_progress.name"); ?>" value="dupload" />
    <input id="file1" type="file" name="file1" />
    <input class="btn primary" type="submit" value="Upload" />
</form>

And this is progress.php:

<?php
session_start();

$key = ini_get("session.upload_progress.prefix") . 'dupload';

if (!empty($_SESSION[$key])){
    $current = $_SESSION[$key]["bytes_processed"];
    $total = $_SESSION[$key]["content_length"];
    echo $current < $total ? ceil($current / $total * 100) : 100;
}
else {
    var_dump($_SESSION);
    var_dump($_FILES);
}

AJAX:

$('#upload').submit(function () {
    interval_id = setInterval(function () {
        $.ajax({
            url: "ajax/progress.php6",
            type: "POST",
            success: function (data) {
                console.log(data);
            }
        });
    }, 200);
    return false;
});

All the ini settings are right. (session is enabled, name and prefix is right)

I am always getting an empty session array. What's wrong?

Thanks!

Upvotes: 3

Views: 2317

Answers (3)

ATilara
ATilara

Reputation: 531

I think it's because your form is not getting submitted, as you have return false in

$('#upload').submit(function () {
    interval_id = setInterval(function () {
        $.ajax({
            url: "ajax/progress.php6",
            type: "POST",
            success: function (data) {
                console.log(data);
            }
        });
    }, 200);
    return false;
});

and it initializes interval, so the page always return null as nothing is being uploaded. Try using http://www.malsup.com/jquery/form, it submits form

Upvotes: 0

AdamGold
AdamGold

Reputation: 5051

Wasn't able to sort it out so I used XMLHTTPREQUEST "progress" action and that worked well. Thanks!

Upvotes: 1

It's not possible in one POST request, you can do AJAX requests, and read session while file is uploading. After file is uploaded, the session.upload_progress.name key is removed so you are getting an empty array.

Upvotes: 0

Related Questions