Upload video on fanpage via PHP API - php

I have a little problem with my FB application. It's about that I always get error:
{"error":{"message":"(#353) Missing video file","type":"OAuthException","code":353}}
with this code:
$post_url = "https://graph-video.facebook.com/xxx/videos?"
. "title=" . $video_title . "&description=" . $video_desc
. "&access_token=" . $access_token;
$ch = curl_init();
$data = array(
'source' => 'http://x/upload/' . $name . '.' . $type,
'file' => './upload/' . $name . '.' . $type,
'type' => 'avi',
);
curl_setopt($ch, CURLOPT_URL, $post_url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$response = curl_exec($ch);
if (!$response)
{
print_r(Debug::vars(array(curl_error($ch), curl_errno($ch))));
}
curl_close($ch);
File exist, access_token is valid and is logged as a app, In $data I've tried set only 'file' or 'source' but effects was the same.

You are best off using the Facebook PHP SDK for this, but it might be as simple as removing your file param and adding "#" to your source path. Here is a working example with the SDK (assuming you have asked for the appropriate FB permissions):
$this->facebook->setFileUploadSupport(true);
$upload = $this->facebook->api('/me/videos', 'POST', array(
'source' => '#'.$file,
'title' => $title,
'description' => $description
));

Related

PHP-Oauth authentication with Grant CodeFlow

I implement OAUTH authentication. I'm sending a POST request to an API. But something is wrong in my code. I get error 404 back. can someone help me. this API does not support ClientSecret.
this is my Code
<?php
$callback_uri = "http://localhost/zeiterfassung/" ;
$client_id = "2371031349-3075189699-483870032-1896673008" ;
$code = $_GET['code'];
$resourc = "http://localhost/zeiterfassung/";
if (isset($_GET['code'])) {
// try to get an access token
$code = $_GET['code'];
$url = 'https://adfs3int.fds.metro.info/oauth2/token';
$params = array(
"code" => $code,
"client_id" => $client_id,
"redirect_uri" => 'http://' . $_SERVER["HTTP_HOST"] . $_SERVER["PHP_SELF"],
"grant_type" => "authorization_code"
);
$ch = curl_init();
curl_setopt($ch, constant("CURLOPT_" . 'URL'), $url);
curl_setopt($ch, constant("CURLOPT_" . 'POST'), true);
curl_setopt($ch, constant("CURLOPT_" . 'POSTFIELDS'), $params);
$output = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);
if ($info['http_code'] === 200) {
header('Content-Type: ' . $info['content_type']);
return $output;
} else {
return 'An error happened';
}
} else {
$url = "https://adfs3int.fds.metro.info/adfs/oauth2/authorize";
$params = array(
"response_type" => "code",
"client_id" => $client_id,
"redirect_uri" => $callback_uri,
"resource" => $resourc
);
$request_to = $url . '?' . http_build_query($params);
header("Location: " . $request_to);
}
?>
404 is a client site error and say's that you have done something wrong - it means that what you are looking for is not there where are you looking.
It's like, you searching socks in you closet but you cant find the socks cause your socks aren't in the closet.
I looks like the requesting api is hosted on your localhost, maybe the api is in an ohter folder?

PHP Upload PDF to Google Drive API

