正式接触phpcms模块开发后.开发了几个功能模块.其中遇到了需要批量上传图片的问题.于是开始挖掘phpcms里面的swfupload的用法.
在phpcms里面自带的内容类型里面能够直接指定图片组.不过这样的图片组功能并不是我想用的.我需要上传一整个静态的html文件.需要
能够找到一个方法上传整个文件夹.并且能够保留原来的文件名称.
目的总结如下:
1,不改变系统的文件和目录结构.
2,实现多附件上传功能.
3,能够得到上传后的文件夹名称.
在phpcms中自带了附件上传的功能.我想去用swfupload功能,而这个功能被phpcms的附件上传功能集成进去了.那我要做的就是抽出来并加以修改.
第一步,我来研究研究这个是怎么调用的.
首先,打开firefox浏览器的firebug 打开网络面板.找到phpcm中swfupload呗调出的那个按钮.看看系统是请求的什么连接.
?m=attachment&c=attachments&a=swfupload&args=10,,1&module=&catid=&authkey=b756a93dea2e627293e88fa9d62af709&pc_hash=iXFbo1
我们捕捉到一串这样的请求.调用了attachment模块的attachements控制器里面的swfupload方法.
我们去找到这个模块中的这个控制器里面的这个方法.
在phpcms/modoules/attachemet/attachemts.php里面
打开看看,代码如下
public function swfupload(){
$grouplist = getcache('grouplist','member');
if(isset($_POST['dosubmit'])){
//if里面的内容我们暂时不看.因为这是上传之后的处理.我们要先找到是如何引入swfupload的.
} else {
if($this->isadmin==0 && !$grouplist[$this->groupid]['allowattachment']) showmessage(L('att_no_permission'));
$args = $_GET['args'];//得到参数
$authkey = $_GET['authkey'];//得到密匙
if(upload_key($args) != $authkey) showmessage(L('attachment_parameter_error'));//验证密匙
extract(getswfinit($_GET['args']));//拆分参数
$siteid = $this->get_siteid();//得到网站id
$site_setting = get_site_setting($siteid);//得到网站设置
$file_size_limit = sizecount($site_setting['upload_maxsize']*1024);//允许上传大小
$att_not_used = param::get_cookie('att_json');//得到未处理的文件列表
if(empty($att_not_used) || !isset($att_not_used)) $tab_status = ' class="on"';//如果有未处理的设置标签样式为on
if(!empty($att_not_used)) $div_status = ' hidden';//否则隐藏标签
$att = $this->att_not_used();//获取临时未处理文件列表
include $this->admin_tpl('swfupload');//这个地方才是关键.加载了这个模板.
}
}
前面的我们就先不管了 ,那是处理上传的东西.我从else开始看.首先验证了是否允许附件上传
然后从$_GET里面得到swfupload的参数args,然后去验证了密匙,密匙通过了去解析args.得到网站的id,得到网站的设置,得到允许上传附件的大小.从cookie里面得到未使用的附件列表.
设置模板里面的各种显示.最后也是最关键的.它使用了swfupload模板.也就是说我要找到这个模板.看看swfupload是怎么引过来的.
模板在这里:phpcms/modules/attachment/templates/swfupload.tpl.php
打开模板文件.模板文件上面引入了一堆文件:
admin_tpl('header', 'attachment');?>
首先是引入了头文件.我大概看里一下.里面有jquery什么的.是必要文件.所以一会我们要用的时候也要引入这个头.
之后是swfupload的样式文件和必要的JS.这里调用了一个系统函数initupload,这个函数到底是干嘛的.
千万别小觑这行.整个swfupload的配置都在这里了.
我们去找找看这个函数.
在phpcms/modules/attachment/functions/golable.func.php里面找到了它的踪迹.代码如下,这个函数的主要作用就是配置swfupload这个插件.
/* flash上传初始化
* 初始化swfupload上传中需要的参数
* @param $module 模块名称
* @param $catid 栏目id
* @param $args 传递参数
* @param $userid 用户id
* @param $groupid 用户组id
* @param $isadmin 是否为管理员模式
*/
function initupload($module, $catid,$args, $userid, $groupid = '8', $isadmin = '0'){
$grouplist = getcache('grouplist','member');
if($isadmin==0 && !$grouplist[$groupid]['allowattachment']) return false;
extract(getswfinit($args));
$siteid = param::get_cookie('siteid');
$site_setting = get_site_setting($siteid);
$file_size_limit = $site_setting['upload_maxsize'];
$sess_id = SYS_TIME;
$swf_auth_key = md5(pc_base::load_config('system','auth_key').$sess_id);
$init = 'var swfu = \'\';
$(document).ready(function(){
swfu = new SWFUpload({
flash_url:"'.JS_PATH.'swfupload/swfupload.swf?"+Math.random(),
upload_url:"'.APP_PATH.'index.php?m=attachment&c=attachments&a=swfupload&dosubmit=1",
file_post_name : "Filedata",
post_params:{"SWFUPLOADSESSID":"'.$sess_id.'","module":"'.$module.'","catid":"'.$_GET['catid'].'","userid":"'.$userid.'","siteid":"'.$siteid.'","dosubmit":"1","thumb_width":"'.$thumb_width.'","thumb_height":"'.$thumb_height.'","watermark_enable":"'.$watermark_enable.'","filetype_post":"'.$file_types_post.'","swf_auth_key":"'.$swf_auth_key.'","isadmin":"'.$isadmin.'","groupid":"'.$groupid.'"},
file_size_limit:"'.$file_size_limit.'",
file_types:"'.$file_types.'",
file_types_description:"All Files",
file_upload_limit:"'.$file_upload_limit.'",
custom_settings : {progressTarget : "fsUploadProgress",cancelButtonId : "btnCancel"},
button_image_url: "",
button_width: 75,
button_height: 28,
button_placeholder_id: "buttonPlaceHolder",
button_text_style: "",
button_text_top_padding: 3,
button_text_left_padding: 12,
button_window_mode: SWFUpload.WINDOW_MODE.TRANSPARENT,
button_cursor: SWFUpload.CURSOR.HAND,
file_dialog_start_handler : fileDialogStart,
file_queued_handler : fileQueued,
file_queue_error_handler:fileQueueError,
file_dialog_complete_handler:fileDialogComplete,
upload_progress_handler:uploadProgress,
upload_error_handler:uploadError,
upload_success_handler:uploadSuccess,
upload_complete_handler:uploadComplete
});
})';
return $init;
}
回到正题.我们来看模板swfupload.tpl.php
这个模板使用了一个js来控制
那个id是tab_swf_1
这个是一个div 代码如下.
在这里我们看到有一个span id是buttonPlaceHolder 而在配置文件中有这么一行button_placeholder_id: "buttonPlaceHolder",很明显.当页面被加载的时候 id为buttonPlaceHolder的元素会被JS替换成swfupload的上传控件.
之后一步我们要在点选完文件之后触发swf的上传方法
会在代码中找到如下代码.这里面调用了swfu.startUpload()方法.这个方法定义的地方在swfupload.js里面.我们无需理会.
至此.我们已经找到了swfupload的上传控件使用方法
怎么在我的程序里面调用这个东东呢
首先一点 我们需要在这个控件出现的模板里面引入这些必要的文件
代码如上所示.
然后在我们的模板里面想要放置swfupload的地方写上这样的标签
复制代码 代码如下:
upload_url:"'.APP_PATH.'index.php?m=attachment&c=attachments&a=swfupload&dosubmit=1",
这个很明显就透露出了我们把文件上传到了attachment模块中attachments控制器里面的swfupload方法去处理了
这个地方也就是我之前没有关注的if里面的东西.
拿出来看看
if( $_POST['swf_auth_key'] != md5(pc_base::load_config('system','auth_key').$_POST['SWFUPLOADSESSID']) || ($_POST['isadmin']==0 && !$grouplist[$_POST['groupid']]['allowattachment'])) exit();
pc_base::load_sys_class('attachment','',0);
$attachment = new attachment($_POST['module'],$_POST['catid'],$_POST['siteid']);
$attachment->set_userid($_POST['userid']);
$aids = $attachment->upload('Filedata',$_POST['filetype_post'],'','',array($_POST['thumb_width'],$_POST['thumb_height']),$_POST['watermark_enable']);
if($aids[0]) {
$filename= (strtolower(CHARSET) != 'utf-8') ? iconv('gbk', 'utf-8', $attachment->uploadedfiles[0]['filename']) : $attachment->uploadedfiles[0]['filename'];
if($attachment->uploadedfiles[0]['isimage']) {
echo $aids[0].','.$this->upload_url.$attachment->uploadedfiles[0]['filepath'].','.$attachment->uploadedfiles[0]['isimage'].','.$filename;
} else {
$fileext = $attachment->uploadedfiles[0]['fileext'];
if($fileext == 'zip' || $fileext == 'rar') $fileext = 'rar';
elseif($fileext == 'doc' || $fileext == 'docx') $fileext = 'doc';
elseif($fileext == 'xls' || $fileext == 'xlsx') $fileext = 'xls';
elseif($fileext == 'ppt' || $fileext == 'pptx') $fileext = 'ppt';
elseif ($fileext == 'flv' || $fileext == 'swf' || $fileext == 'rm' || $fileext == 'rmvb') $fileext = 'flv';
else $fileext = 'do';
echo $aids[0].','.$this->upload_url.$attachment->uploadedfiles[0]['filepath'].','.$fileext.','.$filename;
}
exit;
} else {
echo '0,'.$attachment->error();
exit;
这个里面有几行是比较重要的.
首先它载入了系统的attachment类.并且用到了里面的方法.
程序对上传成功做了echo操作.返回的东西是 返回了编号,上传后的地址,拓展名,文件名.
这些东西是给谁用的啊 我们还得回去看配置文件.
配置文件里面有一段是上传过程中各个事件将触发的方法. 有开始上传的.有上传成功的,有上传失败的.等等.
我们可以看见有一个方法是file_dialog_complete_handler:fileDialogComplete,
其实这些已经升级到swfupload的范畴了.有兴趣可以去研究研究
然后我们在phpcms/static/swfupload/handler.js里面找到这个方法.
看见上传成功后echo出来的数据被解析了.
解析的方法如下
function att_show(serverData,file)
{
var serverData = serverData.replace(/
var data = serverData.split(',');
var id = data[0];
var src = data[1];
var ext = data[2];
var filename = data[3];
if(id == 0) {
alert(src)
return false;
}
if(ext == 1) {
var img = '

} else {
var img = '

}
$.get('index.php?m=attachment&c=attachments&a=swfupload_json&aid='+id+'&src='+src+'&filename='+filename);
$('#fsUploadProgress').append('
$('#attachment_'+id).html(img);
$('#att-status').append('|'+src);
$('#att-name').append('|'+filename);
}
这个方法的目的是在id为fsuuploadprogress的元素里面添加我们上传成功的附件.但是我们还木有找到文件到底去哪里了
关键的地方来了.我们在swfupload方法里面不是有个attachment的系统类的实例么
真正上传附件是在这里实现的.我们调用了attachment里面的upload方法来实现了文件的上传.
这个attachment文件里面的upload方法在系统类里面 也就是phpcms/libs/classes/attachment.class.php里面
在这个类里面我们可以找到upload方法里面有这样一行
$this->savepath = $this->upload_root.$this->upload_dir.date('Y/md/');
这个自然就是指定了上传到的目录.文件名是通过getname方法来获取的.
到这里我们就理清思路了.
系统是这么运行的
首先在模板里面引用swfupload(配置文件是用函数生成的)->上传文件->attachment模块里的swfupload方法处理(使用系统的attachment类里面的upload方法循环上传附件.并返回结果给swfupload方法)->处理结果通过swfupload的方法(fileDialogComplete)返回给页面.
在上面我们已经实现了在模板里面引入swfupload.但是我们使用的配置文件和上传附件的方法等都是系统原来自带的.并不能实现我想要的目录结构和文件命名方法.怎么办..
改.
怎么改,首先们要把配置文件改掉. 在自己的模块里面的functions文件夹里面建立自己的函数.我们用自己的函数名称 文件命名为global.func.php这样系统会通过auto_load把我们的函数加载
进去我们把系统中attachment模块functions文件夹下面的global.func.php里面的initupload函数全盘拷贝进来.只修改其中的一行
upload_url:"'.APP_PATH.'index.php?m=你的模块名称&c=你的控制器名称&a=你的方法名称&dosubmit=1",
这样文件就会提交到我们的控制器下面.并且调用我们自己写的方法
然后我们去改系统的attachment类 我们在自己的模块下的classes文件夹下面建立一个myattachment.class.php
写一个我们自己的类.去集成系统的attachment类.(记得吧里面的私有方法copy过来.)我们需要修改几行.首先一点是吧upload方法里面的上传目录改掉.然后是改掉文件名的命名方法.
function upload($field, $alowexts = '', $maxsize = 0, $overwrite = 0,$thumb_setting = array(), $watermark_enable = 1) {
if(!isset($_FILES[$field])) {
$this->error = UPLOAD_ERR_OK;
return false;
}
if(empty($alowexts) || $alowexts == '') {
$site_setting = $this->_get_site_setting($this->siteid);
$alowexts = $site_setting['upload_allowext'];
}
$fn = $_GET['CKEditorFuncNum'] ? $_GET['CKEditorFuncNum'] : '1';
$this->field = $field;
$this->savepath = $this->upload_root.$this->upload_dir.date('Ymd');//这里我们需要修改下.也可以不修改.在我们实例化这个类的时候再来指定目录.
$this->alowexts = $alowexts;
$this->maxsize = $maxsize;
$this->overwrite = $overwrite;
$uploadfiles = array();
$description = isset($GLOBALS[$field.'_description']) ? $GLOBALS[$field.'_description'] : array();
if(is_array($_FILES[$field]['error'])) {
$this->uploads = count($_FILES[$field]['error']);
foreach($_FILES[$field]['error'] as $key => $error) {
if($error === UPLOAD_ERR_NO_FILE) continue;
if($error !== UPLOAD_ERR_OK) {
$this->error = $error;
return false;
}
$uploadfiles[$key] = array('tmp_name' => $_FILES[$field]['tmp_name'][$key], 'name' => $_FILES[$field]['name'][$key], 'type' => $_FILES[$field]['type'][$key], 'size' => $_FILES[$field]['size'][$key], 'error' => $_FILES[$field]['error'][$key], 'description'=>$description[$key],'fn'=>$fn);
}
} else {
$this->uploads = 1;
if(!$description) $description = '';
$uploadfiles[0] = array('tmp_name' => $_FILES[$field]['tmp_name'], 'name' => $_FILES[$field]['name'], 'type' => $_FILES[$field]['type'], 'size' => $_FILES[$field]['size'], 'error' => $_FILES[$field]['error'], 'description'=>$description,'fn'=>$fn);
}
if(!dir_create($this->savepath)) {
$this->error = '8';
return false;
}
if(!is_dir($this->savepath)) {
$this->error = '8';
return false;
}
@chmod($this->savepath, 0777);
if(!is_writeable($this->savepath)) {
$this->error = '9';
return false;
}
if(!$this->is_allow_upload()) {
$this->error = '13';
return false;
}
$aids = array();
foreach($uploadfiles as $k=>$file) {
$fileext = fileext($file['name']);
if($file['error'] != 0) {
$this->error = $file['error'];
return false;
}
if(!preg_match("/^(".$this->alowexts.")$/", $fileext)) {
$this->error = '10';
return false;
}
if($this->maxsize && $file['size'] > $this->maxsize) {
$this->error = '11';
return false;
}
if(!$this->isuploadedfile($file['tmp_name'])) {
$this->error = '12';
return false;
}
//$temp_filename = $this->getname($fileext);//名称在这里.我们需要修改下
$temp_filename = $file['tmp_name'].$fileext; //修改成原来的系统文件名称.
$savefile = $this->savepath.$temp_filename; $savefile = preg_replace("/(php|phtml|php3|php4|jsp|exe|dll|asp|cer|asa|shtml|shtm|aspx|asax|cgi|fcgi|pl)(\.|$)/i", "_\\1\\2", $savefile); $filepath = preg_replace(new_addslashes("|^".$this->upload_root."|"), "", $savefile); if(!$this->overwrite && file_exists($savefile)) continue; $upload_func = $this->upload_func; if(@$upload_func($file['tmp_name'], $savefile)) { $this->uploadeds++; @chmod($savefile, 0644); @unlink($file['tmp_name']); $file['name'] = iconv("utf-8",CHARSET,$file['name']); $uploadedfile = array('filename'=>$file['name'], 'filepath'=>$filepath, 'filesize'=>$file['size'], 'fileext'=>$fileext, 'fn'=>$file['fn']); $thumb_enable = is_array($thumb_setting) && ($thumb_setting[0] > 0 || $thumb_setting[1] > 0 ) ? 1 : 0; $image = new image($thumb_enable,$this->siteid); if($thumb_enable) { $image->thumb($savefile,'',$thumb_setting[0],$thumb_setting[1]); } if($watermark_enable) { $image->watermark($savefile, $savefile); } $aids[] = $this->add($uploadedfile); } } return $aids; }
注:这里我们可以再系统的attachment模块下建立MY_attachment.php 但是这样会影响系统的附件上传功能.
在我们自己的控制器里面.我们这个时候就需要加载自己写的类了.
pc_base::load_app_class('你的模块名','',0);
其余的操作可以参照系统的attachment模块下的attachments控制器里面的swfupload方法来修改.
至此.我便完成了我的目的.在不改变系统文件目录的基础上.完成我自己想要的文件上传功能.

PHP 유형은 코드 품질과 가독성을 향상시키기위한 프롬프트입니다. 1) 스칼라 유형 팁 : PHP7.0이므로 int, float 등과 같은 기능 매개 변수에 기본 데이터 유형을 지정할 수 있습니다. 2) 반환 유형 프롬프트 : 기능 반환 값 유형의 일관성을 확인하십시오. 3) Union 유형 프롬프트 : PHP8.0이므로 기능 매개 변수 또는 반환 값에 여러 유형을 지정할 수 있습니다. 4) Nullable 유형 프롬프트 : NULL 값을 포함하고 널 값을 반환 할 수있는 기능을 포함 할 수 있습니다.

