C# 如何过滤上传或发布到php Web服务器的文件的扩展名?
我用c编写了一个post函数,将一个文件发送到web服务器php,上传的每个文件都没有经过扩展名过滤,我担心如果有坏人将恶意文件(如Webshell或其他恶意软件)上传到我的web服务器中。 我只想要一个可以通过post功能上传的扩展名.licC# 如何过滤上传或发布到php Web服务器的文件的扩展名?,c#,php,C#,Php,我用c编写了一个post函数,将一个文件发送到web服务器php,上传的每个文件都没有经过扩展名过滤,我担心如果有坏人将恶意文件(如Webshell或其他恶意软件)上传到我的web服务器中。 我只想要一个可以通过post功能上传的扩展名.lic (php) <?php $uploads_dir = './newfolder'; if ($_FILES["file"]["error"] == UPLOAD_ERR_OK) { $tmp_name = $_FILES["file"]["tmp_
(php)
<?php
$uploads_dir = './newfolder';
if ($_FILES["file"]["error"] == UPLOAD_ERR_OK) {
$tmp_name = $_FILES["file"]["tmp_name"];
$name = $_FILES["file"]["name"];
move_uploaded_file($tmp_name, "$uploads_dir/$name");
}
?>
c#
public void upLoad()
{
try
{
WebClient client = new WebClient();
string myFile = this.temPfold + "License.lic";
client.Credentials = CredentialCache.DefaultCredentials;
client.UploadFile(this.myurl, "POST", myFile);
client.Dispose();
}
catch (Exception)
{
Application.Exit();
}
}
正如在一篇评论中指出的那样——仅仅因为文件声称具有特定的扩展名并不意味着它一定是该类型的。但是,可以通过执行以下处理来实现一些过滤。测试扩展名预期的mimetype、大小,如果每个.lic文件都有类似的头,则可以测试实际文件本身的一部分-尽管可能也会使用文件sha1或md5校验和
<?php
try{
if( !empty( $_FILES['file'] ) ){
$LIC_MIME_TYPE='text/plain'; # what is the correct mimetype?
$LIC_MAX_FILE_SIZE=1024; # how large???
$dir = './newfolder/';
$obj=(object)$_FILES['file'];
$name=$obj->name;
$tmp=$obj->tmp_name;
$err=$obj->error;
$size=$obj->size;
$mime=mime_content_type( $tmp );
if( !empty( $err ) )throw new Exception('An error occurred', $err );
if( !$mime==$LIC_MIME_TYPE )throw new Exception( sprintf( 'Invalid mimetype %s',$mime),400 );
$ext = strtolower( pathinfo( $name, PATHINFO_EXTENSION ) );
if( $ext!=='lic' ) throw new Exception('Invalid file extension',400 );
if( !is_uploaded_file( $tmp ) ) throw new Exception( 'Possible File upload attack', 400 );
if( $size > $LIC_MAX_FILE_SIZE ) throw new Exception( 'File too large', 400 );
$status = move_uploaded_file( $tmp, $dir . $name );
if( !$status )throw new Exception('Failed to Save file',400 );
}
}catch( Exception $e ){
exit( sprintf( '%s [%d]', $e->getMessage(),$e->getCode() ) );
}
?>
我想这并不能真正解决您的安全问题。例如,文件扩展名为.jpg并不意味着它实际上包含一个图像$ext=strrchr'somefile.php',';返回'.php',因此在您的示例中,ifstrrchr$_FILES[file][name],'.=='.lic'//处理文件这将返回最后一个扩展名,但正如前面提到的,只是因为文件显示了它;这并不意味着它是。你可以使用函数mime\u content\u type来检查上传文件的mime类型。POST请求中有关文件扩展名和mime类型的信息可能是伪造的,所以不要信任它们。mime_content_type$file返回上载文件的实际mime类型。