I have website created in PHP. Basically it is a send document kind of project. It uses a document store in Azure I will call and send it into Azure. Now I want to send in email as well as store in Google drive.
So it should be stored to drive with public access. I have create following code. It works properly I don't want any input from user.
$client->setAccessToken($_SESSION['accessToken']);
$service = new Google_DriveService($client);
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$file = new Google_DriveFile();
foreach ($files as $file_name) {
$file_path = 'files/'.$file_name;
$mime_type = finfo_file($finfo, $file_path);
$file->setTitle($file_name);
$file->setDescription('This is a '.$mime_type.' document');
$file->setMimeType($mime_type);
$service->files->insert(
$file,
array(
'data' => file_get_contents($file_path),
'mimeType' => $mime_type
)
);
}
finfo_close($finfo);
I want upload from Azure URL using cURL or using API. When mail send it is automatically uploaded to drive at the same time.
Question Update
I have function to send a mail this is work perfectly. I would like to store an attachment to google drive and retrieve path store that path in to database.
This all work will be based on API no user interaction required. That file is PDF in formate and not specific bytes its different as per data of file.
Issue :
When I upload a file to Drive original file name is rename to untitled. Here is code.
function uploadFile($credentials, $filename, $targetPath)
{
global $GAPIS;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $GAPIS . 'upload/drive/v2/files?uploadType=media');
curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
//curl_setopt($ch, CURLOPT_POSTFIELDS, array("title" =>"newfile.txt"));
curl_setopt($ch, CURLOPT_POSTFIELDS, file_get_contents($filename));
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER,
array('Content-Type : text/plain', 'Content-Length:' . filesize($filename),
'Authorization: Bearer ' . getAccessToken($credentials))
);
$postResult = curl_exec($ch);
curl_close($ch);
return json_decode($postResult, true);
}
==========================================
Updated code (Issue with Added code but still getting issue with Untitle.pdf in drive)
==========================================
<?php
$GAPIS = 'https://www.googleapis.com/';
$GAPIS_AUTH = $GAPIS . 'auth/';
$GOAUTH = 'https://accounts.google.com/o/oauth2/';
$CLIENT_ID = '709846732498-xxxxxxxx';
$CLIENT_SECRET = 'XXXXXXXXXXXXXX';
$REDIRECT_URI = 'http' . ($_SERVER['SERVER_PORT'] == 80 ? '' : 's') . '://' . $_SERVER['SERVER_NAME'] . $_SERVER['SCRIPT_NAME'];
$SCOPES = array($GAPIS_AUTH . 'drive', $GAPIS_AUTH . 'drive.file', $GAPIS_AUTH . 'userinfo.email', $GAPIS_AUTH . 'userinfo.profile');
$STORE_PATH = 'credentials.json';
function uploadFile($credentials, $filename, $targetPath)
{
global $GAPIS;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $GAPIS . 'upload/drive/v2/files?uploadType=media');
curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, file_get_contents($filename));
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER,
array('Content-Type : application/pdf', 'Content-Length:' . filesize($filename),
'Authorization: Bearer ' . getAccessToken($credentials))
);
$postResult = curl_exec($ch);
curl_close($ch);
return json_decode($postResult, true);
}
function getStoredCredentials($path)
{
$credentials = json_decode(file_get_contents($path), true);
if (isset($credentials['refresh_token']))
return $credentials;
$expire_date = new DateTime();
$expire_date->setTimestamp($credentials['created']);
$expire_date->add(new DateInterval('PT' . $credentials['expires_in'] . 'S'));
$current_time = new DateTime();
if ($current_time->getTimestamp() >= $expire_date->getTimestamp())
{
$credentials = null;
unlink($path);
}
return $credentials;
}
function storeCredentials($path, $credentials)
{
$credentials['created'] = (new DateTime())->getTimestamp();
file_put_contents($path, json_encode($credentials));
return $credentials;
}
function requestAuthCode()
{
global $GOAUTH, $CLIENT_ID, $REDIRECT_URI, $SCOPES;
$url = sprintf($GOAUTH . 'auth?scope=%s&redirect_uri=%s&response_type=code&client_id=%s&approval_prompt=force&access_type=offline',
urlencode(implode(' ', $SCOPES)), urlencode($REDIRECT_URI), urlencode($CLIENT_ID)
);
header('Location:' . $url);
}
function requestAccessToken($access_code)
{
global $GOAUTH, $CLIENT_ID, $CLIENT_SECRET, $REDIRECT_URI;
$url = $GOAUTH . 'token';
$post_fields = 'code=' . $access_code . '&client_id=' . urlencode($CLIENT_ID) . '&client_secret=' . urlencode($CLIENT_SECRET)
. '&redirect_uri=' . urlencode($REDIRECT_URI) . '&grant_type=authorization_code';
$ch = curl_init();
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_fields);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $url);
$result = curl_exec($ch);
curl_close($ch);
return json_decode($result, true);
}
function getAccessToken($credentials)
{
$expire_date = new DateTime();
$expire_date->setTimestamp($credentials['created']);
$expire_date->add(new DateInterval('PT' . $credentials['expires_in'] . 'S'));
$current_time = new DateTime();
if ($current_time->getTimestamp() >= $expire_date->getTimestamp())
return $credentials['refresh_token'];
else
return $credentials['access_token'];
}
function authenticate()
{
global $STORE_PATH;
if (file_exists($STORE_PATH))
$credentials = getStoredCredentials($STORE_PATH);
else
$credentials = null;
if (!(isset($_GET['code']) || isset($credentials)))
requestAuthCode();
if (!isset($credentials))
$credentials = requestAccessToken($_GET['code']);
if (isset($credentials) && isset($credentials['access_token']) && !file_exists($STORE_PATH))
$credentials = storeCredentials($STORE_PATH, $credentials);
return $credentials;
}
$credentials = authenticate();
$result = uploadFile($credentials, 'example.pdf', '');
if (!isset($result['id']))
throw new Exception(print_r($result));
else
echo 'File copied successfuly (file Id: ' . $result['id'] . ')';
echo '<pre>'; print_r($result);
going by https://developers.google.com/drive/api/v3/simple-upload , this should work:
<?php
$ch = curl_init ();
curl_setopt_array ( $ch, array (
CURLOPT_URL => 'https://www.googleapis.com/upload/drive/v3/files?uploadType=media',
CURLOPT_HTTPHEADER => array (
'Content-Type: application/pdf', // todo: runtime detection?
'Authorization: Bearer [YOUR_AUTH_TOKEN]'
),
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => file_get_contents ( '/path/to/file.pdf' ),
CURLOPT_RETURNTRANSFER => 1
) );
try {
if (false === ($resp = curl_exec ( $ch ))) {
throw new \RuntimeException ( 'curl error ' . curl_errno ( $ch ) . ": " . curl_error ( $ch ) );
}
$parsed = json_decode ( $resp, true );
if (! $parsed || $parsed ['code'] !== 200) {
throw new \RuntimeException ( 'google api error: ' . $resp );
}
} finally{
curl_close ( $ch );
}
var_dump($resp);
I am still not completely sure i understand your question. Assuming you just want to upload a file in php or curl here are two options.
Uploading to Google drive is in two parts the first part you create the meta data that being the file name and basic information about your fine. The second part is where you upload the actual data of your file.
$fileMetadata = new Google_Service_Drive_DriveFile(array(
'name' => 'My Report',
'mimeType' => 'application/vnd.google-apps.spreadsheet'));
$content = file_get_contents('files/report.csv');
$file = $driveService->files->create($fileMetadata, array(
'data' => $content,
'mimeType' => 'text/csv',
'uploadType' => 'multipart',
'fields' => 'id'));
printf("File ID: %s\n", $file->id);
Code ripped from media upload
If you want to do this in curl inserting the meta data shouldnt be an issue your issue will be uploading the file itself. You will need to POST the metadata to create the empty file and capture its file-id. Then use the file-id for a content upload. You can find more information on the requests you will nee dot make here simple upload request.
The code will probably look something like this but again your going to have to pass the file id.
curl
--silent
--request POST
--data-binary "#c:\temp\myfile.jpg"
-OL MyFolder\myfile2.jpeg
-H "Slug: myfile3.jpg"
-H "Authorization: Bearer [your access token here]"
-H "Content-Type: image/jpeg {"fileid":"1234"}"
"https://www.googleapis.com/upload/drive/v3/files?uploadType=media"
Note i have not tested the upload in curl this is just a guess.
You can use Logic Apps to send the file from Azure Blob storage to Google Drive as well as an email attachment.
https://learn.microsoft.com/en-us/azure/connectors/connectors-create-api-azureblobstorage
Alternatively files stored in Azure Blobs can be addresses with a public URL assuming you have the right permissions set on the container and/or blob.

