Yii2如何在控制器中包含php文件


Yii2 how to include a php file in a Controller

在我的Yii2框架工作项目中,我想包括一个php文件。该文件包含两个功能文件名"encryptdecrypt.php",并将其保存在公用''扩展文件夹中

<?
    public function encryptIt( $q ) {
        $cryptKey  = 'OrangeOnlineMedia';
        $qEncoded      = base64_encode( mcrypt_encrypt( MCRYPT_RIJNDAEL_256, md5( $cryptKey ), $q, MCRYPT_MODE_CBC, md5( md5( $cryptKey ) ) ) );
        return( $qEncoded );
    }
    public function decryptIt( $q ) {
        $cryptKey  = 'OrangeOnlineMedia';
        $qDecoded      = rtrim( mcrypt_decrypt( MCRYPT_RIJNDAEL_256, md5( $cryptKey ), base64_decode( $q ), MCRYPT_MODE_CBC, md5( md5( $cryptKey ) ) ), "'0");
        return( $qDecoded );
    }
    ?>

我在控制器页面("客户控制器")中包括这一行

页面顶部包括使用这行

$encFile =Yii::getAlias('@common'). ''extensions'encryptdecrypt.php';
require_once($encFile);

并在动作中使用该函数下方的代码

public function actionCreate()
{
    $model = new Customers();
    if ($model->load(Yii::$app->request->post()) ) {
        $model->password=encryptIt($model->password);            
        if($model->created_date==null)
        {
          $model->created_date=date('y-m-d') ; 
        }
        $model->save();
        return $this->redirect(['view', 'id' => $model->customer_id]);
    } else {
        return $this->render('create', [
            'model' => $model,
        ]);
    }
}

我得到以下错误"调用未定义的函数backend''controlles''encryptIt()"

感谢

Yii2使用PSR-4自动加载器规则,因此首先保存Security.php

common'extensions文件夹中,打开Security.php并在其中创建类。

<?php
namespace common'extensions;
class Security {
    public function encrypt(){
    // todo
    }
    public function decrypt(){
    // todo
    }
}

然后在你的CustomersController动作中Create像这样使用它:

public function actionCreate()
{
    $model = new Customers();
    if ($model->load(Yii::$app->request->post()) ) {
        $security = new 'common'extensions'Security(); // <-- Create Object Here
        $model->password= $security->encrypt($model->password);            
        if($model->created_date==null)
        {
          $model->created_date=date('y-m-d') ; 
        }
        $model->save();
        return $this->redirect(['view', 'id' => $model->customer_id]);
    } else {
        return $this->render('create', [
            'model' => $model,
        ]);
    }
}

BTW在Yii2中,您也可以生成这样的安全密码哈希:Yii::$app->security->generatePasswordHash($password);

可能是您使用了错误的文件夹。正如你提到的,文件在common'extension folder

$encFile =Yii::getAlias('@common'). ''extension'encryptdecrypt.php';
require_once($encFile);

尝试获取

 $encFile = Yii::getAlias('@common/extensions/encryptdecrypt.php'); 

也尝试

var_dump($encFile) 

并检查路径名

使用DOCUMENT_ROOT

当前脚本在其下执行的文档根目录,如服务器的配置文件中所定义。

示例

无论服务器类型如何,都要包含文件,请执行以下操作:

$_SERVER['DOCUMENT_ROOT'] .Yii::getAlias('@common/sub_directory/yourFileName.php');
// outputs something like: /var/www/YiiApp/common/sub_directory/yourFileName.php
# or 
$_SERVER['DOCUMENT_ROOT'] .Yii::getAlias('@web/images/image.jpg');
// outputs something like: /var/www/YiiApp/web/images/image.jpg