Dailymotion API - Can't get to a video to upload - php

I can't manage to get a file to upload the DailyMotion API.
I'm following these steps : https://developer.dailymotion.com/video-upload/upload-new-video-api/
The first API call runs fine and returns me the "upload_url" that I feed into the method you'll see below.
It fails on the 2nd step and the response error is :
{"error":"missing content size","seal": "[some string]"}
How am I supposed to set the content size ?
the code for the 2nd call :
<?php
namespace PierreMiniggio\YoutubeChannelCloner\Dailymotion\API;
class DailymotionFileUploader
{
public function upload(string $uploadUrl, string $filePath): ?string
{
$formattedFile = function_exists('curl_file_create')
? curl_file_create(str_replace('\\', '/', $filePath))
: sprintf("#%s", $filePath)
;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $uploadUrl);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt(
$ch,
CURLOPT_POSTFIELDS,
['file' => $formattedFile]
);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
//var_dump($response); die(); // the output I printed above
curl_close($ch);
if (empty($response)) {
return null;
}
$jsonResponse = json_decode($response, true);
if (empty($jsonResponse) || ! isset($jsonResponse['url'])) {
return null;
}
return $jsonResponse['url'];
}
}
OS : W10
I made sure the file path and the upload URL are correct.
I tried using the dailymotion/sdk lib and use the function that uploads a file instead of using my curl requests, but I get the exact same error.

Problem Solved, It was issue with curl/PHP.
I was running the script in PHP 7.4.3-dev, updated to 7.4.11 and it solved the issue.
More Info about the bug here : https://bugs.php.net/bug.php?id=79013

Related

Github api request with php curl

I am trying to get the latest commit from github using the api, but I encounter some errors and not sure what the problem is with the curl requests. The CURLINFO_HTTP_CODE gives me 000.
What does it mean if I got 000 and why is it not getting the contents of the url?
function get_json($url){
$base = "https://api.github.com";
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $base . $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
//curl_setopt($curl, CONNECTTIMEOUT, 1);
$content = curl_exec($curl);
echo $http_status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
curl_close($curl);
return $content;
}
echo get_json("users/$user/repos");
function get_latest_repo($user) {
// Get the json from github for the repos
$json = json_decode(get_json("users/$user/repos"),true);
print_r($json);
// Sort the array returend by pushed_at time
function compare_pushed_at($b, $a){
return strnatcmp($a['pushed_at'], $b['pushed_at']);
}
usort($json, 'compare_pushed_at');
//Now just get the latest repo
$json = $json[0];
return $json;
}
function get_commits($repo, $user){
// Get the name of the repo that we'll use in the request url
$repoName = $repo["name"];
return json_decode(get_json("repos/$user/$repoName/commits"),true);
}
I use your code and it will work if you add an user agent on curl
curl_setopt($ch, CURLOPT_USERAGENT,'YOUR_INVENTED_APP_NAME');

How can I have a public function to run all my PHP cURL requests?

I have a basic RESTful API setup using cURL for all my requests.
At the moment, I am attempting to split out all my functions to have one function that runs all my requests.
For example, I have the following which can be called from localhost/api/getUserData
private function getUserData() {
$url = 'localhost/api/users/';
runApiCall($url);
}
That function then goes on to pass the URL to runApiCall(), which is the following:
function runApiCall($url) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_COOKIE, 'PHPSESSID=' . $_COOKIE['PHPSESSID']);
$result = curl_exec($ch);
curl_close($ch);
$this->response($result, 200);
}
Although, I keep getting an error in my console of http://localhost/api/getUserData 500 (Internal Server Error)
The API was working perfectly fine before I split it out.
EDIT:
If I simply change my getUserData() function to the following, it works perfectly fine:
private function getUserData() {
$url = 'localhost/api/users/';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, false);
curl_setopt($ch, CURLOPT_COOKIE, 'PHPSESSID=' . $_COOKIE['PHPSESSID']);
$result = curl_exec($ch);
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
$this->response($this->json($result), $status);
}
You have an issue with scope as you are inside a class.
private function getUserData() {
$url = 'localhost/api/users/';
$this->runApiCall($url); // call $this object's runAppCall() function
}
If you had error handling enabled, you'd see an error thrown by PHP telling you that it could not find the method runApiCall(). This is because you are inside a class and must explicitly tell PHP to run the method on the class.
You can do this by:
private function getUserData() {
$url = 'localhost/api/users/';
// EITHER
$this->runApiCall($url);
// OR
self::runApiCall($url);
}
In future, I'd recommend adding this line at the route of your application when you are developing, then set it to false in production:
ini_set('display_errors', 1);
This will now log any PHP errors to the browser, making it much easier for you to debug.

Uploading files to Zoho API with PHP Curl