Connecting to OpenId Using cURL Gives Error

I am using the following code to access an OpenId system and request a bearer token.
if (isset($_GET['code'])) {
// try to get an access token
$code = $_GET['code'];
$url = 'https://3rdpartydomain.com/connect/token';
$params = array(
"code" => $code,
"client_id" => CLIENTID,
"client_secret" => CLIENTSECRET,
"redirect_uri" => 'http://' . $_SERVER["HTTP_HOST"] . $_SERVER["PHP_SELF"],
"grant_type" => "authorization_code"
);
$ch = curl_init();
curl_setopt($ch, constant("CURLOPT_" . 'URL'), $url);
curl_setopt($ch, constant("CURLOPT_" . 'POST'), true);
curl_setopt($ch, constant("CURLOPT_" . 'POSTFIELDS'), $params);
$output = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);
if ($info['http_code'] === 200) {
header('Content-Type: ' . $info['content_type']);
return $output;
} else {
return 'An error happened';
}
} else {
$url = "https://3rdpartydomain.com/connect/token";
$params = array(
"response_type" => "code",
"client_id" => CLIENTID,
"redirect_uri" => 'http://' . $_SERVER["HTTP_HOST"] . $_SERVER["PHP_SELF"],
"scope" => "openid"
);
$request_to = $url . '?' . http_build_query($params);
header("Location: " . $request_to);
}
However, I'm getting the following message:
{"Message":"The requested resource does not support http method 'GET'."}
Can someone help identify the correct to my code please?
Thanks!
Add these:
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
There is probably a change of requested method in the redirect from your IdP. I've seen this issue when I was testing my OIDC with curl -XPOST. The workaround was to remove that request type specification. Try to comment your line: curl_setopt($ch, constant("CURLOPT_" . 'POST'), true);

Why is VirusTotal returning this error?

