dutu000
dutu000

Reputation: 15

Why would PHP not always upload a file

On a PHP page, I call an upload function that contains the standard PHP upload procedure. After I call the function, I do a redirect (tried with either window. location or header ()).

The strange thing is that everything works fine a couple of times, then it would not upload anymore (uploadOK won't be 0 either). It would just not move the file onto the server.

Then, I would take out the redirect and the upload would start working again. I put the redirect back in, the upload will still work a couple of times then stop again... Do you have any idea why?

Another strange thing is that, even when it doesn't work, the upload function still returns the correct path+filename, but it would not echo "File ... was uploaded".

I suspect that the problem might be in the move_uploaded_file() function... but it would not return 0, because "Error..." would not be echoed.

Without calling the redirect after the upload, it uploads fine every time.

PHP page:

$_SESSION["temp_file_name"]="../".UploadFisier($_FILES["fileToUpload"], $_SESSION["ID_CLASA"]."_".$id_item."_temp_".UserIdLogat($dbocr)."_", "../teme/", "");     
header("Location: trimite_tema_script.php");

The Upload function:

function UploadFisier($file, $suffix, $target_dir, $maxsize)
{
    if ($maxsize=="") { $maxsize=3000000; }
    if ($target_dir=="") { $target_dir="../upload/"; }

    $target_empty_file=$target_dir.$suffix;
    $target_file = $target_empty_file.basename($file["name"]);

    $uploadOk = 1;

    if ($target_file != $target_empty_file)
    {
        if ($file["size"] > $maxsize)
        {
            echo "file too large";
            $uploadOk = 0;
        }
    }
    else
    {
       echo "no file selected.";
       $uploadOk = 0;
    }

    if ($uploadOk == 1)
    {
        //we overwrite
        if (file_exists($target_file))
        {
            unlink($target_file);
        }

        if (move_uploaded_file($file["tmp_name"], $target_file))
        {
            echo "File ". basename( $file["name"]). " was uploaded.";
            //we output the path and filename without the "../" at the beginning
            $linksave=substr($target_file, 3);
        }
        else
        {
            echo "Error....";
        }
    }

    echo "uploadOk ".$uploadOk;
    return $linksave;
}

Upvotes: -1

Views: 39

Answers (2)

Bademeister
Bademeister

Reputation: 866

Wrap a try/catch in your code. maybe you will find out more about the error.

function UploadFisier($file, $suffix, $target_dir, $maxsize)
{
    try {
       // your code
    } catch (\Exception $e) {
         echo $e->getMessage();
         die();
    }
}

Upvotes: 0

Noha Shehab
Noha Shehab

Reputation: 413

Check the file_uploads value in PHP.ini and confirm that is something like this

file_uploads = On

Upvotes: 0

Related Questions