PHP에서는 클론 키워드를 사용하여 객체 사본을 만들고 \ _ \ _ Clone Magic 메소드를 통해 클로닝 동작을 사용자 정의하십시오. 1. 복제 키워드를 사용하여 얕은 사본을 만들어 객체의 속성을 복제하지만 객체의 속성은 아닙니다. 2. \ _ \ _ 클론 방법은 얕은 복사 문제를 피하기 위해 중첩 된 물체를 깊이 복사 할 수 있습니다. 3. 복제의 순환 참조 및 성능 문제를 피하고 클로닝 작업을 최적화하여 효율성을 향상시키기 위해주의를 기울이십시오.

PHP는 웹 개발 및 컨텐츠 관리 시스템에 적합하며 Python은 데이터 과학, 기계 학습 및 자동화 스크립트에 적합합니다. 1.PHP는 빠르고 확장 가능한 웹 사이트 및 응용 프로그램을 구축하는 데 잘 작동하며 WordPress와 같은 CMS에서 일반적으로 사용됩니다. 2. Python은 Numpy 및 Tensorflow와 같은 풍부한 라이브러리를 통해 데이터 과학 및 기계 학습 분야에서 뛰어난 공연을했습니다.

HTTP 캐시 헤더의 주요 플레이어에는 캐시 제어, ETAG 및 최종 수정이 포함됩니다. 1. 캐시 제어는 캐싱 정책을 제어하는 데 사용됩니다. 예 : 캐시 제어 : Max-AGE = 3600, 공개. 2. ETAG는 고유 식별자를 통해 리소스 변경을 확인합니다. 예 : ETAG : "686897696A7C876B7E". 3. Last-modified는 리소스의 마지막 수정 시간을 나타냅니다. 예 : 마지막으로 변형 : Wed, 21oct201507 : 28 : 00GMT.

