I am using Yii2 basic. I want to upload files to google drive using Yii2. I have created project in google console and generated the oauth and credentials. Everything is working fine in normal php. Files are getting uploaded to google drive in normal php. I have installed the plugin called googleclient api through composer. But while incorporating the same in yii2 it gives me error.
I have created a component called Upload and has getClient() function to register the google client api.
Following is the component class Upload in components directory,
<?php
namespace app\components;
include __DIR__ . '/vendor/autoload.php';
use Yii;
use yii\base\Component;
use yii\base\InvalidConfigException;
use google\apiclient\src\Google\Client;
class Upload extends Component
{
public function getClient()
{
$client = new Google_Client();
$client->setApplicationName('Google Drive API PHP Quickstart');
$client->setRedirectUri('http://localhost/lwa/basic/web');
$client->setScopes(Google_Service_Drive::DRIVE);
$client->setAuthConfig('credentials.json');
$client->setAccessType('offline');
$client->setPrompt('select_account consent');
// Load previously authorized token from a file, if it exists.
// The file token.json stores the user's access and refresh tokens, and is
// created automatically when the authorization flow completes for the first
// time.
$tokenPath = 'token.json';
if (file_exists($tokenPath)) {
$accessToken = json_decode(file_get_contents($tokenPath), true);
$client->setAccessToken($accessToken);
}
// If there is no previous token or it's expired.
if ($client->isAccessTokenExpired()) {
// Refresh the token if possible, else fetch a new one.
if ($client->getRefreshToken()) {
$client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
} else {
// Request authorization from the user.
$authUrl = $client->createAuthUrl();
printf("Open the following link in your browser:\n%s\n", $authUrl);
print 'Enter verification code: ';
$authCode = trim(fgets(STDIN));
// Exchange authorization code for an access token.
$accessToken = $client->fetchAccessTokenWithAuthCode($authCode);
$client->setAccessToken($accessToken);
// Check to see if there was an error.
if (array_key_exists('error', $accessToken)) {
throw new Exception(join(', ', $accessToken));
}
}
// Save the token to a file.
if (!file_exists(dirname($tokenPath))) {
mkdir(dirname($tokenPath), 0700, true);
}
file_put_contents($tokenPath, json_encode($client->getAccessToken()));
}
return $client;
}
// Get the API client and construct the service object.
$client = getClient();
//$service = new Google_Service_Drive($client);
}
I have a model as follows
<?php
namespace app\models;
use Yii;
use yii\helpers\ArrayHelper;
class UploadExcel extends \yii\base\Model
{
public $filepath;
public function rules()
{
return [
[['filepath'],'required'],
[['filepath'], 'file', 'extensions' => 'xlsx'],
];
}
public function attributeLabels()
{
return [
'filepath' => ' File',
];
}
}
The controller action create is as follows,
public function actionCreate()
{
$model = new UploadExcel();
if ($model->load(Yii::$app->request->post())) {
$file_tmp = $_FILES["file"]["tmp_name"];
$file_type = $_FILES["file"]["type"];
$file_name = basename($_FILES["file"]["name"]);
$path = "uploads/".$file_name;
move_uploaded_file($file_tmp, $path);
function check_folder_exists( $folder_name ){
$service = new Google_Service_Drive(new Google_Client() );
$parameters['q'] = "mimeType='application/vnd.google-apps.folder' and name='$folder_name' and trashed=false";
$files = $service->files->listFiles($parameters);
$op = [];
foreach( $files as $k => $file ){
$op[] = $file;
}
return $op;
}
function create_folder( $folder_name, $parent_folder_id=null ){
$folder_list = check_folder_exists( $folder_name );
// if folder does not exists
if( count( $folder_list ) == 0 ){
$service = new Google_Service_Drive( $GLOBALS['client'] );
$folder = new Google_Service_Drive_DriveFile();
$folder->setName( $folder_name );
$folder->setMimeType('application/vnd.google-apps.folder');
if( !empty( $parent_folder_id ) ){
$folder->setParents( [ $parent_folder_id ] );
}
$result = $service->files->create( $folder );
$folder_id = null;
if( isset( $result['id'] ) && !empty( $result['id'] ) ){
$folder_id = $result['id'];
}
return $folder_id;
}
return $folder_list[0]['id'];
}
$folder_id = create_folder( "excel1" );
function insert_file_to_drive( $file_path, $file_name, $parent_file_id = null ){
$service = new Google_Service_Drive( $GLOBALS['client'] );
$file = new Google_Service_Drive_DriveFile();
$file->setName( $file_name );
if( !empty( $parent_file_id ) ){
$file->setParents( [ $parent_file_id ] );
}
$result = $service->files->create(
$file,
array(
'data' => file_get_contents($file_path),
'mimeType' => 'application/octet-stream',
)
);
$is_success = false;
if( isset( $result['name'] ) && !empty( $result['name'] ) ){
$is_success = true;
}
return $is_success;
}
$success = insert_file_to_drive( $path , $file_name, $folder_id);
if( $success ){
echo "file uploaded successfully";
} else {
echo "Something went wrong.";
}
function dd( ...$d ){
echo "<pre style='background-color:#000;color:#fff;' >";
print_r($d);
exit;
}
}
//return $this->redirect(['view', 'id' => $model->ASCId]);
else{
return $this->render('create', [
'model' => $model,
]);
}
}
}
Now when I select the file to upload and click on submit button, it gives me error as
# Google_Service_Exception
## {
"error": {
"errors": [
{
"domain": "usageLimits",
"reason": "dailyLimitExceededUnreg",
"message": "Daily Limit for Unauthenticated Use Exceeded. Continued use requires signup.",
"extendedHelp": "https://code.google.com/apis/console"
}
],
"code": 403,
"message": "Daily Limit for Unauthenticated Use Exceeded. Continued use requires signup."
}
}