This article mainly introduces the image upload function of Yii combined with CKEditor. Yii is the famous PHP development framework, and CKEditor is the famous WYSIWYG editor. Friends in need can refer to this
In a project I worked on a few days ago, I needed to implement the image upload function in the WYSIWYG editor. I chose CKEditor because I liked its interface better. Although there is CKFinder that works well with CKEditor, its function is too complicated. After briefly looking at the documentation of CKEditor, I found that this function can be implemented by myself without the help of CKFinder.
Although the following code is based on Yii Framework, the idea is exactly the same when using other frameworks or languages. Children's shoes in need can be referred to.
First of all, to enable the image upload function in CkEditor, you need to configure the filebrowserImageUploadUrl attribute of the editor:
CKEDITOR.replace( 'editor1', { filebrowserUploadUrl : '/uploader/upload.php', filebrowserImageUploadUrl : '/uploader/upload.php?type=Images' });
Then implement the image upload function on the corresponding URL and return a specific format to CKEditor HTML code, CKEditor can preview and insert pictures normally.
Only part of the code of the controller is intercepted below. I implemented the Controller part like this:
/** * 保存上传的图片 * * @return string javascript code * @author lfyzjck **/ public function actionImg($type, $CKEditor, $CKEditorFuncNum, $langCode = 'zh-cn') { if(empty($CKEditorFuncNum) || $type != 'Images'){ $this->mkhtml($CKEditorFuncNum,'','错误的函数调用'); } if(isset($_FILES['upload'])){ //获取关于图片上传配置 $options = Options::model()->findByPk(1); $form = new UploadForm('image',$options); $form->upload = CUploadedFile::getInstanceByName('upload'); if($form->validate()){ //文件名:时间+源文件名 $target_filename = date('Ymd-hm',time()).$form->upload->getName(); $path = Yii::app()->basePath.'/../uploads/'.$target_filename; //图片保存路径 $form->upload->saveAs($path); $this->mkhtml($CKEditorFuncNum,Yii::app()->baseUrl.'/uploads/'.$target_filename, "上传成功"); } else{ $this->mkhtml($CKEditorFuncNum,'',$form->getError('upload')); } } } /** * 返回CKEditor的提示信息 * * @return void * @author lfyzjck **/ private function mkhtml($fn, $fileurl, $message) { $str = ''; exit($str); }
The mkhtml function that needs special explanation will call the CKEditor function to generate prompt information. When the upload is successful, the image link will be returned, and CKEditor will generate an image preview based on the URL.
Then comes the UploadForm code, which will verify whether the format and size of the image meet the requirements.
class UploadForm extends CFormModel { public $upload; private $options; private $type; public function __construct($type, $options){ $this->options = $options; $this->type = $type; } /** * Declares the validation rules. * The rules state that username and password are required, * and password needs to be authenticated. */ public function rules() { return array( array('upload', 'file', 'types' => $this->options->getAttribute("allow_".$this->type."_type"), 'maxSize' => 1024 * (int)$this->options->getAttribute("allow_".$this->type."_maxsize"), 'tooLarge'=>'文件大小超过限制', ), ); } }
The above is the entire content of this article. I hope it will be helpful to everyone's study. For more related content, please pay attention to the PHP Chinese website!
Related recommendations:
About Yii
Framework method to obtain all subclasses under a category
How Yii2 uses the Bootbox plug-in to implement custom pop-up windows
Use Yii2 rbac permission control menu menu
The above is the detailed content of Yii and CKEditor implement image upload function. For more information, please follow other related articles on the PHP Chinese website!

ThesecrettokeepingaPHP-poweredwebsiterunningsmoothlyunderheavyloadinvolvesseveralkeystrategies:1)ImplementopcodecachingwithOPcachetoreducescriptexecutiontime,2)UsedatabasequerycachingwithRedistolessendatabaseload,3)LeverageCDNslikeCloudflareforservin

You should care about DependencyInjection(DI) because it makes your code clearer and easier to maintain. 1) DI makes it more modular by decoupling classes, 2) improves the convenience of testing and code flexibility, 3) Use DI containers to manage complex dependencies, but pay attention to performance impact and circular dependencies, 4) The best practice is to rely on abstract interfaces to achieve loose coupling.

Yes,optimizingaPHPapplicationispossibleandessential.1)ImplementcachingusingAPCutoreducedatabaseload.2)Optimizedatabaseswithindexing,efficientqueries,andconnectionpooling.3)Enhancecodewithbuilt-infunctions,avoidingglobalvariables,andusingopcodecaching

ThekeystrategiestosignificantlyboostPHPapplicationperformanceare:1)UseopcodecachinglikeOPcachetoreduceexecutiontime,2)Optimizedatabaseinteractionswithpreparedstatementsandproperindexing,3)ConfigurewebserverslikeNginxwithPHP-FPMforbetterperformance,4)

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Dreamweaver Mac version
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

WebStorm Mac version
Useful JavaScript development tools

Atom editor mac version download
The most popular open source editor

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software