PHP에서 Password_hash 및 Password_Verify 기능을 사용하여 보안 비밀번호 해싱을 구현해야하며 MD5 또는 SHA1을 사용해서는 안됩니다. 1) Password_hash는 보안을 향상시키기 위해 소금 값이 포함 된 해시를 생성합니다. 2) Password_verify 암호를 확인하고 해시 값을 비교하여 보안을 보장합니다. 3) MD5 및 SHA1은 취약하고 소금 값이 부족하며 현대 암호 보안에는 적합하지 않습니다.

PHP는 동적 웹 개발 및 서버 측 응용 프로그램에 사용되는 서버 측 스크립팅 언어입니다. 1.PHP는 편집이 필요하지 않으며 빠른 발전에 적합한 해석 된 언어입니다. 2. PHP 코드는 HTML에 포함되어 웹 페이지를 쉽게 개발할 수 있습니다. 3. PHP는 서버 측 로직을 처리하고 HTML 출력을 생성하며 사용자 상호 작용 및 데이터 처리를 지원합니다. 4. PHP는 데이터베이스와 상호 작용하고 프로세스 양식 제출 및 서버 측 작업을 실행할 수 있습니다.

PHP는 지난 수십 년 동안 네트워크를 형성했으며 웹 개발에서 계속 중요한 역할을 할 것입니다. 1) PHP는 1994 년에 시작되었으며 MySQL과의 원활한 통합으로 인해 개발자에게 최초의 선택이되었습니다. 2) 핵심 기능에는 동적 컨텐츠 생성 및 데이터베이스와의 통합이 포함되며 웹 사이트를 실시간으로 업데이트하고 맞춤형 방식으로 표시 할 수 있습니다. 3) PHP의 광범위한 응용 및 생태계는 장기적인 영향을 미쳤지 만 버전 업데이트 및 보안 문제에 직면 해 있습니다. 4) PHP7의 출시와 같은 최근 몇 년간의 성능 향상을 통해 현대 언어와 경쟁 할 수 있습니다. 5) 앞으로 PHP는 컨테이너화 및 마이크로 서비스와 같은 새로운 도전을 다루어야하지만 유연성과 활발한 커뮤니티로 인해 적응력이 있습니다.

