mhopkins321
mhopkins321

Reputation: 3083

Have user validate file before saving to server

My script has a user upload a pdf. I have found a pdf parser that then displays the first part of the plain text. The user will then verify that the data is the correct data. If it is, then the user submits the data and it saves it to a file. For data that isn't a file, I've always passed the info using invisible form fields to an execute page. However with a file I'm not sure the best way to do it.

if ($_FILES["file"]["error"] > 0){
    echo "Error: " . $_FILES["file"]["error"] . "<br>";
}
else{
    $uploadedFile = $_FILES["file"]["tmp_name"];
    $result = pdf2text($uploadedFile);
    echo substr($result, 0, 200);
    echo "<BR>";
}

Upvotes: 0

Views: 103

Answers (2)

Kasia Gogolek
Kasia Gogolek

Reputation: 3414

Based on the POST method uploads manual

The file will be deleted from the temporary directory at the end of the request if it has not been moved away or renamed.

You will want to move your tmp_file to a cache directory inside your app, and then based on your validation being true or false remove it, or move it to a permanent directory.

if ($_FILES["file"]["error"] > 0){
    echo "Error: " . $_FILES["file"]["error"] . "<br>";
}
else{
    $uploadedFile = $_FILES["file"]["tmp_name"];
    $tmp_file     = PATH_TO_CACHE_FOLDER . time(). $_FILES["file"]["name"]
    if (move_uploaded_file($_FILES['userfile']['tmp_name'], $tmp_file)) {
        $result = pdf2text($uploadedFile);
        echo substr($result, 0, 200);
        echo "<BR>";

    }
}

and in the next script

if(isValid() === true)
{
    $tmp_file = $_POST['tmp_file_name'];
    $file_name = $_POST['file_name'];
    move_uploaded_file($tmp_file, PERMANENT_PATH . $file_name);
}

this is just mock code, but should give you a better idea.

Upvotes: 2

Tasos Bitsios
Tasos Bitsios

Reputation: 2799

Move the uploaded file with:

move_uploaded_file( $uploadedFile, "some/where/temp.pdf" );

...and create a hidden form field containing the new filename (some/where...).

Upvotes: 0

Related Questions