PHP Curl - Wistia API Upload - php

I'm trying to upload a movie to the Wistia API by CURL (http://wistia.com/doc/upload-api).
It works fine using the following command line, but when I put it in PHP code, I just get a blank screen with no response:
$ curl -i -d "api_password=<YOUR_API_PASSWORD>&url=<REMOTE_FILE_PATH>" https://upload.wistia.com/
PHP Code:
<?php
$data = array(
'api_password' => '<password>',
'url' => 'http://www.mysayara.com/IMG_2183.MOV'
);
$chss = curl_init('https://upload.wistia.com');
curl_setopt_array($chss, array(
CURLOPT_POST => TRUE,
CURLOPT_RETURNTRANSFER => TRUE,
CURLOPT_POSTFIELDS => json_encode($data)
));
// Send the request
$KReresponse = curl_exec($chss);
// Decode the response
$KReresponseData = json_decode($KReresponse, TRUE);
echo("Response:");
print_r($KReresponseData);
?>
Thanks.

For PHP v5.5.0 or later, here's a class for uploading to Wistia, from a LOCALLY STORED file.
Usage:
$result = WistiaUploadApi::uploadVideo("/var/www/mysite.com/tmp_videos/video.mp4","video.mp4","abcdefg123","Test Video", "This is a video upload demonstration");
The class:
#param $file_path Full local path to the file
#param $file_name The name of the file (not sure what Wistia does with this)
#param $project The 10 character project identifier the video will upload to
#param $name The name the video will have on Wistia
#param $description The description the video will have on Wistia
class WistiaUploadApi
{
const API_KEY = "<API_KEY_HERE>";
const WISTIA_UPLOAD_URL = "https://upload.wistia.com";
public static function uploadVideo($file_path, $file_name, $project, $name, $description='')
{
$url = self::WISTIA_UPLOAD_URL;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
$params = array
(
'project_id' => $project,
'name' => $name,
'description' => $description,
'api_password' => self:: API_KEY,
'file' => new CurlFile($file_path, 'video/mp4', $file_name)
);
curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
//JSON result
$result = curl_exec($ch);
//Object result
return json_decode($result);
}
}
If you don't have a project to upload into, leaving $project blank will NOT apparently force Wistia to create one. It will just fail. So you might have to remove this from the $params array if you don't have a project to upload to. I've not experimented to see what happens when you leave $name blank.

Your problem (and the difference between the command line and PHP implementation) is probably that you're JSON encoding the data in PHP, you should use http_build_query() instead:
CURLOPT_POSTFIELDS => http_build_query($data)
For clarity, the Wistia API says it returns JSON, but doesn't expect it in the request.

Related

CURL Warning: curl_file_create() expects parameter 1 to be a valid path, string given

I don't know why this is not working. I am trying to download a image from a URL then sent it via CURL. POST request the path with var_dump is working, but with CURL it doesn't work
The error is
Warning: curl_file_create() expects parameter 1 to be a valid path, string given
// define('TMP', __DIR__ . DIRECTORY_SEPARATOR . 'tmp');
/**
* #param $url
* #return string
*/
function dlImage($url) {
$save_dir = TMP . DIRECTORY_SEPARATOR;
$filename = basename($url);
$save = $save_dir.$filename;
file_put_contents($save,file_get_contents($url));
return $save;
}
function upload( $body, $title, $type, $type_real, $subCat, $poster = null, $imdbUrl = null)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'xxxx');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 0);
curl_setopt($ch, CURLOPT_POST, 1);
$data = [
'key' => 'xxxx',
'type' => $type,
'subtype' => $subCat,
'type_real' => $type_real,
'title' => $title,
'posterUpload' => curl_file_create(realpath(dlImage($poster)),'image/jpeg'),
'imdbUrl' => $imdbUrl,
];
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$result = curl_exec($ch);
curl_close($ch);
var_dump($result);
}
// path is working fine
dlimage output (var_dump) : string(113)
"C:\laragon\www\api\tmp\MV5BNDliY2E1MjUtNzZkOS00MzJlLTgyOGEtZDg4MTI1NzZkMTBhXkEyXkFqcGdeQXVyNjMwMzc3MjE#.jpg"
add more error checking, replace
file_put_contents($save,file_get_contents($url));
with
$content=file_get_contents($url);
if(!is_string($content)){
throw new \RuntimeException("failed to fetch url {$url}");
}
if(($len=strlen($content))!==($written=file_put_contents($save,$content))){
throw new \RuntimeException("could only write {$written}/{$len} bytes to file {$save}");
}
then you should probably get an errorlog explaining where things went wrong, and my best guess is that things went wrong with file_get_contents() and/or file_put_contents().

Undefined index on cURL request on Graph API

