1+ <?php
2+ /**
3+ * 此页面用来协助 IE6/7 预览图片,因为 IE 6/7 不支持 base64
4+ */
5+
6+ $ DIR = 'preview ' ;
7+ // Create target dir
8+ if (!file_exists ($ DIR )) {
9+ @mkdir ($ DIR );
10+ }
11+
12+ $ cleanupTargetDir = true ; // Remove old files
13+ $ maxFileAge = 5 * 3600 ; // Temp file age in seconds
14+
15+ if ($ cleanupTargetDir ) {
16+ if (!is_dir ($ DIR ) || !$ dir = opendir ($ DIR )) {
17+ die ('{"jsonrpc" : "2.0", "error" : {"code": 100, "message": "Failed to open temp directory."}, "id" : "id"} ' );
18+ }
19+
20+ while (($ file = readdir ($ dir )) !== false ) {
21+ $ tmpfilePath = $ DIR . DIRECTORY_SEPARATOR . $ file ;
22+
23+ // Remove temp file if it is older than the max age and is not the current file
24+ if (@filemtime ($ tmpfilePath ) < time () - $ maxFileAge ) {
25+ @unlink ($ tmpfilePath );
26+ }
27+ }
28+ closedir ($ dir );
29+ }
30+
31+ $ src = file_get_contents ('php://input ' );
32+
33+ if (preg_match ("#^data:image/(\w+);base64,(.*)$# " , $ src , $ matches )) {
34+
35+ $ previewUrl = sprintf (
36+ "%s://%s%s " ,
37+ isset ($ _SERVER ['HTTPS ' ]) && $ _SERVER ['HTTPS ' ] != 'off ' ? 'https ' : 'http ' ,
38+ $ _SERVER ['HTTP_HOST ' ],
39+ $ _SERVER ['REQUEST_URI ' ]
40+ );
41+ $ previewUrl = str_replace ("preview.php " , "" , $ previewUrl );
42+
43+
44+ $ base64 = $ matches [2 ];
45+ $ type = $ matches [1 ];
46+ if ($ type === 'jpeg ' ) {
47+ $ type = 'jpg ' ;
48+ }
49+
50+ $ filename = md5 ($ base64 ).". $ type " ;
51+ $ filePath = $ DIR .DIRECTORY_SEPARATOR .$ filename ;
52+
53+ if (file_exists ($ filePath )) {
54+ die ('{"jsonrpc" : "2.0", "result" : " ' .$ previewUrl .'preview/ ' .$ filename .'", "id" : "id"} ' );
55+ } else {
56+ $ data = base64_decode ($ base64 );
57+ file_put_contents ($ filePath , $ data );
58+ die ('{"jsonrpc" : "2.0", "result" : " ' .$ previewUrl .'preview/ ' .$ filename .'", "id" : "id"} ' );
59+ }
60+
61+ } else {
62+ die ('{"jsonrpc" : "2.0", "error" : {"code": 100, "message": "un recoginized source"}} ' );
63+ }
0 commit comments