Video Upload on Imgur PHP - php

I'm currently working on an Imgur API which should upload images, gifs and videos; images and gifs are being uploaded without any problems and are working fine.
My Problem is the video part, I always get an error similar to this:
{"data":{"error":"No image data was sent to the upload
api","request":"\/3\/upload","method":"POST"},"success":false,"status":400}
or this:
Notice: Undefined index: link in C:\xampp\htdocs\localfile\php\upvideo.php on line 50 There's a Problem No image data was sent to the upload api
or I get an timeout response.
Since the API docs told me that I need to post it as a Binaryfile I tried using fopen(), fread(), file_get_contents() and countless more. Sadly none of them seem to give curl the string it wants if I use a video; it works just fine with images and gifs (which are now being sent as binary - before I used base64encode before passing it to curl).
I do know that there are 2 tags video and image which I change based on what I'm trying to send at the moment, but video always seems to give me the errors above.
Here is my code:
<?php
// the posted stuff from my form
$title = htmlspecialchars($_POST["title"]);
$posted = htmlspecialchars($_POST["token"]);
$desc = htmlspecialchars($_POST["desc"]);
// data from the file i put into the form
$fileName = $_FILES["imglink"]["name"];
$fileTmpName = $_FILES["imglink"]["tmp_name"];
$size = $_FILES["imglink"]["size"];
// checks if everything is set and ready
if ($title != "" && $desc != "" && is_string($posted)) {
if($fileName == ''){
header("location: ../sub-pages/error.php?noimage");
}else{
/*$data = file_get_contents($fileTmpName);*/
/*var_dump($data);*/
// take the file temporary name and make it something binary..
$handle = fopen($fileTmpName, "rb");
$data = fread($handle, filesize($fileTmpName));
//the curl function
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_SSL_VERIFYHOST => 0,
CURLOPT_SSL_VERIFYPEER => 0,
CURLOPT_URL => "https://api.imgur.com/3/upload",
CURLOPT_RETURNTRANSFER => TRUE,
CURLOPT_ENCODING => "",
CURLOPT_POST => 1,
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => false,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
// all the files i need imgur to get e.g the video (i change video to image if i want to post an image), name of the image etc.
CURLOPT_POSTFIELDS => array( 'video' => # $data, "type" => "file", "title" => $title, "description" => $desc, "name" => $fileName),
CURLOPT_HTTPHEADER => array( "Authorization: Bearer ". $posted),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
$pms = json_decode($response, true);
$url = $pms['data']['link'];
if ($url!="") {
echo "Posted";
header("location: ../sub-pages/succes.php?link=". $url);
} else {
echo "<h2>There's a Problem</h2>";
echo $pms['data']['error'];
}
}
}
else{
echo "no";
}?>
All answers to topic this seem to be outdated or not fixing this.

Related

Add an image to Drupal 7 using CURL

I'm migrating data from Zoho creator into Drupal 7. I wrote a PHP script to get all records and save them into nodes and that worked fine, but I need help to get the images and add them to the nodes as well. This is the code I have to get the image using CURL:
curl_setopt_array($curl, array(
CURLOPT_URL => $url.$id."/Image1/download",
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => array("Authorization: Zoho-oauthtoken $token")
));
$image = curl_exec($curl);
What should I do after that?
You just need to save as file your data using file_save_data()
$image = curl_exec($curl);
// save as file in Drupal
$file = file_save_data($image);
var_dump($file->fid);
Then, to use as image you could use image_style_url() :
$imgfile = file_load($fid);
$url = image_style_url("thumb", $imgfile->uri);

Inconsistent Curl response from localhost to live site

Hi everyone I have a php file which returns a JSON which I constructed from a response from curl. My Problem is when I run it in locally(localhost) server the JSON response its length is 55 which is correct, it got all the events I needed. But when I tried it on our hosting site, the response is inconsistent, it is different from the localhost. For the first load I checked the length response and it returns 32 events out of 55, then I tried to reload it again then the response increased to 39 etc..
This is my localhost response. [https://prnt.sc/rll4w0]. This the file hosted on cpanel https://cdev.trilogycap.co/icedev/dynamic/civicore.php .This is the first response https://prnt.sc/rll2rc .And when I reload this page again https://prnt.sc/rll3fl
My php file function process is like this.
I have a function which gets all the ID's of the event of this year and push it to the global array. I have removed the duplicate ID's there. So now I call a function for multicurl.
In which, for each ID I will process and call the API again and construct it. I then pushed it to my responseEvents variable array in global which then I encode to be able to make a valid JSON file. Is there a connection or wrong thing I did in my multi curl? Is their an execution limit to php multi curl? Or is the settimelimit(0) affect my code?
Here's my code
<?php
//Use this so that when we run the curl it wont timeout when dealing with getting data
set_time_limit(0);
$API_KEY = "APIKEY";
$CURRENT_YEAR = date("Y");
$CURRENT_MONTH = date("m");
$CURRENT_DAY = date("d");
$events = getOpportunityYearly();//array of ID's removed duplicates [1,1,2,3,4,5 etc]
$noDuplicate = array_values(array_unique($events));//remove $event ID duplciates
$responseEvents = [];//this is the array to be returned as json to use
//pass noDuplicate array which holds event ID's
multiCurl($noDuplicate);
print_r(json_encode($responseEvents, JSON_HEX_QUOT | JSON_HEX_TAG | JSON_HEX_AMP |JSON_UNESCAPED_SLASHES ));
//returns an array of ID of events
function getOpportunityYearly(){
$eventArr = [];//pass eventsID here
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => 'https://api.com/voc/api/v3/data/opportunities_dates?key='.$GLOBALS['API_KEY'].'&fields=["startDate","endDate","opportunities_id"]&where={"whereType":"AND","clauses":[{"fieldName":"startDate","operator":">=","operand":"'.$GLOBALS['CURRENT_YEAR'].'-'.$GLOBALS['CURRENT_MONTH'].'-'.$GLOBALS['CURRENT_DAY'].'"},{"fieldName":"endDate","operator":"<=","operand":"'.$GLOBALS['CURRENT_YEAR'].'-12-31"}]}',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET",
));
//convert response to obj
$response = json_decode(curl_exec($curl));
curl_close($curl);
$eventsID = $response->records;
//print_r($eventsID);
//every opportunity object get its id and push to events array
foreach($eventsID as $opportunity){
array_push($eventArr,$opportunity->opportunities_id->value);
}
return $eventArr;
}
function multiCurl($eventArray){
// array of curl handles
$multiCurl = array();
// data to be returned
$result = array();
// multi handle
$mh = curl_multi_init();
$index = null;
foreach ($eventArray as $event) {
//$event are the ID per each event
$multiCurl[$event] = curl_init();
curl_setopt_array($multiCurl[$event], array(
CURLOPT_URL =>'https://api.com/voc/api/v3/data/opportunities/'.$event.'?key='.$GLOBALS['API_KEY'].'&fields=["opportunityName","typeOfWork","firstDateInOpportunity","lastDateInOpportunity","startTime","endTime","physicalDifficulty","minimumAge","location","state","city","county","campingAvailable","groupsAllowed","registrationFormID","cRQ_payment","paymentAmount","additionalInformation","photo","displayToPublic","latitude","longitude","summary","description","photo"]&where={"whereType":"AND","clauses":[{"fieldName":"displayToPublic","operator":"checked"}]}',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET"
));
curl_multi_add_handle($mh, $multiCurl[$event]);
}
do {
curl_multi_exec($mh,$index);
} while($index > 0);
// get content and remove handles
foreach($multiCurl as $key=>$value) {
$records = json_decode(curl_multi_getcontent($value));//response of each request
$record = $records->records[0];
if(strtolower($record->displayToPublic->displayValue) == 'yes'){
$eve = [
"page_item_url"=> $record->opportunities_id->value,
"data"=>[
"typeOfWork"=>$record->typeOfWork->displayValue,
"opportunityName"=> $record->opportunityName->displayValue,
"firstDateInOpportunity"=> $record->firstDateInOpportunity->displayValue,
"lastDateInOpportunity"=> property_exists($record, 'lastDateInOpportunity') ? $record->lastDateInOpportunity->displayValue : $record->firstDateInOpportunity->displayValue,
"startTime"=>$record->startTime->displayValue,
"endTime"=>$record->endTime->displayValue,
"physicalDifficulty"=>$record->physicalDifficulty->displayValue,
"minimumAge"=>$record->minimumAge->displayValue,
"location"=>$record->location->displayValue,
"state"=>$record->state->displayValue,
"city"=>$record->city->displayValue,
"county"=>$record->county->displayValue,
"campingAvailable"=>$record->campingAvailable->displayValue,
"groupsAllowed"=>$record->groupsAllowed->displayValue,
"registrationFormID"=>$record->registrationFormID->displayValue,
"cRQ_payment"=>$record->cRQ_payment->displayValue,
"paymentAmount"=>$record->paymentAmount->displayValue,
"photo"=>$record->photo->displayValue,
"displayToPublic"=>$record->displayToPublic->displayValue,
"latitude"=> property_exists($record, 'latitude') ? $record->latitude->displayValue : "0",
"longitude"=> property_exists($record, 'longitude') ? $record->longitude->displayValue : "0",
"photo"=>$record->photo->displayValue,
"description"=> $record->description->displayValue,
"additionalInformation"=> $record->additionalInformation->displayValue,
"summary"=> $record->summary->displayValue
]
];
array_push($GLOBALS["responseEvents"],$eve);
curl_multi_remove_handle($mh, $value);
}
}//foreach
curl_multi_close($mh);
}
?>
I think somehow your curl did not retreive all of the information when entering this foreach foreach($multiCurl as $key=>$value)
That can explain why it is ok on local (fast response) and not on your distant server (network time, longer response time).
You should try this, which I get from documentation and should wait for all connections to properly end.
do {
$status = curl_multi_exec($mh, $index);
if ($index) {
// Wait a short time for more activity
curl_multi_select($mh);
}
} while ($index && $status == CURLM_OK);

Problem getting post data in API via php curl call

I am trying to send a file to a slim API via curl PHP.
Actually I have a PHP file that receive a from post data and is suppose to call a slim API with the received data and slim API is going to store the data in the database. It works fine when there is no file in the data but when I send a file to API along with other data using PHP curl and set the 'content-type: multipart/form-data' I miss all the posted data in API side. I couldn't figure out what's wrong with it!!!
By the way it works well when I test the API with postman. The API successfully gets the file and save it in the storage. The problem must be in the client side where I call the API using curl and PHP.
Could anybody please help me how to setup the curl call to to make the API work ?
Thanks a lot
route.php
$app->post('/softwareskills/insert', SoftwareSkillsController::class . ':insert')->setName('SoftwareSkills.insert');
SoftwareSkillsController.php
class SoftwareSkillsController {
public function insert(Request $request, Response $response, array $args)
{
$params= $request->getParsedBody();
$file = $request->getUploadedFiles();
var_dump($params); // return empty array!
var_dump($file); // return empty array!
}
}
upload.php
<?php
// $_POST and $_FILES to send them via php CURL
$tmpfile = $_FILES['attachment']['tmp_name'];
$filename = basename($_FILES['attachment']['name']);
$filemime = $_FILES['attachment']['type'];
$data = array(
"StNo" => $_POST['StNo'],
"SoftwareName" => $_POST['SoftwareName'],
"proficiency" => $_POST['proficiency'],
"attachment" => new CURLFile($tmpfile,$filemime,$filename)
);
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "http://myapi.com/softwareskills/insert",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => http_build_query($data),
CURLOPT_HTTPHEADER => array(
"content-type: multipart/form-data"
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}

how to upload mp3 file and get its duration in laravel 4.2

I'd like to upload a MP3 file in Laravel and then get the duration of the MP3. Here's my code, but it's not working:
$music_file = Input::file('audio_path');
$file_music = date('Y-m-d-H-i-s')."-".$music_file->getClientOriginalName();
$path = public_path('assets/music/' . $file_music);
$path = $music_file->getRealPath();
for moving MP3
$music_file = Input::file('audio_path');
$file_music = date('Y-m-d-H-i-s')."-".$music_file->getClientOriginalName();
$path = public_path('assets/music/' . $file_music);
$music_file->move($path,$file_music);
After observing many doubts on this subject I will leave here a step by step with the solution I found for this problem.
For this we will use the getid3 package, a media file parser.
This solution was tested on Laravel 6.x, but it is compatible with several versions of Laravel.
1 - To install it on Laravel using the Composer, at the root of the project using the console type:
$ composer require james-heinrich/getid3
In this example we will create an endpoint to send an .mp3 file and return its duration.
2 - Create a Route to send the file:
Route::post('media', 'FilesController#media');
3 - Create a Controller to get the file and return the duration:
class FilesController extends Controller
{
public function media(Request $request)
{
$file = $request->file('upload');
if(!empty($request->file('upload'))) {
$getID3 = new \getID3;
$ThisFileInfo = $getID3->analyze($file);
$len= #$ThisFileInfo['playtime_string']; // playtime in minutes:seconds, formatted string
return $len;
}
}
4 - Sending the file:
Test using POSTMAN (good to check if everything in Laravel is OK):
Note: the upload field in POSTMAN is of type FILE.
Using Curl / PHP
<?php
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://localhost/api/media",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => array('upload'=> new CURLFILE('/home/fellipe/Desktop/android-timeless.mp3')),
CURLOPT_HTTPHEADER => array(
"Content-Type: application/x-www-form-urlencoded",
"Accept: application/json"
),
));
$response = curl_exec($curl);
curl_close($curl);
echo $response;

Implementing Sketchfab API

I am trying to implement sketchfab api in my website. I got the code and access token from their website , I implemented everything but when I execute the code, I get a blank screen. What is the problem?
The first problem was with curl, I enabled it by going to php.ini file but then this blank screen problem.
<?php
$url = "https://api.sketchfab.com/v1/models";
$path = "./";
$filename = "m.3DS";
$description = "Test of the api with a simple model";
$token_api = "THE ACCESS TOKEN";
$title = "Uber Glasses";
$tags = "test collada glasses";
$private = 1;
$password = "Tr0b4dor&3";
$data = array(
"title" => $title,
"description" => $description,
"fileModel" => "#".$path.$filename,
"filenameModel" => $filename,
"tags" => $tags,
"token" => $token_api,
"private" => $private,
"password" => $password
);
$ch = curl_init();
curl_setopt_array($ch, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => $url,
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => $data
));
$response = curl_exec($ch);
curl_close($ch);
echo $response; // I am trying to echo the response here
?>
The call to the upload api will return a json that contains the id of the model. You can use this id to generate an url and make another call to the oEmbed api. pseudo code example:
// your curl setup
$response = curl_exec($ch);
// Response
{success: true, {result: {id: 'xxxxxx'} } when upload OK
{success: false, error: 'error message'} when upload error
$id = $response['result']['id'];
$call= "https://sketchfab.com/oembed?url=https://sketchfab.com/show/" . $id;
// do another curl call with $call content
// it will return a response like below but with your model information
// Response
{
provider_url: "http://sketchfab.com",
provider_name: "Sketchfab",
thumbnail_url: "https://sketchfab.com/urls/dGUrytaktlDeNudCEGKk31oTJY/thumbnail_448.png?v=24a1cb0590851ccfeeae01a2ca1eece1",
thumbnail_width: "448",
thumbnail_height: "280",
author_name: "Klaas Nienhuis",
author_url: "https://sketchfab.com/klaasnienhuis",
title: "Maison d'artiste",
html: "<iframe frameborder="0" width="640" height="320" webkitallowfullscreen="true" mozallowfullscreen="true" src="http://sketchfab.com/embed/dGUrytaktlDeNudCEGKk31oTJY?autostart=0&transparent=0&autospin=0&controls=1&watermark=0"></iframe>",
width: 640,
height: 320,
version: "1.0",
type: "rich"
}
If you have an issue with this try in the command line to print the result of call.

Categories