Rejecting a HTTP request before reading the body

2019-07-22 13:39发布

I'm working on a website where users will need to upload some very large files. The site is written in PHP.

There are some instances where I'll want to reject a file based off the headers. Ideally, I'd like to reject the request as soon as the headers are received without ever reading the body. There's no reason to read a 200M file if the header is enough to tell that the file should be rejected. Additionally, when I do accept a request, I'd like to periodically save the number of bytes read as the request body is received.

I know this is impossible with PHP because the entire HTTP request is read before PHP gets its hands on it. What are my alternatives? I've never worked with Perl, but I was reading that mod_perl gives access to the Apache API. Would it be possible to do this using mod_perl? An Apache module?

3条回答
可以哭但决不认输i
2楼-- · 2019-07-22 13:55

If you can hard-code rules for rejecting a file, you could use a mod_rewrite rule in .htaccess. Use the %{HTTP:header} condition:

RewriteCond %{HTTP:AcceptThisFile} False [NC]
RewriteRule (...)
查看更多
淡お忘
3楼-- · 2019-07-22 13:57

There is modsecurity that can be used with "simple" regex. That goes in Apache2 and is executed before the whole file is received. You can start by reading the docs a bit:

http://www.modsecurity.org/documentation/modsecurity-apache/2.5.5/modsecurity2-apache-reference.html

You may keep the default rules too since they will also forbid many useless accesses, although it takes time to remove those rules that actually prevent your own website to work right with many, so removing all of those default rules could be a good idea.

查看更多
爱情/是我丢掉的垃圾
4楼-- · 2019-07-22 14:12

Largely impossible using the standard PHP handlers. You don't get the request till its been parsed and there is unfortunately no good way to defer that.

EDIT: I've had good experience using the commons fileupload library's streaming mode and java. A bit messy to merge into an Apache config, but well worth the bandwidth savings if you are talking 200M files.

查看更多
登录 后发表回答