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);
Related
I am working on integrating my application with the API of another application. Previously I have done such integrations using JSON and had no problem, unfortunately, the application I want to connect to uses XML which I have not interacted with before.
The task is to load an .xml file into a PHP script, then perform gzip on that XML, and then encode the byte array to base64.
I have the XML file ready, I can use base64_encode() too, but I sit on this gzip for several hours and nothing works. (I load the XML file into the script using simplexml_load_file)
I tried using gzencode, gzcompress but it doesn't work.
Authentication involves combining HTTP parameters and encoding them with urlencode(). The req_sig (signature) parameter contains the encoded parameters (mentioned above) + API code. If everything matches then a response is returned, if not then an error is displayed: ERROR4000Signature does not match, even though the signature matches, because it is generated the same way in other queries using GET.
My code:
$xml=simplexml_load_file("request.xml") or die("Failed to load");
$gzip = gzencode($xml);
$base64 = base64_encode($gzip);
$username = 'test-app-user';
$req_id = rand(10000000000, 99999999999);
$api_token = "za5rth23ku776fdvbn2";
$string_bazowy = "command=$base64"."req_id=$req_id"."username=$username";
$encoded = urlencode($string_bazowy);
$string_zmieniony = "$encoded"."$api_token";
$md5 = md5($string_zmieniony);
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://saldeo-test.brainshare.pl/api/xml/1.0/company/synchronize?command=$base64&req_id=$req_id&username=$username&req_sig=$md5",
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',
));
$response = curl_exec($curl);
curl_close($curl);
echo $response;
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.
I need to parse this web page ....
http://monitorps.sardegnasalute.it/monitorps/MonitorServlet?page=carLavoroPresidi&tipoProntoSoccorso=TUTTI&codiceAziendaSanitaria=200102&idPresidio=102MAD02&indirizzo=null&idProntoSoccorso=30
... using PHP to extract the numbers that are in the table under le columns "ROSSO", GIALLO", "VERDE" and "BIANCO".
(NOTE: you could see different value in that page if you try to browse it ... it doesn't matter ..,, it change dinamically .... )
Those values are a POST request result inside the web page.
This is the PHP code that I'm using to send a POST request using curl, and than parse the JSON response (using Skyscanner JSON Path .. it's working fine in my code .. ), trying to extract the values using a XPath parsing.
<?php
include "./tmp/vendor/autoload.php";
$ch = curl_init();
curl_setopt_array($ch, array(
CURLOPT_URL => "http://monitorps.sardegnasalute.it/monitorps/MonitorServlet",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => "idMacroArea=null&codiceAziendaSanitaria=200102&idAreaVasta=null&idPresidio=102MAD02&idProntoSoccorso=30&tipoProntoSoccorso=TUTTI&vicini=null&xhr=true",
CURLOPT_HTTPHEADER => array(
"cache-control: no-cache",
"content-type: application/x-www-form-urlencoded"
),
));
$server_output = curl_exec ($ch);
curl_close ($ch);
$jsonObject = new JsonPath\JsonObject($server_output);
$jsonPathExpr = '$..view';
$res = $jsonObject->get($jsonPathExpr);
print $res[0];
$dom = new DOMDocument();
#$dom->loadHTML(json_encode($res[0]));
$xpath = new DOMXPath($dom);
$xpath_for_parsing = '/html/body/div[1]/div/div/div/table/tbody/tr[2]/td[4]';
$colorWaitingNumber = $xpath->query($xpath_for_parsing);
$theValue = 'N.D.';
foreach( $colorWaitingNumber as $node )
{
$theValue = $node->nodeValue;
}
print $theValue;
?>
The result is in the following image
where the table is the result of the command in my code ...
print $res[0];
and
N.D
is the result when I try to parse to extract one of my desired value
About the xpath that I'm using I've checked it verifying with the page source code ......
Where am I doing wrong?
I've solved!
My original code was "quite" right except for a mistake.
You've to comment this line ...
//#$dom->loadHTML(json_encode($res[0]));
and substitute it with this one
#$dom->loadHTML($res[0]);
and all will work fine!
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;
I am currently attempting to make a function in my class which gets data from an external server.
I am able to get the data with CURL, but I do not want to use CURL to directly store it in a file.
This is semi difficult to explain so I will show you.
This is my function for getting the image:
function getCharacterPortrait($CharID, $size){
$url = "http://image.eveonline.com/character/{$CharID}_{$size}.jpg";
$ch = curl_init($url);
curl_setopt_array($ch, array(
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HEADER => false,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_ENCODING => "",
CURLOPT_AUTOREFERER => true,
));
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
So, what I want to do from here, is take the $data which is the raw image I presume, and store it in a .jpg in a specified file.
I have found a similar explanation for this using CURL, but CURL was used to directly store it. I would like the script that is calling the function to get the image to store the file.
Sorry if I am being a bit confusing, but I think you get the premise of what I am saying. If more explaining is needed please do say so.
How about this?
$a = implode('',#file('http://url/file.jpg'));
$h = fopen('/path/to/disk/file.jpg','wb');
fwrite($h,$a);
fclose($h);
Just write all the data cURL gave you to a file with file_put_contents() for example?
[your curl code...]
file_put_contents('localcopy.jpg', $data);
Edit:
Apparently there is also a cURL option to download to a file like:
$fp = fopen($path, 'w');
curl_setopt($ch, CURLOPT_FILE, $fp);
Found at http://www.phpriot.com/articles/download-with-curl-and-php
Use it
$url = "http://image.eveonline.com/character/{$CharID}_{$size}.jpg";
$local_path = "myfolder/{$CharID}_{$size}.jpg";
$file = file_get_contents($url);
file_put_contents($file, $local_path);