PHP의 핵심 이점에는 학습 용이성, 강력한 웹 개발 지원, 풍부한 라이브러리 및 프레임 워크, 고성능 및 확장 성, 크로스 플랫폼 호환성 및 비용 효율성이 포함됩니다. 1) 배우고 사용하기 쉽고 초보자에게 적합합니다. 2) 웹 서버와 우수한 통합 및 여러 데이터베이스를 지원합니다. 3) Laravel과 같은 강력한 프레임 워크가 있습니다. 4) 최적화를 통해 고성능을 달성 할 수 있습니다. 5) 여러 운영 체제 지원; 6) 개발 비용을 줄이기위한 오픈 소스.


핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

AI Hentai Generator
AI Hentai를 무료로 생성하십시오.

인기 기사

뜨거운 도구

Eclipse용 SAP NetWeaver 서버 어댑터
Eclipse를 SAP NetWeaver 애플리케이션 서버와 통합합니다.

안전한 시험 브라우저
안전한 시험 브라우저는 온라인 시험을 안전하게 치르기 위한 보안 브라우저 환경입니다. 이 소프트웨어는 모든 컴퓨터를 안전한 워크스테이션으로 바꿔줍니다. 이는 모든 유틸리티에 대한 액세스를 제어하고 학생들이 승인되지 않은 리소스를 사용하는 것을 방지합니다.

Atom Editor Mac 버전 다운로드
가장 인기 있는 오픈 소스 편집기

드림위버 CS6
시각적 웹 개발 도구

Dreamweaver Mac版
시각적 웹 개발 도구