I'm using Facebook's graph API to retrieve some data via a cURL call in PHP and I'm receiving an Undefined index error and I don't know how to target it correctly.
cURL Request:
<?php
/* Call the cURL request to pull in Instagram images */
$curl = curl_init();
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_URL, "https://graph.facebook.com/v5.0/". get_option('insta_id') ."/media?fields=media_url,permalink,username,media_type,thumbnail_url&access_token=". get_option('insta_accesstoken'));
$result = curl_exec($curl);
$array = json_decode($result, true);
?>
Array mapping:
<?php
/* Loop through the array and only pull API fields */
$mediaUrls = array_map(function($entry) {
return [
'media_url' => $entry['media_url'],
'permalink' => $entry['permalink'],
'username' => $entry['username'],
'media_type' => $entry['media_type'],
'thumbnail_url' => $entry['thumbnail_url']
];
}, $array['data']);
?>
Via the Graph API, some have the thumbnail_url and some don't as shown below:
I am receiving an debug error as below:
Correct answer was 'thumbnail_url' => !empty($entry['thumbnail_url']) ? $entry['thumbnail_url'] : "" by #CD001.

I want to upload file to specific folder with google drive API curl

I have uploaded file to google drive with curl API. But I want to upload file to specific folder. I have also tried with folder id in API url like: https://www.googleapis.com/upload/drive/v3/files/folder_id?uploadType=media
add_action('wpcf7_before_send_mail', 'save_application_form');
function save_application_form($WPCF7_ContactForm) {
$wpcf7 = WPCF7_ContactForm :: get_current();
$submission = WPCF7_Submission :: get_instance();
if ($WPCF7_ContactForm->id == 8578) {
if ($submission) {
$submited = array();
//$submited['title'] = $wpcf7->title();
$submited['posted_data'] = $submission->get_posted_data();
$uploaded_files = $submission->uploaded_files();
$name = $submited['posted_data']["Name"];
$position_test = $submited['posted_data']["Position"];
$email = $submited['posted_data']["Email"];
$phone = $submited['posted_data']["phone"];
$message = $submited['posted_data']["Message"];
$position = $submited['posted_data']["AttachYourCV"];
// $test2 = $_FILES['AttachYourCV']['name'];
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$cf7_file_field_name = 'AttachYourCV';
$image_location = $uploaded_files[$cf7_file_field_name];
$mime_type = finfo_file($finfo, $image_location);
$token = GetRefreshedAccessToken('client_id', 'refresh_token', 'client_secret');
$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:' . $mime_type, // todo: runtime detection?
'Authorization: Bearer ' . $token
),
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => file_get_contents($image_location),
CURLOPT_RETURNTRANSFER => 1
));
$response = curl_exec($ch);
$id = json_decode($response, TRUE);
$get_id = $id['id'];
curl_close($ch);
if (isset($id['id'])) {
$get_id = $id['id'];
$post_fields = array();
$folder_id = '1-9r8oVsAfV_iJmYh1cZYPMvE9Qhv8RLA';
// remove extension
$this_file_name = explode('.', $position);
// submit name field
$post_fields['name'] .= $this_file_name[0];
$post_fields['parents'] = $folder_id[1];
$ch2 = curl_init();
curl_setopt_array($ch2, array(
CURLOPT_URL => 'https://www.googleapis.com/drive/v3/files/' . $get_id,
CURLOPT_HTTPHEADER => array(
'Content-Type:application/json', // todo: runtime detection?
'Authorization: Bearer ' . $token
),
CURLOPT_POST => 1,
CURLOPT_CUSTOMREQUEST => 'PATCH',
CURLOPT_POSTFIELDS => json_encode($post_fields),
CURLOPT_RETURNTRANSFER => 1
));
$response = curl_exec($ch2);
if ($response === false) {
$output = 'ERROR: ' . curl_error($ch2);
} else {
$output = $response;
}
// close second request handler
curl_close($ch2);
}
}
I have added another curl call but still didn't get file in folder. My file untitled issue solved with this way.
Uploading files to google drive is a two part thing. (note it can be done as a single call but if you want to add the corect data its best to do it as two)
create Adds the initial meta data for the file. Name, media type, and location that being its parent directory.
Second the actual upload of the file itself.
Note: a file uploaded without first sending the metadata will create a dummy metadata most often with a title of the file being "unknown."
Create
When you do your create of the inertial metadata. You need to add the parents in this inital call the field is called parents[] you need to add the file id there. I cant help you do this as your not adding the code for it.
Upload
By default the file is uploaded into the root folder unless you add a parent folder id for the file.
If you check the documentation you will find the optional query parms
Try using &addParents=[folderId]
Example:
https://www.googleapis.com/upload/drive/v3/files?uploadType=media&addParents=1bpHmln41UI-CRe5idKvxrkIpGKh57T32
If you originally created the metadata for the file in the root directory and then try to upload the file to a different directory i suspect that the upload will create new metadata. These two calls need to be done the same. Your create should have parents set.
post body
$data = array("name" => "test.jpg", "parents" => array("123456"));
$data_string = json_encode($data);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);