I am trying to attach a file to a Zoho CRM Account page using the ZohoCRM API and not having any success. I am using Curl and PHP5.3 (no curl_file_create, so using hand rolled version).
In my log I get the following report
Curl::post
Url: https://crm.zoho.com/crm/private/json/Accounts/uploadFile?authtoken=MY_TOKEN&scope=crmapi
Params: Array(
[content] => #/tmp/b2d-JbJvMY;filename=b2d-JbJvMY;type=application/pdf
[id] => MY_ACCOUNT_ID
)
I get no response from ZohoCRM and the file is definitely not attached to the target Account record. What am I doing wrong?
Here's some excerpts from my code that may help or hinder: ... other methods from my ZohoAPI class such as getSearchRecords appear to be working fine...
class Curl {
...
protected static function post($url, $params) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER,0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
...
}
class ZohoAPI extends Curl {
....
protected function apiPost($url, $params) {
$url .= "?authtoken={$this->token}&scope={$this->scope}";
$apiParams = empty($params) ? '' : $params;
return $this->post($url, $apiParams);
}
...
public function uploadFile($module='Accounts', $zohoId = '', $file ) {
$url = "{$this->apiUrl}/{$this->mode}/{$module}/uploadFile";
$params = array(
'content' => curl_file_create($file, 'application/pdf' , basename( $file, '.pdf')),
'id' => $zohoId
);
return $this->apiPost($url, $params);
}
...
}
When trying to upload a file, check you have permission to do so :-(
Turns out the file I was trying to upload could not be read by the process.

Alternative for HTTPRequest in php

I am using the HttpRequest class in my php script, but when I uploaded this script to my hosting provider's server, I get a fatal error when executing it:
Fatal error: Class 'HttpRequest' not found in ... on line 87
I believe the reason is because my hosting provider's php.ini configuration doesnt include the extension that supports HttpRequest. When i contacted them they said that we cannot install the following extentions on shared hosting.
So i want the alternative for httpRequest which i make like this:
$url= http://ip:8080/folder/SuspendSubscriber?subscriberId=5
$data_string="";
$request = new HTTPRequest($url, HTTP_METH_POST);
$request->setRawPostData($data_string);
$request->send();
$response = $request->getResponseBody();
$response= json_decode($response, true);
return $response;
Or How can i use this request in curl as it is not working for empty datastring?
You can use CURL in php like this:
$ch = curl_init( $url );
$data_string = " ";
curl_setopt( $ch, CURLOPT_POSTFIELDS, $data_string );
curl_setopt( $ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
$result = curl_exec($ch);
curl_close($ch);
return $result;
and empty data string doesn't make sense in post request, but i've checked it with empty data string and it works quiet well.
you can use a framework like zend do this. framework usually have multiple adapters (curl,socket,proxy).
here is a sample with ZF2:
$request = new \Zend\Http\Request();
$request->setUri('[url]');
$request->setMethod(\Zend\Http\Request::METHOD_POST);
$request->getPost()->set('key', $value);
$client = new \Zend\Http\Client();
$client->setEncType('application/x-www-form-urlencoded');
$response = false;
try {
/* #var $response \Zend\Http\Response */
$response = $client->dispatch($request);
} catch (Exception $e) {
//handle error
}
if ($response && $response->isSuccess()) {
$result = $response->getBody();
} else {
$error = $response->getBody();
}
you don't have to use the entire framework just include (or autoload) the classes that you need.
Use the cURL in php
<?php
// A very simple PHP example that sends a HTTP POST to a remote site
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,"http://example.com/feed.rss");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,"postvar1=value1&postvar2=value2");
// in real life you should use something like:
// curl_setopt($ch, CURLOPT_POSTFIELDS,
// http_build_query(array('postvar1' => 'value1')));
// receive server response ...
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$server_output = curl_exec ($ch);
curl_close ($ch);
// further processing ....
if ($server_output == "OK") { ... } else { ... }
?>
for more see this PHP Difference between Curl and HttpRequest
a slight variaton on the curl methods proposed, i decode the json that is returned, like in this snippet

Uploading files using PHP

I have set up an HTML form to select a file and submit it to a PHP script which will upload it. I cannot use move_uploaded_files() because Box's API requires that I add a HTTP Header for Authorization: access_token. What I've done is set up my own POST method using the cURL library.
The problem I'm running into is setting the filename correctly, as it requires the full path of the file. I cannot get the full path of the file from the HTML form and using $_FILES['filename']['tmp_name'] uploads a .tmp file which I do not want. Does anyone know the solution to this problem? Thanks a lot!
My code:
public function upload_file($file) {
$url = 'https://api.box.com/2.0/files/content';
$params = [
'filename' => '#'.$file['tmp_name'],
'folder_id' => '0'
];
$header = "Authorization: Bearer ".$this->access_token;
$data = $this->post($url, $params, $header);
}
public function post($url, $params, $header='') {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
if(!empty($header)) {
curl_setopt($ch, CURLOPT_HTTPHEADER, array($header));
}
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
Suggest you do one of the following:
Use move_uploaded_files to upload file into some directory and use that location to send the file to box using curl. After successful upload you can delete the file from this directory.
Instead of uploading the file through PHP, you can upload them client side using the cors http://developers.blog.box.com/2013/05/13/uploading-files-with-cors/
Another question which I have in my mind is how are you keeping your access_token refreshed?
Vishal
I agree with what Vishal has suggested in point number one.
I have written the PHP SDK for v2
Just include the api class and initiate the class:
<?php
include('library/BoxAPI.class.php');
$client_id = 'CLIENT ID';
$client_secret = 'CLIENT SECRET';
$redirect_uri = 'REDIRECT URL';
$box = new Box_API($client_id, $client_secret, $redirect_uri);
if(!$box->load_token()){
if(isset($_GET['code'])){
$token = $box->get_token($_GET['code'], true);
if($box->write_token($token, 'file')){
$box->load_token();
}
} else {
$box->get_code();
}
}
// Upload file
$box->put_file('RELATIVE FILE URL', '0'));
?>
Have a look here
Download: BoxPHPAPI

Categories