Limit PHP Uploaded Files to CSV

How can you limit & verify that an uploaded file is a .csv file using PHP.  Using the code for  
//This Works
if (!($uploaded_type=="image/gif")) {
echo "You may only upload .Gif files.<br>";
//This is ineffective
if (!($uploaded_type=="text/txt")) {
echo "You may only upload .CSV files.<br>";

Open in new window

Who is Participating?
idealwsConnect With a Mentor Commented:
The below code will check to make sure the file has the .csv extension only if not it will print a error. If it does then it is uploaded and moved to the directory specified in the $datadir variable. You can then proceed to do what you need after the file is uploaded.
// Directory to upload to
$datadir = "data/";
// Lets get the file name
$uploadfile = $datadir.$_FILES['userfile']['name'];
$ext = strrchr($_FILES['userfile']['name'],'.');
if($ext != ".csv") {
    echo "Only CSV files are allowed to be uploaded";
    $error = 1;
    // Ad your upload code here
    if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
        // If this file is moved (uploaded do this

Open in new window

hernst42Connect With a Mentor Commented:
Depending on the install the type might be "text/csv" and "text/comma-separated-values" But the best would be to look into the file, parse the first line and check the content
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.