最好只检查表单输入的名称而不是扩展名


What is the best to check a form input just for a name and not an extension

在我的表单中,有一个重命名文件的输入。 当他们选择要上传的文件时,会对其进行检查以确保它只是一个.pdf文件。我正在尝试检查输入以确保他们没有向新名称添加文件扩展名。我正在尝试检查"pdf"的任何变体这是我所拥有的,但有没有更好的方法可以做到这一点。欢迎任何帮助,谢谢

  <?php
    function get_file_extension($pdf)
    {
     return substr(strrchr($pdf,'.'),0);
    }
    $pdf = "test.pdf";
    $test = strstr($pdf, '.');
    $pdf_ext = array('.pdf','.PDF','.Pdf','.PDf','.pdF','.pDf','.PdF','.PdF');
    $test =  get_file_extension($pdf);
    if($test == in_array($test,$pdf_ext)) {
       echo 'you do not a .pdf';
    } else {
       echo 'name ok';
    }
   ?>

只需使用 strtolowerstrtoupper

if(strtolower($test) == 'pdf') {
   echo 'pdf';
} else {
   echo 'no pdf';
}

if(strtoupper($test) == 'PDF') {
   echo 'pdf';
} else {
   echo 'no pdf';
}

您可以检查他们是否输入文件扩展名为 .pdf 的名称,然后为他们删除它,而不是不允许用户输入文件扩展名的名称。

<?php
function get_filename_without_pdf($file){
    preg_match('/(.+?)('.pdf)?$/i', $file, $matches);
    return $matches[1];
}
echo get_filename_without_pdf('test1.pdf') . PHP_EOL;
echo get_filename_without_pdf('test2.PdF') . PHP_EOL;
echo get_filename_without_pdf('test3.txt') . PHP_EOL;
echo get_filename_without_pdf('test4') . PHP_EOL;

输出

test1
test2
test3.txt
test4