How to output the contents of file_get_contents

I'm trying to figure out how to get a php file (html, css and javascript) and load it into the content section below.
The following is the original...
function wpse_124979_add_help_tabs() {
if ($screen = get_current_screen()) {
$help_tabs = $screen->get_help_tabs();
$screen->remove_help_tabs();
$screen->add_help_tab(array(
'id' => 'my_help_tab',
'title' => 'Help',
'content' => 'HTML CONTENT',
I have tried the following but fails. I added a file_get_contents (first line), and then tried pull it in with 'content' => $adminhelp,
The following is with my amended code...
$adminhelp = file_get_contents('admin-help.php');
function wpse_124979_add_help_tabs() {
if ($screen = get_current_screen()) {
$help_tabs = $screen->get_help_tabs();
$screen->remove_help_tabs();
$screen->add_help_tab(array(
'id' => 'my_help_tab',
'title' => 'WTV Help',
'content' => $adminhelp,
Any ideas what's wrong?
If you want the output of the PHP file to be saved as $adminhelp use:
$adminhelp = file_get_contents('http://YOUR_DOMAIN/admin-help.php');
Right now you're loading the source code of admin-help.php into $adminhelp.
Another example for getting the output of a webpage is cURL:
// create curl resource
$ch = curl_init();
// set url
curl_setopt($ch, CURLOPT_URL, "http://YOUR_DOMAIN/admin-help.php");
//return the transfer as a string
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// $output contains the output string
$adminhelp = curl_exec($ch);
// close curl resource to free up system resources
curl_close($ch);
If this doesn't answer your question, please include the error message that you're receiving.

New Instagram API requesting for tagged media by user id

I am trying to create a website like Instagram where user's media are retrieved according to a specific hashtag, so every user has his/her own web page.
according to new Instagram API I'm struggling to request media using access_tokens , I have this code below but it is not working at all, logically it is correct
// function to print out images
function printImages($userID){
$url = 'https://api.instagram.com/v1/users/'.$userID.'/media/recent/? access_token='.$_GET['code'].'&count=5';
$instagramInfo = connectToInstagram($url);
$results = json_decode($instagramInfo, true);
//parse through the images one by one
foreach($results['data'] as $items){
$image_url = $items['images']['low_resolution']['url']; // goining through all result and give back url of picture to save it on the php serve.
echo '<img src" '. $image_url .' "/><br/>';
}
and here is my full code in case
<?php
//config for user PHP server
set_time_limit(0);
ini_set('default_socket_timeout', 300);
session_start();
//Make constraints using define.
define('clientID', 'my client id I have removed it');
define('clientSecret', 'my secret I have removed it');
define('redirectURI', 'my url removed too for the question');
define('ImageDirectory', 'pics/');
// function that is going to connect to instagram.
function connectToInstagram($url){
$ch = curl_init();
curl_setopt_array($ch, array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_SSL_VERIFYHOST => 2,
));
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
if (isset($_GET['code'])){
$code = ($_GET['code']);
$url = 'https://api.instagram.com/oauth/access_token';
$access_token_settings = array ('client_id' => clientID,
'client_secret' => clientSecret,
'grant_type' => 'authorization_code',
'redirect_uri' => redirectURI,
'code' => $code
);
//function to get userID cause username doesn't allow uss to get pictures
function getUserID($userName){
$url = 'https://api.instagram.com/v1/users/search?q='.$userName.'&access_token='.$_GET['code'];
$instagramInfo = connectToInstagram($url);
$results = json_decode($instagramInfo, true);
echo $results['data']['0']['id'];
}
// function to print out images
function printImages($userID){
$url = 'https://api.instagram.com/v1/users/'.$userID.'/media/recent/?access_token='.$_GET['code'].'&count=5';
$instagramInfo = connectToInstagram($url);
$results = json_decode($instagramInfo, true);
//parse through the images one by one
foreach($results['data'] as $items){
$image_url = $items['images']['low_resolution']['url']; // goining through all result and give back url of picture to save it on the php serve.
echo '<img src" '. $image_url .' "/><br/>';
}
}
//cURL is what we use in PHP , it's a library calls to other API's.
$curl = curl_init($url); //setting a cURL session and we put in $url because that's where we are getting the data from
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $access_token_settings); // setting the POSTFIELDS to the array setup that we created above.
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // setting it equal to 1 because we are getting strings back
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); // but in live work-production we want to set this to true for more security
$result = curl_exec($curl);
curl_close();
$results = json_decode($result, true);
$use
could anyone tell me what should I do to use access_tokens for every user using my app ?
Have you approved permission of your app from instagram?
Instagram has changed their api policy on 2016/6/1.

Categories