search
HomePHP FrameworkYIIyii2 failed to upload file

yii2 failed to upload file

Feb 18, 2020 pm 03:17 PM
yii2

yii2 failed to upload file

Let’s take a look at the code first:

First look at the View part:

<form action="<?= Url::to([&#39;default/datafile&#39;]) ?>" method="post" enctype="multipart/form-data">
    <label for="file">Filename:</label>
    <input type="file" name="myFile" id="file" />
    <br />
    <input type="submit" name="submit" value="Submit" />
</form>

The above action is built using the YII helper class The url that can be recognized internally is actionDatafile()

in DeaufaultController.php (recommended tutorial: yii framework)

 public function actionDatafile(){
        if(empty($_FILES)){
            $status = 1;
            $info = &#39;没有文件上传&#39;;
        }
        if($_FILES[&#39;myFile&#39;][&#39;error&#39;] === 0 || $_FILES[&#39;myFile&#39;][&#39;error&#39;] === &#39;0&#39; ){
            //文件上传成功
            $tmp = pathinfo($_FILES[&#39;myFile&#39;][&#39;name&#39;]);
            $new_fname = $tmp[&#39;filename&#39;].&#39;_&#39;.rand(1000000,9999999).&#39;.&#39;.$tmp[&#39;extension&#39;];
            echo $new_fname;
            if(!move_uploaded_file($_FILES[&#39;myFile&#39;][&#39;tmp_name&#39;], &#39;../runtime/file/&#39;.$new_fname)){
                $status = 1;
                $info = &#39;上传(移动)失败&#39;;
            }else{
                $status = 0;
                $info = &#39;上传成功&#39;;
            }
        } else {
            //文件上传失败
            $info = &#39;文件上传失败&#39;;
            switch($_FILES[&#39;myFile&#39;][&#39;error&#39;]){
                case 1:
                    $info = &#39;上传文件超过php.ini中upload_max_filesize配置参数&#39;;
                    break;
                case 2:
                    $info = &#39;上传文件超过表单MAX_FILE_SIZE选项指定的值&#39;;
                    break;
                case 3:
                    $info = &#39;文件只有部份被上传&#39;;
                    break;
                case 4:
                    $info = &#39;没有文件被上传&#39;;
                    break;
                case 5:
                    $info = &#39;上传文件大小为0&#39;;
                    break;
            }
            $status = 1;
        }
        return $info;
    }

found after execution

yii2 failed to upload file

Solution:

1. Check the configuration (php.ini)

file_uploads, upload_max_filesize, post_max_size, and upload_tmp_dir have been set.

2. Check the parameters

Found crsf in the parameters. This parameter is included in the yii framework verification. When it comes to verification, it is similar to the error message. Add the cancellation verification code, as follows:

public function beforeAction($action)
    {
        if ($action->id == &#39;datafile&#39;) {
            $this->enableCsrfValidation = false;
        }
 
        return parent::beforeAction($action);
    }

For more programming-related content, please pay attention to the Programming Introduction column on the php Chinese website!

The above is the detailed content of yii2 failed to upload file. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Key Skills for Yii Development: Building Robust Web ApplicationsKey Skills for Yii Development: Building Robust Web ApplicationsMay 14, 2025 am 12:03 AM

TobuildrobustwebapplicationswithYii,mastertheseskills:1)MVCarchitectureforstructuringapplications,2)ActiveRecordforefficientdatabaseoperations,3)WidgetsystemforreusableUIcomponents,4)Validationandsecuritymeasures,5)Cachingforperformanceoptimization,a

What Skills Are Required to Become a Successful Yii Developer?What Skills Are Required to Become a Successful Yii Developer?May 13, 2025 am 12:01 AM

TobecomeasuccessfulYiideveloper,youneed:1)PHPmastery,2)understandingofMVCarchitecture,3)Yiiframeworkproficiency,4)databasemanagementskills,5)front-endknowledge,6)APIdevelopmentexpertise,7)testinganddebuggingcapabilities,8)versioncontrolproficiency,9)

Yii Developers: Common ErrorsYii Developers: Common ErrorsMay 12, 2025 am 12:04 AM

ThemostcommonerrorsinYiiframeworkare"UnknownProperty","InvalidConfiguration","ClassNotFound",and"ValidationErrors".1."UnknownProperty"errorsoccurwhenaccessingnon-existentproperties;ensurepropertiesexi

Yii Developer: Most recquired skills in EuropeYii Developer: Most recquired skills in EuropeMay 11, 2025 am 12:02 AM

The key skills that European Yii developers need to possess include: 1. Yii framework proficiency, 2. PHP proficiency, 3. Database management, 4. Front-end skills, 5. RESTful API development, 6. Version control system, 7. Testing and debugging, 8. Security knowledge, 9. Agile methodology, 10. Soft skills, 11. Localization and internationalization, 12. Continuous learning, these skills make developers stand out in the European market.

Yii: Is the community still active?Yii: Is the community still active?May 10, 2025 am 12:03 AM

Yes,theYiicommunityisstillactiveandvibrant.1)TheofficialYiiforumremainsaresourcefordiscussionsandsupport.2)TheGitHubrepositoryshowsregularcommitsandpullrequests,indicatingongoingdevelopment.3)StackOverflowcontinuestohostYii-relatedquestionsandhigh-qu

Is it easy to migrate a Laravel Project to Yii?Is it easy to migrate a Laravel Project to Yii?May 09, 2025 am 12:01 AM

Migratingalaravel Projecttoyiiishallingbutachieffable WITHIEFLEFLANT.1) Mapoutlaravel component likeroutes, Controllers, Andmodels.2) Translatelaravel's SartisancommandeloequentTooyii's giiandetiverecordeba

Essential Soft Skills for Yii Developers: Communication and CollaborationEssential Soft Skills for Yii Developers: Communication and CollaborationMay 08, 2025 am 12:11 AM

Soft skills are crucial to Yii developers because they facilitate team communication and collaboration. 1) Effective communication ensures that the project is progressing smoothly, such as through clear API documentation and regular meetings. 2) Collaborate to enhance team interaction through Yii's tools such as Gii to improve development efficiency.

Laravel MVC : What are the best benefits?Laravel MVC : What are the best benefits?May 07, 2025 pm 03:53 PM

Laravel'sMVCarchitectureoffersenhancedcodeorganization,improvedmaintainability,andarobustseparationofconcerns.1)Itkeepscodeorganized,makingnavigationandteamworkeasier.2)Itcompartmentalizestheapplication,simplifyingtroubleshootingandmaintenance.3)Itse

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Article

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),