0

I wrote a PHP script to upload a .txt file and it works partially:

<?php
    $allowedExts = array("txt");
    $temp = explode(".", $_FILES["file"]["name"]);
    $extension = end($temp);
    $dest = "/etc/squid/squid.conf";
    if ((($_FILES["file"]["type"] == "text/plain")
    && ($_FILES["file"]["size"] < 170000)
    && in_array($extension, $allowedExts)))
    {
        if ($_FILES["file"]["error"] > 0)
        {
            echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
        }
        else
        {
            echo "<div style='text-align: center'>";
            echo "Upload File Success!!<br><br>";
            echo "FIle : " . $_FILES["file"]["name"] . "<br>";
            echo "Type : " . $_FILES["file"]["type"] . "<br>";
            echo "Size : " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
            
            echo "</div>";

            move_uploaded_file($_FILES["file"]["tmp_name"],
            "/var/www/squid_proxy/upload/" . $_FILES["file"]["name"]);
            copy("/var/www/squid_proxy/upload/" . $_FILES["file"]["name"],
                $dest);
        }
    }
    else
    {
        echo "<div style='text-align: center'>";
        echo "Error, File upload only .txt";
        echo "</div>";
    }
?>

Both file type and MIME validation work well, but I want a validation of the file's content. The file is stuctured with headers. See this example:

#ADVANCED

#WIZARD

Before the file upload to server, it must be checked that the file contains #ADVANCED in the first line and #WIZARD in the third line. If the headers are missing or the file is empty, an error message should be shown.

How can I validate the content of the uploaded file?

2 Answers 2

2

Here $line[0] is Line 1 and $line[2] is line 3. file() reads entire file into an array.

$lines = file($myFile); //file lines into an array

if (strip($lines[0]) == '#ADVANCED' && strip($lines[2]) == '#WIZARD'){
//success
}

EDIT (as suggested by @barmar)

Added strip() to the variable $lines[0] and $lines[2] to trim the /n char.

Sign up to request clarification or add additional context in comments.

3 Comments

You need the flag FILE_IGNORE_NEW_LINES, or call strip($lines[0]) and strip($lines[2]).
@Barmar Is this necessary? If yes, then why?
By default, each string will end with newline, e.g. "#ADVANCED\n". This won't be equal to the string without newline.
0

Use file function. It will return array of lines of you txt-file.

$lines = file($filename);
// Then you can check if 
if ($lines[0] == '#ADVANCED' && $lines[2] == '#WIZARD') {
    // do some stuff
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.