我在这里发现了一些相关的帖子,但没有任何关系......我需要"正确"提供图像(humm)并尽可能少地使用资源.我正在研究一个子(下面)但是,由于我使用CGI这个事实并不太资源友好.这只是我的假设.我是一个Perl新手但是,我比它更喜欢它.
该查询将由"somescript.pl?img=image.png"生成
#!/usr/bin/perl -Tw
use strict;
use warnings;
use CGI;
#I should drop warnings after all is said and done. Also name my vars generically. Right?
#I dont know if this query method will work or is even the best method.
$query = new CGI;
my @img = $query->param;
if ( $_ eq "img" ) { my $file = $query->param($_); }
if ( $_ ne "img" ) { ## I will send to an error sub that serves up a error image
}
# Prob a one liner to take care of the above. Not within my ability though.
# Still figuring all this out here.. Very verbose sorry...
# I will strip everything but lowercase alpha and the "."
# with s =~ /[something like A-Z] I will look it up //g;
# Still.. prob all above will fit in a one liner by a PERL guru!
# Below is related to -Taint, I was told this is important to use the -T.
$ENV{PATH} = "bin:/usr/bin";
delete( $ENV{qw(IFS CDPATH BASH_ENV ENV)} );
# now I will grab the images extension.
my $ext = ( $file =~ m/[^.]+$/ )[0];
#I was informed to use the "three" but, I am unsure what that means.
# My attempt based on my reading many posts here.
my $length = ( stat($file) )[10];
my $image = do {
local $/ = undef;
print "Content-type: image/$ext\n";
print "Content-length: $length \n\n";
binmode STDOUT;
open( FH, "<", $file ) || die "Could not find $file: $!";
my $buffer = "";
while ( read( FH, $buffer, 10240 ) ) {
print $buffer;
}
close(FH);
};
Run Code Online (Sandbox Code Playgroud)
正如你所看到的,我在这里的尝试显然是初学者.
我在堆栈溢出中找到了很好的建议.我感谢过去和现在的所有人.
.jpeg
而不是.jpg
!File::MMagic
或者File::MimeInfo
会做出更好的通用解决方案.(stat $file)[10]
不是内容长度,它是ctime
,对你来说毫无价值.(stat $file)[7]
虽然-s $file
工作正常,但对任何Perl程序员来说都很明显,无需参考stat
手册.(2a:-s
在打开文件句柄而不是文件名时使用文件句柄,以避免因文件替换而竞争.)image.pl?image=../../../../../../../etc/passwd
.我建议特别提到images目录,这样你就不依赖于getcwd
,并使用和构建一个只能在images目录中的路径名.File::Spec
->no_upwards
File::Spec->catfile
die
如果它是可以避免的,它对CGI来说并不是一个好形式.如果找不到该文件,则返回404
状态.如果请求是非法的,则返回a 400
或403
status等.path_info
允许image.pl/foo.png
而不是,那么您的网址会更好image.pl?img=foo.png
.看看 Apachegallery 中的实现方式
http://metacpan.org/pod/Apache::画廊
它使用 Imlib2 并且非常高效,包括动态调整大小和旋转以及使用共享磁盘缓存等高级功能。