I'm trying to use VirusTotal's public API to scan files. This is my code:
$post_url = 'https://www.virustotal.com/vtapi/v2/file/scan';
$filemime = exec("file -b --mime-type '$file_to_scan'");
$post = array('apikey' => $virustotal_api_key, 'file' => '#' . realpath($file_to_scan) . ';type=' . $filemime . ';filename=' . $name);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$post_url);
curl_setopt($ch, CURLOPT_POST,1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_HTTPHEADER,array('Expect:'));
$api_reply = curl_exec($ch);
curl_close($ch);
$api_reply_array = json_decode($api_reply, true);
Whenever I run this code, I get the following error:
[response_code] => 0
[verbose_msg] => Invalid submission format, the uploaded file must travel as a multipart MIME message, please review the documentation
I've spent multiple hours trying to figure this out, but it just won't work. Can anyone point me in the right directions?
This is the print_r of $post in the above code:
[apikey] => xxx
[file] => #/absolute/path/to/file.exe;type=application/octet-stream;filename=file.exe
Thanks!
Figured it out, after assistance from VirusTotal themselves (kudos, Karl). The problem was how PHP 5.6 changed cURL. If you are on PHP 5.6, you need to add:
curl_setopt($ch, CURLOPT_SAFE_UPLOAD, false);
The line to fix is
$post = array('apikey' => $virustotal_api_key, 'file' => '#' . realpath($file_to_scan) . ';type=' . $filemime . ';filename=' . $name);
This must be changed to:
$cfile = new CURLFile(realpath($file_to_scan),$filemime,$name);
$post = array('apikey' => $virustotal_api_key, 'file' => $cfile);
Then it also works with PHP 7 :)

Parse.com - Upload image using REST API and PHP

I created a PHP-script which is uploading an image, picked up from an HTML-form, to the Parse.com backend.
Actually it looks like the script is working, because I am getting a URL and a name as result.
After the Upload I am associating the uploaded file with an Object.
The result is also looking fine and the image is appearing inside the data browse.
But if I try to get the image in my iOS app or take a look at it inside of the browser (by clicking on it) I only get an access denied alert or a white page (with broken image icon).
iOS Error: Error Domain=Parse Code=150 "The operation couldn’t be completed. (Parse error 150.)
Here you can see my code:
Upload image:
$teamImage = $_FILES["teamImage"];
$APPLICATION_ID = "XXXXXXXXXXXXXXXXXXX";
$REST_API_KEY = "XXXXXXXXXXXXXXXXXXX";
$urlFile = 'https://api.parse.com/1/files/' . $teamImage['name'];
$image = $teamImage['tmp_name'];
$headerFile = array(
'X-Parse-Application-Id: ' . $APPLICATION_ID,
'X-Parse-REST-API-Key: ' . $REST_API_KEY,
'Content-Type: ' . $teamImage['type'],
'Content-Length: ' . strlen($image),
);
$curlFile = curl_init($urlFile);
curl_setopt($curlFile, CURLOPT_POST, 1);
curl_setopt($curlFile, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curlFile, CURLOPT_POSTFIELDS, $image);
curl_setopt($curlFile, CURLOPT_HTTPHEADER, $headerFile);
curl_setopt($curlFile, CURLOPT_SSL_VERIFYPEER, false);
$responseFile = curl_exec($curlFile);
$httpCodeFile = curl_getinfo($curlFile, CURLINFO_HTTP_CODE);
$result = array('code'=>$httpCodeFile, 'response'=>$responseFile);
Associating image to Object (image name for test case hardcoded)
$url = 'https://api.parse.com/1/classes/Teams';
$data = array(
'name' => 'Test',
'teamImage' => array(
'name' => '......jpg',
'__type' => 'File'
),
);
$_data = json_encode($data);
$headers = array(
'X-Parse-Application-Id: ' . $APPLICATION_ID,
'X-Parse-REST-API-Key: ' . $REST_API_KEY,
'Content-Type: application/json',
'Content-Length: ' . strlen($_data),
);
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $_data);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$responseTwo = curl_exec($curl);
$httpCodeTwo = curl_getinfo($curl, CURLINFO_HTTP_CODE);
$resultTwo = array('code'=>$httpCodeTwo, 'response'=>$responseTwo);
Image Url, which I am getting back from Parse: http://files.parse.com/725d8f61-de18-4de5-a84c-dcc6e74c43ae/197e7bb6-62ad-4dc4-a011-6db88333ac45-BMW_1series_3door_Wallpaper_1920x1200_01.jpg
Data Browser Screenshot:
I think you need to specify the url as well
$data = array(
'name' => 'Test',
'teamImage' => array(
'name' => '......jpg',
'__type' => 'File',
'url' => '....jpg'
),
);

Categories