Hi am using this OneDrive SDK . https://github.com/krizalys/onedrive-php-sdk . I am using PHP. What I need is to create a cronjob that will fetch my files in OneDrive and save it to my local directory. It works fine following the tutorial in the SDK. However, the way that SDK works is it needs you to be redirected to Microsoft account login page to be authenticated.
This will require a browser. My question, is it possible to do this by just running it in the backend like a cron? I can't seem to find a way to do it using the SDK. In Google, they will provide you a key to access the services without logging in every time. I am not sure about OneDrive.
$localPath = __DIR__.'/uploads/';
$today = date('Y-m-d');
$folder = $client->getMyDrive()->getDriveItemByPath('/'.$today);
echo "<pre>";
try {
$files = $folder->getChildren();
$createdDirectory = $localPath.$today;
// Check if directory exist
if(is_dir($createdDirectory)){
echo "\n"." Directory ".$createdDirectory." already exists, creating a new one..";
// Create new directory
$uuid1 = Uuid::uuid1();
$createdDirectory = $createdDirectory.$uuid1->toString();
echo "\n".$createdDirectory." created..";
}
// Create directory
mkdir($createdDirectory);
echo "\n".count($files)." found for ".$today;
// Loop thru files inside the folder
foreach ($files as $file){
$save = $file->download();
// Write file to directory
$fp = fopen($createdDirectory.'/'.$file->name, 'w');
fwrite($fp, $save);
echo("\n File ".$file->name." saved!");
}
} catch (Exception $e){
die("\n".$e->getMessage());
}
die("\n Process Complete!");
My code is something like that in the redirect.php
It doesn't look like that SDK supports the Client Credentials OAuth Grant. Without that, the answer is no. You may want to look at the official Microsoft Graph SDK for PHP which supports this via the Guzzle HTTP client:
$guzzle = new \GuzzleHttp\Client();
$url = 'https://login.microsoftonline.com/' . $tenantId . '/oauth2/token?api-version=1.0';
$token = json_decode($guzzle->post($url, [
'form_params' => [
'client_id' => $clientId,
'client_secret' => $clientSecret,
'resource' => 'https://graph.microsoft.com/',
'grant_type' => 'client_credentials',
],
])->getBody()->getContents());
$accessToken = $token->access_token;
Related
im using php google SDK (PHP 7.2.27), The process to create signed url v4 takes >1500 ms. what i want to ask is it this normal? or something wrong with my setup? can it be optimized? the real code have caching mechanism so its solved the problem when the url already created, it will be problem if happen for the first time. here's the part of code to create signed url v4 :
<?php
require __DIR__ . '/vendor/autoload.php';
use Google\Cloud\Storage\StorageClient;
$bucketName = <REDACTED>
$objectName = <REDACTED>
$process_time = microtime(true);
$storage = new StorageClient();
$bucket = $storage->bucket($bucketName);
$object = $bucket->object($objectName);
$url = $object->signedUrl(
# This URL is valid for 15 minutes
new \DateTime('30 sec'),
[
'version' => 'v4',
'keyFilePath' => dirname(__FILE__)."/<REDACTED>.json"
]
);
$process_time = microtime(true) - $process_time;
echo "Process Time : ".$process_time."\n";
print('Generated GET signed URL:' . PHP_EOL);
print($url . PHP_EOL);
Update:
the cause is at "$storage = new StorageClient();"
using php 8.1 and its still takes >1500ms
this is snoop file of that "new StorageClient()" do :
Change
$storage = new StorageClient();
to
$storage = new StorageClient([
'projectId' => '<your_related_project_id_to_object_bucket_location>'
]);
the first one (without parameter) is an example from official document that slows down the connection about 1500ms, as someone totally new in GCP this documentation bring more confusion than clear explanation, dont use it.
I am having trouble authenticating and accessing the Microsoft Graph API via PHP.
I have the Azure app all setup with clientID and clientSecret codes, as well as the correct redirectURI.
When I try to view this PHP code in web browser, I get a HTTP 500 error.
I have the below code:
<?php
use Microsoft\Graph\Graph;
use Microsoft\Graph\Model;
$clientSecret = 'SAMPLE';
$clientId = 'SAMPLE';
$redirectUri = 'SAMPLE';
$tenantId = 'SAMPLE';
$guzzle = new \GuzzleHttp\Client();
$url = 'https://login.microsoftonline.com/' . $tenantId . '/oauth2/token?api-version=1.0';
$token = json_decode($guzzle->post($url, [
'form_params' => [
'client_id' => $clientId,
'client_secret' => $clientSecret,
'resource' => 'https://graph.microsoft.com/',
'grant_type' => 'client_credentials',
],
])->getBody()->getContents());
$accessToken = $token->access_token;
$graph = new Graph();
$graph->setAccessToken($accessToken);
$user = $graph->createRequest("GET", "/me")
->setReturnType(Model\User::class)
->execute();
echo "<script type='text/javascript'>alert('$user->getGivenName()');</script>";
?>
I am hoping someone can provide anything useful, as I can't seem to find documentation anywhere on this.
I have also had to install composer.phar on web hosting via SSH, and am not sure if that is running correctly / in the correct directory. It does have all the required add-ins installed though such as guzzleHTTP, Microsoft Graph, and oauth2.
I have been trying to upload files to my google drive account via service-account using php. I guess the file is successfully uploaded as I can print the file id, file created time and all other information.
Here is my issue: When I login into my google drive account, I cannot see any uploaded file. Where is the file hiding or what should I do?
Here is the code:
require __DIR__ . '/vendor/autoload.php'; //api
$serviceAccount = "xxx#xxxxxx.iam.gserviceaccount.com";
$key_file = "mykey-goes-here.p12";
$auth = new Google_Auth_AssertionCredentials(
$serviceAccount,
array('https://www.googleapis.com/auth/drive.file'),
file_get_contents($key_file)
);
$client = new Google_Client();
$client->setAssertionCredentials( $auth );
$service = new Google_Service_Drive($client);
$file = new Google_Service_Drive_DriveFile();
$file->setTitle("my file name");
$file->setDescription('testing desc');
$file->setMimeType('text/plain');
// Provide file name here and path in below
$result = $service->files->insert($file, array(
'data' => file_get_contents("test.txt"),
//'mimeType' => 'text/plain',
'mimeType' => 'application/octet-stream',
'uploadType' => 'media',
//'uploadType' => 'multipart'
));
// Uncomment the following line to print the File ID
printf("File ID: %s\n", $result->id);
echo "<br><br>";
echo '<pre>'; print_r($result); echo'</pre>';
solution:
I discovered that Files uploaded by service account is not available via UI.
To solve the issue, one need to delegate/authorize the application to use the said service account.
link
I'm totally new to Google Cloud Storage (since I used Amazon S3 until now).
I want to set up my web application, so that users can download files directly from the Google Cloud Storage.
I've already tried it, using the Google Api PHP Client, but didn't get a functionally code.
I've uploaded a test file named "test.jpg" to my bucket "test-bucket-46856" which I want to download via signed url (so that users only have time limited access), but I have no idea how to get this started.
Please help. Thanks.
//Edit:
Found the perfect solution. Here the link for all others who are also searching for this solution:
https://gist.github.com/stetic/c97c94a10f9c6b591883
<?php
/*
* PHP Example for Google Storage Up- and Download
* with Google APIs Client Library for PHP:
* https://github.com/google/google-api-php-client
*/
include( "Google/Client.php" );
include( "Google/Service/Storage.php" );
$serviceAccount = "1234-xyz#developer.gserviceaccount.com";
$key_file = "/path/to/keyfile.p12";
$bucket = "my_bucket";
$file_name = "test.txt";
$file_content = "01101010 01110101 01110011 01110100 00100000 01100001 00100000 01110100 01100101 01110011 01110100";
$auth = new Google_Auth_AssertionCredentials(
$serviceAccount,
array('https://www.googleapis.com/auth/devstorage.read_write'),
file_get_contents($key_file)
);
$client = new Google_Client();
$client->setAssertionCredentials( $auth );
$storageService = new Google_Service_Storage( $client );
/***
* Write file to Google Storage
*/
try
{
$postbody = array(
'name' => $file_name,
'data' => $file_content,
'uploadType' => "media"
);
$gsso = new Google_Service_Storage_StorageObject();
$gsso->setName( $file_name );
$result = $storageService->objects->insert( $bucket, $gsso, $postbody );
print_r($result);
}
catch (Exception $e)
{
print $e->getMessage();
}
/***
* Read file from Google Storage
*/
try
{
$object = $storageService->objects->get( $bucket, $file_name );
$request = new Google_Http_Request($object['mediaLink'], 'GET');
$signed_request = $client->getAuth()->sign($request);
$http_request = $client->getIo()->makeRequest($signed_request);
echo $http_request->getResponseBody();
}
catch (Exception $e)
{
print $e->getMessage();
}
I am trying to upload a file to the Amazon S3 using the AWS PHP SDK but whenever I try uploading, the script gives output till the PutObject operation but no output after that operation. I am not even able to dump the result object. The credentials are stored in the .aws in the root folder of my test machine (running Ubuntu). Below is the code -
$s3 = new Aws\S3\S3Client([
'version' => 'latest',
'region' => 'us-east-1'
]);
echo "<br />".realpath(UPLOAD_DIR . $apiKEY . "/" . $name);
try {
$result = $s3->putObject([
'Bucket' => 'quicklyusercannedspeechbucket',
'ContentType' => 'text/plain',
'Key' => $apiKEY . "/" . $name,
'SourceFile' => realpath(UPLOAD_DIR . $apiKEY . "/" . $name)
]);
var_dump($result);
}
catch(\Aws\S3\Exception\S3Exception $e) {
echo $e->getAwsErrorCode();
}
echo "Finished";
var_dump($result);
When I run the above code, I don't get any output for the $result array. Any idea what might be happening?
Any help is appreciated ^_^
-Pranav
Use below code to view if your image is uploaded successfully
try {
$result = $s3->putObject([
'Bucket' => 'quicklyusercannedspeechbucket',
'ContentType' => 'text/plain',
'Key' => $apiKEY . "/" . $name,
'SourceFile' => realpath(UPLOAD_DIR . $apiKEY . "/" . $name)
]);
$s3file='http://quicklyusercannedspeechbucket.s3.amazonaws.com/'.$name;
echo "<img src='$s3file'/>";
echo 'S3 File URL:'.$s3file;
var_dump($result);
}
catch(\Aws\S3\Exception\S3Exception $e) {
echo $e->getAwsErrorCode();
}
You can get step by step detail from here Amazon S3 File Upload Using PHP
It seems that I had put the credentials in the wrong folder. As per the NGINX, the default folder for storing the credentials was /var/www rather than the home directory of the user.
Also, I turned on the display_errors in the php.ini which helped me find that the AWS SDK was having problems with the credentials.
Thanks!