Implementing Sketchfab API - php

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.

Related

Video Upload on Imgur 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.

how to include google analytics in php web service

I have a webservice writen in php and it is called from an desktop application installed on PC's.
I want to have a register of the users who calls the functions on the web service and for this I only want to send hits to Google Analytics.
webservice in php:
<?php
require_once('lib/nusoap.php'); // basic include.. must go at the top
$SERVICE_NAMESPACE = "urn:Service"; // create a namespace to run under.
$server = new soap_server(); // the soap object from the include above.
// this has many input parameters but we only need two: the service name and the namespace
$server->configureWSDL('Service', $SERVICE_NAMESPACE);
$server->register('test',// method name
array('name' => 'xsd:string', 'name99' => 'xsd:string'),// input parameter called name.. and it's a string.
array('return' => 'xsd:string'),// output - one string is returned called "return"
$SERVICE_NAMESPACE,// namespace
$SERVICE_NAMESPACE . '#hello1',// soapaction
'rpc',// style.. remote procedure call
'encoded',// use of the call
'Nada interesante'// documentation for people who hook into your service.
);
function test($sName,$sName99)
{
return 'TEST ';
}
//This processes the request and returns a result.
$HTTP_RAW_POST_DATA = isset($HTTP_RAW_POST_DATA) ? $HTTP_RAW_POST_DATA : '';
$server->service($HTTP_RAW_POST_DATA);
?>
I want to have google analytics info and for that i want to integrate the following script:
<script async src="https://www.googletagmanager.com/gtag/js?id=UA-89356985-1"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments)};
gtag('js', new Date());
gtag('config', 'UA-89356985-1');
</script>
I don't know how to integrate in the test function. I want to know when the users calls the test function.
Thanks in advance very much.
You cannot use the Javascript tracker unless your PHP script produces HTML and Javascript that is executed in a browser.
You can however use the Measurement Protocol to make server side calls to Google Analytics. That's basically an endpoint where you send predefined parameters with your custom values (via any method that can make http calls) and they will register in Google Analytics.
This can be used as en example of what you need. use http_build_queryto build you hit as you want to Google Analytics. Change Google_Analytics_UA_Stringto match your Google Analytics ID
<?php
//some of the functions we need to make it work
function generate_serial($n) {
$c = "abcdefghijklmnopqrstuvwyxz0123456789";
$s = '';
for($i=0;$i<$n;$i++) {
$s .= substr($c,rand(0,37),1);
}
return $s;
}
function generate_uuid() {
return generate_serial(8).'-'.generate_serial(4).'-4'.generate_serial(3).'-a'.generate_serial(3).'-'.generate_serial(12);
}
function ip() {
$ip = false;
if(isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
$ip = explode(',',$_SERVER['HTTP_X_FORWARDED_FOR']);
$ip = trim(array_shift($ip));
}
elseif(isset($_SERVER['REMOTE_ADDR'])) {
$ip = $_SERVER['REMOTE_ADDR'];
}
return $ip;
}
//define necessary variables
define('Google_Analytics_UA_String','UA-XXXXXXXX-X');
//create a UUID string for the user sending the request and store in the the session
if(isset($_COOKIE['Google_Analytics_UUID']) and !empty($_COOKIE['Google_Analytics_UUID'])) {
define('Google_Analytics_UUID',$_COOKIE['Google_Analytics_UUID']);
}
else {
define('Google_Analytics_UUID',generate_uuid());
setcookie('Google_Analytics_UUID',Google_Analytics_UUID,time()+63072000);
}
//compile the data we want to send to the API
$data = http_build_query(array(
'v' => 1, // version
'ds' => 'app', // data source
'tid' => Google_Analytics_UA_String, // Tracking ID / Web Property ID
'cid' => Google_Analytics_UUID, // Client ID
'uip' => ip(), // IP Override
't' => 'event', // Hit type
'ec' => 'site clicks', // event category
'ea' => 'click', // event action
'el' => 'button', // event label
'ev' => 'Click here!' // event value
));
//send using PHP's cURL extension
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,'https://www.google-analytics.com/collect');
curl_setopt($ch,CURLOPT_HEADER,true);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
curl_setopt($ch,CURLOPT_POST,true);
curl_setopt($ch,CURLOPT_POSTFIELDS,$data);
$response = curl_exec($ch);
//parse the response and send back to the browser
header('Content-Type: application/json');
$status = curl_getinfo($ch,CURLINFO_HTTP_CODE);
if($status == 200) {
echo json_encode([
'success' => true
]);
}
else {
echo json_encode([
'error' => true
]);
}
?>
The exact running sample is:
<?php
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => 'http://www.google-analytics.com/collect?v=1&tid=UA-XXXXXXX-1&cid=35009a79-1a05-49d7-b876-2b884d0f825b&uid=myserid&uip=179.52.60.197&t=event&ec=Service&ea=SER&el=999999&z=54564653213',
CURLOPT_USERAGENT => 'Vanity-URL-Tracker',
));
$resp = curl_exec($curl);
curl_close($curl);
?>
I have an example for Page Tracking:
public function send($trackingId, $host, $page, $title)
{
$google_analytics_url = 'https://www.google-analytics.com/collect';
$google_analytics_params = http_build_query(array(
'v' => 1,
'tid' => $trackingId, // UA-xxxxxxx-x
'cid' => uniqid(),
't' => 'pageview',
'dh' => $host,
'dp' => '/'.$page,
'dt' => urlencode($title),
));
$url = $google_analytics_url.'?'.$google_analytics_params;
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => $url,
CURLOPT_USERAGENT => 'Vanity-URL-Tracker',
));
$resp = curl_exec($curl);
$status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
if($status!= 200) {
log_message('error', json_encode(array('status' => $status, 'response' => $resp)) );
}
if (curl_errno($curl)) {
log_message('error', curl_error($curl));
}
curl_close($curl);
return $resp;
}

