I'm trying to write a very simple test to upload an image to imgur and then redirect to the imgur page once it's done. (haven't gotten to that point yet)
I've looked all around these forums and tried so many different codes posted here, as well as cobbled some together from various posts. Finally, I've stopped getting errors in the php.
But.. in every code I've seen, it displays the image once it's done. Using that exact same code, my image does not appear, all I get is a page with Result: and nothing more. Does anyone have any idea what could be the problem?
<html>
<body>
<form action="upload_img.php" method="post" enctype="multipart/form-data">
<input type="file" name="imgupload" /><br>
<input type="submit" value="Upload to Imgur" />
</form>
</body>
</html>
and the php file:
<?php
$client_id = '$clientIDHERE';
$file = file_get_contents($_FILES["imgupload"]["tmp_name"]);
$url = 'https://api.imgur.com/3/image.json';
$headers = array("Authorization: Client-ID $client_id");
$pvars = array('image' => base64_encode($file));
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL=> $url,
CURLOPT_TIMEOUT => 30,
CURLOPT_POST => 1,
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_HTTPHEADER => $headers,
CURLOPT_POSTFIELDS => $pvars
));
$json_returned = curl_exec($curl); // blank response
echo "Result: " . $json_returned ;
curl_close ($curl);
?>
Before you close the $curl handle you should check for errors:
if ($error = curl_error($curl)) {
die('cURL error:'.$error);
}
Related
eBay is making changes to their APIs, shutting down the finding API at the end of the year. I'm using a very simple application on my WordPress site that displays products based on a specific query I hard code. I am able to replicate my page using the Browse API, but I'm really struggling with the Oauth part of things. From what I understand, the Browse get requests only require an application access token (not a user access token). I'm just still struggling to get my head around all of this. I'm trying to add a function that generates an auth token, but it's not working and I don't think I'm calling the function correctly...so looking for help on a few things here. Most importantly--can i do it this way? And am i entering the variables correctly and how exactly do i call the Oauth function?
<?php
/* Template Name: XXXX */
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
function getOAuthCreds() {
$endpoint = 'https://api.ebay.com/identity/v1/oauth2/token';
$request = "grant_type=client_credentials";
$request .= "scope=https://api.ebay.com/oauth/api_scope";
$session = curl_init($endpoint);
curl_setopt($session, CURLOPT_POST, true);
curl_setopt($session, CURLOPT_POSTFIELDS, $request);
curl_setopt($session, CURLOPT_RETURNTRANSFER, true);
$headers = [
'Content-Type: application/json',
'Authorization = Bearer CODE HERE// I'm using the auth code generated from the application access token (not sure if thats' right?
];
curl_setopt($session, CURLOPT_HTTPHEADER, $headers);
$response = curl_exec($session);
curl_close($session);
return $response;
}
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://api.ebay.com/buy/browse/v1/item_summary/search?q=iphone&sort=-",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_HTTPHEADER => array(
"Content-Type:application/json",
"Authorization:" getOAuthCreds(),///am i calling this correctly?
"X-EBAY-C-MARKETPLACE-ID:EBAY_US",
"X-EBAY-C-ENDUSERCTX:affiliateCampaignId=xx,affiliateReferenceId=xx",
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
//print_r($response);
if ($err) {
if ($debug) echo "cURL Error #:" . $err;
else echo "Oops, something went wrong. Please try again later.";
} else {
//Create an array of objects from the JSON returned by the API
$jsondata = json_decode($response);
$resp = $jsondata->itemSummaries;
//Create a simple grid style for the listings
$pageCSS = "<style>
.netflix-wrapper{
display:grid;
grid-template-columns: 200px 200px 200px;
}
.show-wrapper{padding:10px;}
</style>";
//Create the WordPress page content HTML
$pageHTML="<h2>test</h2>";
$pageHTML.="<div class='test-wrapper'>";
//Loop through the API results
foreach($resp as $item) {
//Put each show into an html structure
// Note: if your theme uses bootstrap use responsive classes here
$pageHTML.="<div class='show-wrapper'>";
//Not all items have a 'poster', so in that case use the img field
$pic = $item->image->imageUrl;
$itemID = $item->legacyItemId;
$link = 'https://www.ebay.com/itm/'.$itemID.'?mkrid=ss-0&siteid=0&mkcid=1&campid=ss&toolid=ss&mkevt=1&customId=ss';
$title = $item->title;
$price = $item->price->value;
$bids = $item->bidCount;
if(empty($bids)){
$bids = 0;
}
// For each SearchResultItem node, build a link and append it to $results
$results .= "<div class=\"item\"><div class=\"ui small image\"><img height=\"200px\" width=\"130px\" src=\"$pic\"></div><div class=\"content\"><div class=\"header\">$title</div><div class=\"meta\" style=\"margin-top:1.1em\"><span class=\"price\"><button class=\"ui teal button\">watch watchers</button></span><div class=\"extra\"><button class=\"ui button\"><b>Current Bids:</b> $bids </button></div><div class=\"extra\"><button class=\"ui orange button\">Current Price: $$price</button></div><div class=\"description\"></div></div></div></div>";
//Show the image first to keep the top edge of the grid level
$pageHTML.="<img style='max-width:166px;float:left;' src='".$pic."' />";
$pageHTML.="<h3>".$item->title."</h3>";
// $pageHTML.="<span>added to netflix ".$showObj->titledate."</span>";
// $pageHTML.="<div style='float:left;'>".$showObj->synopsis."</div>";
$pageHTML.="</div>";
}
$pageHTML.="</div>";
}
?>
<?php get_header(); ?>
<!-- Build the HTML page with values from the call response -->
<html>
<head>
<div class="wrp cnt"><div class="spr"></div>
<section class="bSe fullWidth">
<article><div class="awr lnd">
<title>Most Watched <?php echo $query; ?> on eBay</title>
<style type="text/css">body { font-family: arial,sans-serif;} </style>
<link
rel="stylesheet"
href="//cdn.jsdelivr.net/npm/semantic-ui#2.4.2/dist/semantic.min.css"
/>
</head>
<body>
For reference:
https://developer.ebay.com/api-docs/static/oauth-client-credentials-grant.html
I do not know much about php but gathered from your code there are a few things that are not right.
1. The headers section
In function getOAuthCreds()
Headers should be:
Content-Type = application/x-www-form-urlencoded
Authorization = Basic [B64-encoded_oauth_credentials]
Content-Type = application/x-www-form-urlencoded header. eBay wants you to POST to its server so you will need this. Not sure if curl would automatically add to the header.
Authorization header. From eBay reference above, the header will use Basic authentication scheme. Then followed by the Base64 encoding of your "client_id":"client_secret".
[B64-encoded_oauth_credentials] = Base64Encode(client_id:client_secret)
Sample:
Authorization = Basic Y2xpZW50X2lkOmNsaWVudF9zZWNyZXQ=
In case you are not sure where to get "client_id" and "client_secret". Visit this page.
https://developer.ebay.com/api-docs/static/creating-edp-account.html
If everything is correct, you will receive the following response from eBay
Sample:
{
"access_token": "v^1.1#i^1#p^1#r^0#I^3#f^0#t^H4s ... wu67e3xAhskz4DAAA",
"expires_in": 7200,
"token_type": "Application Access Token"
}
The access_token from the response will be valid for 7200 seconds. Cache and reuse it as the previous comment mentioned. When it is expired, get a new access_token.
2. When calling Browse API
You will use the access_token in the Authorization header (in Browse API call) as follow.
Sample:
Authorization: Bearer v^1.1#i^1#p^1#r^0#I^3#f^0#t^H4s ... wu67e3xAhskz4DAAA
i'm trying to use imgur as a uploading backend - i guess it secure my website if there's upload picture (is it right?) so
i went with this way :
<?php
$client_id = 'xxxxx';
$file = file_get_contents($_FILES["imgupload"]["tmp_name"]);
$url = 'https://api.imgur.com/3/image.json';
$headers = array("Authorization: Client-ID $client_id");
$pvars = array('image' => base64_encode($file));
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL=> $url,
CURLOPT_TIMEOUT => 30,
CURLOPT_POST => 1,
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_HTTPHEADER => $headers,
CURLOPT_POSTFIELDS => $pvars
));
if ($error = curl_error($curl)) {
die('cURL error:'.$error);
}
$json_returned = curl_exec($curl); // blank response
echo "Result: " . $json_returned ;
curl_close ($curl);
?>
HTML form
<form action="upload" method="post" enctype="multipart/form-data">
<input type="file" name="imgupload" /><br>
<input type="submit" value="Upload to Imgur" />
</form>
when i click on submit the result is fine as i guess ^^
Result: {"data":{"id":"TvFtE29","title":null,"description":null,"datetime":1585015712,"type":"image\/png","animated":false,"width":900,"height":940,"size":48902,"views":0,"bandwidth":0,"vote":null,"favorite":false,"nsfw":null,"section":null,"account_url":null,"account_id":0,"is_ad":false,"in_most_viral":false,"has_sound":false,"tags":[],"ad_type":0,"ad_url":"","edited":"0","in_gallery":false,"deletehash":"Z9xFH8mrSH8lRDB","name":"","link":"https:\/\/i.imgur.com\/TvFtE29.png"},"success":true,"status":200}
but my problem i want to collect the https://i.imgur.com/TvFtE29.png into specific variable like $uploaded = 'https://i.imgur.com/TvFtE29.png'; to added into my database -> user pic
i went with json_decode but it's not completed with me in the right way, if someone can help with this issue 🌹
thanks.
json_decode worked fine here:
$json_returned = json_decode($json_returned, true);
$uploaded = $json_returned['data']['link'];
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.
Does anyone know how to upload a video to Wistia using PHP cURL from a file upload input specified within a form? This is my code but I cannot seem to get this to work with the current API. I’ve looked at a few similar posts on this subject but still no luck...
<?php
$pathToFile = $_FILES['fileName']['tmp_name']; /* /tmp/filename.mov */
$nameOfFile = $_FILES['fileName']['name']; /* filename.mov */
$data = array(
'api_password' => '********',
'file' => '#'.$pathToFile,
'project_id' => '********'
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_URL, "https://upload.wistia.com" );
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$result = curl_exec($ch);
curl_close($ch);
?>
UPDATE - FULL CODE (still not working)
cURL returns false for both curl_exec and curl_error when using "'file' => '#'.$pathToFile" but works fine when using "'url' = 'http://example.com/file.mov'... Perhaps I'm not processing the form properly? Here's the full code:
<?php
if ($_POST['submit']) {
$filePath = $_FILES['fileUploaded']['tmp_name'];
$fileName = $_FILES['fileUploaded']['name'];
$fileSize = $_FILES['fileUploaded']['size'];
echo("File Path: ");
echo $filePath;
echo '<br>';
$data = array(
'api_password' => '******',
/* 'url' => 'http://example.com/file.mov', WORKS */
'file' => '#'.$filePath, /* DOES NOT WORK */
'project_id' => '******'
);
// WORKING CMD LINE
// curl -i -F api_password=****** -F file=#file.mov https://upload.wistia.com/
/* cURL */
$chss = curl_init('https://upload.wistia.com');
curl_setopt_array($chss, array(
CURLOPT_POST => TRUE,
CURLOPT_RETURNTRANSFER => TRUE,
CURLOPT_POSTFIELDS => http_build_query($data)
));
// Send the request
$KReresponse = curl_exec($chss);
$KError = curl_error($chss);
// Decode the response
$KReresponseData = json_decode($KReresponse, TRUE);
echo '<br>';
echo("Response:");
print_r($KReresponseData);
echo '<br>';
echo("Error:");
print_r($KError);
}
?>
<form name="upload-form" method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>" enctype="multipart/form-data">
<input type="file" name="fileUploaded">
<input type="submit" name="submit" value="Upload">
</form>
Any help would be much appreciated!
Try this:
$filePath = "#{$_FILES['fileUploaded']['tmp_name']};filename={$_FILES['fileUploaded']['name']};type={$_FILES['fileUploaded']['type']}";
I've got the following code and it works perfectly fine for uploading one image to Imgur using their API:
$client_id = $myClientId;
$file = file_get_contents($_FILES["file"]["tmp_name"]);
$url = 'https://api.imgur.com/3/image.json';
$headers = array("Authorization: Client-ID $client_id");
$pvars = array('image' => base64_encode($file));
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL=> $url,
CURLOPT_TIMEOUT => 30,
CURLOPT_POST => 1,
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_HTTPHEADER => $headers,
CURLOPT_POSTFIELDS => $pvars
));
$json_returned = curl_exec($curl); // blank response
$json = json_decode($json_returned, true);
curl_close ($curl);
However I need to upload multiple images at once. On the client side, the user will have multiple <input type="file" /> fields. I'm completely stuck now with figuring out where and how I will need to modify this code in order to handle multiple image upload when they come through to the server in the form of an array. Does anyone have any ideas?
Change the markup as follows:
<form action="file-upload.php" method="post" enctype="multipart/form-data">
Send these files:<br />
<input name="file[]" type="file" multiple="multiple" /><br />
<input type="submit" value="Send files" />
</form>
Now, you can loop through the $_FILES array using a foreach, like so:
foreach ($_FILES['file']['tmp_name'] as $index => $tmpName) {
if( !empty( $tmpName ) && is_uploaded_file( $tmpName ) )
{
// $tmpName is the file
// code for sending the image to imgur
}
}