I want to copy file from google drive to another server using php.
I have used google drive picker and when user clicks on any file I used to get download url, I was thinking that it can be done through copy function, but it didn't work.
Any solution Please.
function getDownloadurl(fileId) {
var request = gapi.client.request({
'path': '/drive/v2/files/' + fileId,
'params': { 'maxResults': '1000' },
callback: function (responsejs, responsetxt) {
var fileDownloadUrl = responsejs.downloadUrl;
$.ajax({
type: "POST",
url: "ajax-files/copy_drive_file.php",
data: { gd_url:fileDownloadUrl },
async:false,
success: function(data)
{
}
});
copy_drive_file.php
$sourcePath=$_POST['gd_url'];
copy($sourcePath, 'sss/file.jpg');
You need to authorize and authenticate your requests while fetching from PHP
YourJsFile
function getDownloadurl(fileId) {
var accessToken = gapi.auth.getToken().access_token;
var request = gapi.client.request({
'path': '/drive/v2/files/' + fileId,
'params': {
'maxResults': '1000'
},
callback: function(responsejs, responsetxt) {
var fileDownloadUrl = responsejs.downloadUrl;
$.ajax({
type: "POST",
url: "ajax-files/copy_drive_file.php",
data: {
gd_url: fileDownloadUrl,
accessToken: accessToken
},
async: false,
success: function(data) {
console.log(data);
}
});
}
});
}
copy_drive_file.php
if ( isset($_POST['gd_url']) && isset($_POST['accessToken'])) {
$url = $_POST['gd_url'];
$accessToken = $_POST['accessToken'];
$opts = array(
'http'=>array(
'method'=>"GET",
'header' => "Authorization: Bearer " . $accessToken
)
);
$context = stream_context_create($opts);
$content = file_get_contents($url, false, $context);
if (!empty($content)){
file_put_contents("path/filename.file_extension",$content);
echo json_encode(array('file_name' => "filename.file_extension"));
}
}
Maybe this will help?
function copyFile($service, $originFileId, $copyTitle) {
$copiedFile = new Google_Service_Drive_DriveFile();
$copiedFile->setTitle($copyTitle);
try {
return $service->files->copy($originFileId, $copiedFile);
} catch (Exception $e) {
print "An error occurred: " . $e->getMessage();
}
return NULL;
}
Related
Good day!
What I want to achieve is when user clicks the link, it will pass the parameter to javascript, which then using ajax to call the php file where my API is. The API will process the parameter and return a json result.
My code works when the parameter values are given correctly. However I'm stuck at the part where the values are incorrect/invalid and I need to catch the error.
The API document says that if the RESPONSE is 200, then it's a success. Else there is error. My issue is I have no idea how to get this "RESPONSE == 200". Any advise is appreciated!
function callMS_API(addr, cur)
{
$.ajax({
type:'POST',
url:'merklescienceAPI.php',
data:{
WalAddr:addr,
CryCur:cur,
wrapper:"testing"
},
success: function(res)
{
if(res!=200)
{
alert("Invalid Wallet Address!");
}
else
{
alert(res);
}
}
});// ajax
} //end callMS_API
merklescienceAPI.php
<?php
$addr=$_POST['WalAddr']; //Wallet Addr
$cur=$_POST['CryCur']; //Cryptocurrency
$cur_code;
$result = "";
switch ($cur) {
case "Bitcoin":
$cur_code = 0;
break;
case "Ethereum":
$cur_code = 1;
break;
case "LiteCoin":
$cur_code = 2;
break;
case "Tether USD":
$cur_code = 10;
break;
}
require_once('../vendor/autoload.php');
$client = new \GuzzleHttp\Client();
$response = $client->post('https://api.merklescience.com/api/v3/addresses/', [
'body' => '{"identifier":"'.$addr.'","currency":"'.$cur_code.'"}',
'headers' => [
'Accept' => 'application/json',
'Content-Type' => 'application/json',
'X-API-KEY' => '<API KEY>',
],
]);
$data = json_decode($response->getBody());
$result = "SCREENING: " . $data->identifier . "\n\nAddress Risk Level : " . $data->risk_level_verbose;
//Whatever you echo will go to javascript success: function(res), and you can do alert(res)
echo $result;
?>
====================================================================
Edit + Solution
I read and tested further on the Guzzle thingy, and came across this thread. I implemented the Try Catch in the API.php and got my result.
Javascript function
function callMS_API(addr, cur)
{
$.ajax({
type:'POST',
url:'merklescienceAPI.php',
data:{
WalAddr:addr,
CryCur:cur,
wrapper:"testing"
},
success: function(res)
{
alert(res);
}
});//ajax
} //end callMS_API
API.php
try{
$client = new \GuzzleHttp\Client();
$response = $client->post('https://api.merklescience.com/api/v3/addresses/', [
'body' => '{"identifier":"'.$addr.'","currency":"'.$cur_code.'"}',
'headers' => [
'Accept' => 'application/json',
'Content-Type' => 'application/json',
'X-API-KEY' => '<API KEY>',
],
]);
}catch(Exception $e){
$error = true;
}
if($error == false)
{
$data = json_decode($response->getBody());
$result = "SCREENING: " . $data->identifier . "\n\nRisk Level : " . $data->risk_level . " - " . $data->risk_level_verbose;
}else
{
$result = "Invalid Wallet Address!";
}
echo $result;
Thank you everyone for your help!
If you mean status code or HTTP status code 200 you could try add this line to your ajax option:
...
$.ajax({
...
statusCode: {
200: function() {
alert( "200 reaced" );
},
error: function(response) {
if(response.status != 200)
alert(" status code is " + response.status);
}
...
in Ajax
$.ajax({type:'POST',
url:'somefile.php',
data:{
a name:"a value"
} ,
success: <<THIS EXECUTES WITH A 200 RESPONSE>>,
error: <<THIS EXECUTES IF IT GOES BAD>>
});
The success: runs ONLY if the response is 200. for everything else you capture it with error:
I have been trying to work this out for hours now and cannot find any answer that helps me.
This is the code in my javascript file
function sendMovement(cel) {
var name = "test";
$.ajax({
type: 'POST',
url: '../game.php',
data: { 'Name': name },
success: function(response) {
console.log("sent");
}
});
}
This is the code from my PHP file (it is outside the js file)
if($_SERVER["REQUEST_METHOD"] == "POST") {
$data = $_POST['Name'];
console_log($data);
}
When debugging I can see that AJAX is sending a POST and it does print in the console "SENT" but it does not print $data
update: the function console_log() exists in my PHP file and it works
Try getting response in JSON format, for that your js should have dataType:'JSON' as shown below
JS Code:-
function sendMovement(cel) {
var name = "test";
$.ajax({
type: 'POST',
dataType:'JSON', //added this it to expect data response in JSON format
url: '../game.php',
data: { 'Name': name },
success: function(response) {
//logging the name from response
console.log(response.Name);
}
});
}
and in the current server side code you are not echoing or returning anything, so nothing would display in ajax response anyways.
changes in php server code:-
if($_SERVER["REQUEST_METHOD"] == "POST") {
$response = array();
$response['Name'] = $_POST['Name'];
//sending the response in JSON format
echo json_encode($response);
}
I fixed it by doing the following:
To my game.php I added the following HTML code (for debugging purposes)
<p style = "color: white;" id="response"></p>
Also added in my game.php the following
if($_SERVER["REQUEST_METHOD"] == "POST") {
$gameID = $_POST['gameID'];
$coord = $_POST['coord'];
$player = $_POST['player'];
echo "gameID: " . $gameID . "\nCoord: " . $coord . "\nPlayer: " . $player;
}
AND in my custom.js I updated
function sendMovement(cel) {
var handle = document.getElementById('response');
var info = [gameID, cel.id, current_player];
$.ajax({
type: 'POST',
url: '../game.php',
data: {
gameID: info[0],
coord: info[1],
player: info[2]
},
success: function(data) {
handle.innerHTML = data;
},
error: function (jqXHR) {
handle.innerText = 'Error: ' + jqXHR.status;
}
});
}
I am trying to delete a record from my products table, each product has an image. I don't know how to delete the image from the file where it is stored.
Product.js
$(document).ready(function() {
$("#btn-delete").click(function() {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type: 'DELETE',
url: '/product/' + $("#frmDeleteProduct input[name=product_id]").val(),
dataType: 'json',
success: function(data) {
$("#frmDeleteProduct .close").click();
window.location.reload();
},
error: function(data) {
console.log(data);
}
});
});
});
function deleteProductForm(product_id) {
$.ajax({
type: 'GET',
url: '/product/' + product_id,
success: function(data) {
$("#frmDeleteProduct #delete-title").html("¿Do you want to delete this product (" + data.products.name + ")?");
$("#frmDeleteProduct input[name=product_id]").val(data.products.id);
$('#deleteProductModal').modal('show');
},
error: function(data) {
console.log(data);
}
});
}
ProductController.php
I read that I need to put something like this in my controller File::delete('img/products/' . $image); but I don't now how.
public function destroy($id)
{
//File::delete('img/products/' . $image);
$products = Product::destroy($id);
return response()->json([
'error' => false,
'products' => $products,
], 200);
}
You need to pass as a parameter to File::delete() the full path when your image was save. For example, if your images were in a laravel storage path in the subdirectory img/products/, and the name of the image is the id of the product with the .jpg extension, you can do this:
public function destroy($id)
{
$fullImgPath = storage_path("img/products/$id.jpg");
if(File::exists($fullImgPath)) {
File::delete($fullImgPath);
}
$products = Product::destroy($id);
return response()->json([
'error' => false,
'products' => $products,
], 200);
}
But if you have the name of the image in your Product model, you can do this:
public function destroy($id)
{
$product = Product::find($id);
$fullImgPath = storage_path("img/products/".$product->image_name);
if(File::exists($fullImgPath)) {
File::delete($fullImgPath);
}
$product->delete();
return response()->json([
'error' => false,
'products' => $product->id,
], 200);
}
I have multiple uploads on a page, and I am workin on tidying it up, so:
Here's my js:
$(".img").change(function () {
var form = $(this).closest('form');
getPath(form);
})
deleteButton();
copyGalleryData();
});
function getPath(form) {
var name = $(form).attr('name');
submitImage(form, name);
}
var path_to_delete;
function submitImage(form, name) {
var url = '/image/upload';
var form_data = new FormData($(form)[0]);
submit(name);
form_data.append('img', $(form).children(".img"));
$.ajax({
url: url,
data: form_data,
dataType: 'json',
async: true,
type: 'post',
processData: false,
contentType: false,
success: function (data) {
console.log(data);
$(form).children('.image-container').append('<img id="image" name=' + name + '" src="' + data + '" />')
$(".imageDelete").attr('data', data);
alerts();
var deleting = false;
success(name, deleting, data);
$('.messages').html('<div class="alert alert-success">Image Uploaded!<div>');
},
error: function (data) {
alerts();
fail();
$('.messages').html('<div class="alert alert-danger">File type not supported! Use files with image extension only!</div>');
},
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
}
and controller:
class ImageController extends Controller
{
use S3;
public function upload(ImgRequest $request)
{
if ($request->hasFile('img')) {
$this->imageEntity();
return response()->json($path);
}
if ($request->hasFile('coverUpload')) {
$this->imageCover();
}
}
public function imageEntity()
{
$s3Path = config('app.path', public_path());
$image = Input::file('img');
Log::info('Retrieving Image', ['image' => $image]);
$filePath = 'public/logo/' . time() . '.' . $image->getClientOriginalExtension();
$path = $s3Path . $filePath;
$this->S3Store($filePath, $image);
$session = session()->get('key');
try {
$update_image = Entity::find($session);
$update_image->logo = $path;
$update_image->save();
Log::info('Succesfully saved logo for', ['entity_id' => $session]);
return response()->json($path);
} catch (Exception $e) {
Log::error('Images:', ['message' =>$e->getMessage(), 'entity_id' => $session]);
}
}
public function imageCover()
{
$s3Path = config('app.path', public_path());
$image = Input::file('coverUpload');
Log::info('Retrieving Cover', ['image' => $image]);
$filePath = 'public/cover/' . time() . '.' . $image->getClientOriginalExtension();
$path = $s3Path . $filePath;
$this->S3Store($filePath, $image);
$session = session()->get('key');
try {
$image = new Images;
$image->path = $path;
$image->cover = true;
$image->entity_id = $session;
$image->save();
Log::info('Succesfully saved logo for', ['entity_id' => $session]);
return $path;
} catch (Exception $e) {
Log::error('Images:', ['message' =>$e->getMessage(), 'entity_id' => $session]);
}
}
Now the funny thing is response is 200, however it is empty ($path is defined) and ajax is triggering error: part of the code and not success. I have checked the log, and try has been successful:
[2017-10-16 11:22:01] local.INFO: Retrieving Image {"image":"[object]
(Illuminate\Http\UploadedFile: /tmp/phpHPchM4)"} [2017-10-16
11:22:01] local.INFO: Adding to S3 [2017-10-16 11:22:05] local.INFO:
Succesfully added to S3 [2017-10-16 11:22:05] local.INFO:
Succesfully saved logo for {"entity_id":"324"}
Could anyone please help me solve this matter?
Update::
I have updated the controller so that the function returns $path, and main function return the response, however for some reason it is saying that $path is undefined, how to pass data from return to controller that is returned it?
I am trying to get a Twitter access token from their oauth api. The plugin I am using is this https://code.google.com/p/oauth/source/browse/#svn%2Fcode%2Fjavascript. So far I only get "401 failed to validate signature and token".
Strange thing is that my ajax call becomes 'GET' request even though I set type:'POST'. Seems like jquery is changing the type from POST to GET. I don't know why it does that. I am running it on my Mac. I appreciate your help/hints/suggestions/advises. Thanks!
$(function() {
function myCallback(resp) {
console.log(resp);
}
var TwitterAPI;
TwitterAPI = (function() {
var consumer_key = null;
var consumer_secret = null;
function TwitterAPI(cons_key, cons_secret) {
this.consumer_key = cons_key;
this.consumer_secret = cons_secret;
}
TwitterAPI.prototype._url = function (data) {
if (typeof data == 'array') {
return array_map([ // TODO
this, '_url'], data);
} else if ((/boolean|number|string/).test(typeof data)) {
return encodeURIComponent(data).replace(/!/g, '%21').replace(/'/g, '%27').replace(/\(/g, '%28').replace(/\)/g, '%29').replace(/\*/g, '%2A');
} else {
return '';
}
}
TwitterAPI.prototype.myCallback = function(resp) {
console.log(resp);
}
TwitterAPI.prototype.getRequestToken = function() {
var accessor = {
consumerSecret: this.consumer_secret, //this.consumer.consumerSecret,
tokenSecret: ''
};
var message = {
method: "POST",
action: "https://api.twitter.com/oauth/request_token",
parameters: {
oauth_signature_method: "HMAC-SHA1",
oauth_consumer_key: this.consumer_key, //this.consumer.consumerKey
oauth_callback: this._url("http://127.0.0.1/foobar/libs/oauth/wtf.html"),
}
};
OAuth.setTimestampAndNonce(message);
OAuth.SignatureMethod.sign(message, accessor);
var target = OAuth.addToURL(message.action, message.parameters);
message.parameters.oauth_signature = this._url(message.parameters.oauth_signature);
console.log(message.parameters);
$.ajax("https://api.twitter.com/oauth/request_token",
{ url: "https://api.twitter.com/oauth/request_token",
type: 'POST',
dataType: 'jsonp',
jsonp: 'callback',
jsonpCallback: "myCallback",
data: message.parameters,
success: function(data, textResp, xhr) {
console.log(data);
},
error: function(xhr, text, err) {
console.log(text);
}
});
};
return TwitterAPI;
})();
api = new TwitterAPI(key, secret);
$('button#request').on('click', function(e) {
e.stopPropagation();
api.getRequestToken();
});