Using curl to post request handle JSON data

I recently work with kraken.io API and I'm trying to integrate this API wuth my PHP CodeIgniter framework. So I followed the documentation but I got stuck when I used curl
This is my source code below ..
require_once(APPPATH.'libraries/kraken-php-master/Kraken.php');
$kraken = new Kraken("SOME_KEY", "SOME_SECRET");
$params = array(
"file" => base_url()."include/".$dataIn['logo'],
"wait" => true
);
$dataj='{"auth":{"api_key": "SOME_KEY", "api_secret": "SOME_SECRET"},"file":'.base_url()."include/".$dataIn['logo'].',wait":true}';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://api.kraken.io/v1/upload");
curl_setopt($ch, CURLOPT_HTTPHEADER,array('Content-Type: application/json'));
curl_setopt($ch, CURLOPT_POSTFIELDS, $dataj);
$response = curl_exec($ch);
curl_close($ch);
$data = $kraken->upload($params);
print_r($response);exit();
And I got this result
"{"success":false,"message":"Incoming request body does not contain a valid JSON object"}1"
So can anyone please help me,
And thanks in advance,
DONT POST YOUR API_KEY AND API_SECRET
The error message is quite clear, your json object is not valid. For instance this would be a valid JSON object for your request:
{
"auth": {
"api_key": "SOME",
"api_secret": "SECRET"
},
"file": "somefile.txt",
"wait": true
}
In your php code you are setting up a $params array but then you don't use it. Try this:
$dataj='{"auth":{"api_key": "SOME_KEY", "api_secret": "SOME_SECRET"},"file":"' . $params["file"]. '", "wait":true}';
You can validate your JSON HERE
You should use json_encode function to generate your JSON data
$dataj = json_encode([
"auth" => [
"api_key" => "API_KEY",
"api_secret" => "API_SECRET"
],
"file" => base_url() . "include/" . $dataIn['logo'],
"wait" => true
]);
EDIT:
Here is an example from https://kraken.io/docs/upload-url so you don't need to use curl
require_once("Kraken.php");
$kraken = new Kraken("your-api-key", "your-api-secret");
$params = array(
"file" => "/path/to/image/file.jpg",
"wait" => true
);
$data = $kraken->upload($params);
if ($data["success"]) {
echo "Success. Optimized image URL: " . $data["kraked_url"];
} else {
echo "Fail. Error message: " . $data["message"];
}

