Question

With PHP 5 I would like to upload an XML file via a web form and parse it using SimpleXML.

I've tried few SimpleXML examples and they work fine at my CentOS 6 Linux server.

However, I don't have any experience with handling uploaded files in PHP yet.

Should I use the $_FILES and do I always have to use a temporary file or can it be done completely in memory?

From PHP Cookbook I've copied this example:

<html>
<body>

<?php if ($_SERVER['REQUEST_METHOD'] == 'GET') { ?>

        <form method="post" action="<?php echo $_SERVER['SCRIPT_NAME'] ?>"
        enctype="multipart/form-data">
        <input type="file" name="doc"/>
        <input type="submit" value="Send File"/>
        </form>

<?php } else {
                if (isset($_FILES['doc']) &&
                    ($_FILES['doc']['error'] == UPLOAD_ERR_OK)) {
                        $oldPath = $_FILES['doc']['tmp_name'];
                        $newPath = '/tmp/' . basename($_FILES['doc']['name']);

                        if (move_uploaded_file($oldPath, $newPath)) {
                                print "File moved from $oldPath to $newPath";
                        } else {
                                print "Couldn't move $oldPath to $newPath";
                        }
                } else {
                        print "No valid file uploaded.";
                }
        }
?>

</body>
</html>

It works fine and for the print_r statement added by me the following output is printed:

Array
(
    [document] => Array
        (
            [name] => my_file.xml
            [type] => text/xml
            [tmp_name] => /tmp/phpRD9cYI
            [error] => 0
            [size] => 1610252
        )

)

And I can see the /tmp/my_file.xml file.

My question is though if I can skip the creation of temporary files?

I don't like them because:

  1. They are sometimes security issue
  2. They have to be cleaned up (by a cronjob?)
  3. Their names might collide (probably seldom case unless it's 1)

UPDATE: Also, I don't understand, why can't I read the file at $oldPath? It is not found there and I have to call the move_uploaded_file() and then read the $newPath...

Était-ce utile?

La solution

You don't need to save/move the file in a new folder,

if (isset($_FILES['doc']) && ($_FILES['doc']['error'] == UPLOAD_ERR_OK)) {
    $xml = simplexml_load_file($_FILES['doc']['tmp_name']);                        
}

The tempfile generated will be automatically removed when the PHP script finishes. Hope this helps.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top