# value of POST variable in PHP CURL

I'm creating a function to untilize NameCheap's API for registering domain names. The registration process worked out smoothly, now I'm looking to set the proper DNS Hosts.
When I create a pure POST request with something like POSTMAN this works fine and returns the expected XML response. However when I try to pass the data through PHP's CURL functions it breaks. I've narrowed the problem the the '#' symbol that needs to be passed to the DNS Host. If i put anything else there the request goes through. I've tried to url_encode the symbol but the API does not accept that.
Any suggestions?
public function setDNSHost($name, $server){
list($domain,$tld) = explode('.',$name,2);
$request = $this->request_URL;
$curl = curl_init();
$args['ApiUser'] = $this->API_User;
$args['ApiKey'] = $this->API_Key;
$args['UserName'] = $this->API_User;
$args['Command'] = 'namecheap.domains.dns.setHosts';
$args['ClientIP'] = $this->Client_IP;
$args['SLD'] = $domain;
$args['TLD'] = $tld;
$args['HostName1'] = utf8_encode('#');
$args['RecordType1'] = 'A';
$args['Address1'] = $server;
$args['HostName2'] = 'www';
$args['RecordType2'] = 'CNAME';
$args['Address2'] = $name;
$args['HostName3'] = '*';
$args['RecordType3'] = 'CNAME';
$args['Address3'] = $name;
curl_setopt_array($curl, array(
CURLOPT_URL => $request,
CURLOPT_USERAGENT => 'API',
// CURLOPT_FAILONERROR => 1,
CURLOPT_FOLLOWLOCATION => 1,
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => $args,
CURLOPT_TIMEOUT => 15
));
$response = curl_exec($curl);
curl_close($curl);
// $oXML = new SimpleXMLElement($response);
return $response;
}
Some caracters are not allowed to be in the string. To avoid such problems you could use http_build_query on your data before you use the curl function.

Box-api V2 upload file curl php returns false

I´m trying to upload a file from PHP via Box-API v2 and I only get a boolean false response.
I think this is caused by CURL, not Box-API but I was fighting the last five hours, and I can´t find the solution. Any idea??
The implicated code is that:
note: the file exists and is accessible from code and the token is ok (other calls to API work fine)
const CONTENT_ENDPOINT = 'https://api.box.com/2.0/';
$file = "unexeceles.xlsx";
private $defaultOptions = array(
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_VERBOSE => true,
CURLOPT_HEADER => true,
CURLINFO_HEADER_OUT => false,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_FOLLOWLOCATION => false,
);
public function putFile($file) {
$options = $this->defaultOptions;
$options[CURLOPT_HTTPHEADER] = array ("Authorization: Bearer ".$this->token);
$options[CURLOPT_POST] = true;
$postfields = array();
$postfields["filename"] = '#'.$file;
$postfields["parent_id"] = 0;
$options[CURLOPT_POSTFIELDS] = $postfields;
$handle = curl_init(BoxConfig::CONTENT_ENDPOINT."files/content");
curl_setopt_array($handle, $options);
$response = curl_exec($handle);
curl_close($handle);
if (is_string($response)) {
$response = $this->parse($response);
}
return $response;
}
Finally I've found the solution.
The problem was the relative path to the file, the file exists and it´s accessible form code, but CURL seems to need the entire path to the file.
Very helpful the function curl_errno($handle)
if(curl_errno($handle)) {
echo 'Curl error: ' . curl_error($handle);
}

Categories