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;
}
Related
I am creating a local website that makes use of the OpenAI API using XAMPP and HTML/CSS and PHP. I have implemented a page to enter a question and display the answer from the API, but the result has no relation to the question asked. I am looking for help to solve this problem. Here is my php code (it works with another file calling it).
Thanks in advance for your help.
PS: I voluntarily removed the api key when I posted the request on stack overflow
Translated with www.DeepL.com/Translator (free version)
<?php
$apiKey = 'sk-';
$modelId = 'text-davinci-002';
$prompt = "";
$temperature = 0.5;
$maxTokens = 256;
$topP = 1;
$frequencyPenalty = 0;
$presencePenalty = 0;
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://api.openai.com/v1/completions",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => false,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS =>"{\"model\": \"".$modelId."\",
\"prompt\": \"".$prompt."\",
\"temperature\": ".$temperature.",
\"max_tokens\": ".$maxTokens.",
\"top_p\": ".$topP.",
\"frequency_penalty\": ".$frequencyPenalty.",
\"presence_penalty\": ".$presencePenalty."}",
CURLOPT_HTTPHEADER => array(
"Authorization: Bearer ".$apiKey,
"Content-Type: application/json"
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
$result = json_decode($response);
echo $result->choices[0]->text;
}
?>
I tried several solutions such as changing the API model and rewriting the code, but I could not solve the problem. I am looking for help to solve this problem.
I used the function file_get_contents to get content from a website. but just see messege "sorry! something went wrong."
My code here:
<?php
$kkk = 'https://batdongsan.com.vn/phan-tich-nhan-dinh/thi-truong-can-ho-cao-cap-can-mot-su-sang-loc-khat-khe-ar97716';
$ddd = file_get_contents($kkk);
echo $ddd;
?>
Can you help me explain this error or any idea
thank you so much!
Yes, file_get_contents() returns that msg "sorry! something went wrong." for me also. Make API call using PHP CURL. Let's try like this way-
Note:
URL which is not retrieved by file_get_contents(), because their
server checks whether the request come from browser or any script?. If
they found request from script they simply disable page contents.
So that you have to make a request similar as browser request. PHP
Curl is suitable choice for this kind of job. See here
<?php
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://batdongsan.com.vn/phan-tich-nhan-dinh/thi-truong-can-ho-cao-cap-can-mot-su-sang-loc-khat-khe-ar97716",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_POSTFIELDS => "",
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}
My Controller.
public function showMonthlyReport($site_id, $report_id){
$reports = Report::where('report_id', $report_id)->firstOrFail();
$uptime = ???
return view('records', compact('site_id', 'report_id', 'reports', 'uptime'));
}
And my UptimeRobot.php reference https://uptimerobot.com/api getMonitors()method
<?php
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://api.uptimerobot.com/v2/getMonitors",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => "Your Api Key",
CURLOPT_HTTPHEADER => array(
"cache-control: no-cache",
"content-type: application/x-www-form-urlencoded"
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
$data = json_decode($response);
$custom_uptime = ($data->monitors[0]->custom_uptime_ratio);
$uptime = explode("-",$custom_uptime);
}
?>
ApiCommand.php
public function handle()
{
include(app_path() . '/Includes/DeepCrawl.php');
include(app_path() . '/Includes/Uptime.php');
include(app_path() . '/Includes/HelloAnalytics.php');
$stringData = ApiCommand::drawGraph($uptime, $dates, $users, $otherResultsRows, $array_issues, $array_pages_breakdown, $array_uncrawled_url, $array_non_200_pages, $array_orphaned_pages, $array_non_indexable_pages, $array_crawl_source_gap, $array_https_http);
Storage::disk('local')->put('hello.txt', $stringData);
}
Currently building a laravel web application.
I am just wondering how can i able to gather data from uptimerobot. I'm going to use my controller so I can pass it to my view but I don't know how. I have code below with the curl php type above. Really confused what am I doing new programmer here. Can someone explain if I'm at the right path or is it possible to do in controller. Thanks in advance.
I can suggest slightly different solution:
Extract your curl code in a separate console command and run this command each minute (for example, as a cron job).
The result of the command save to database/file/memory.
In your showMonthlyReport() refer to existing result.
Benefits:
In this way you would not have to wait for your curl result on each showMonthlyReport(). All code will run asynchronously
All errors processing will be in one place
Command is testable
I try to get a booking.com page from a hotel to fetch the prices afterwards with regex. The problem is the following:
I call file_get_contents with parameter like checkin and checkout (file_get_contents("/hotel/at/myhotel.html?checkin=2017-10-12&checkout=2017-10-13")) dates so that the prices are shown to the visitor. If I watch the source code in the browser I see the entry:
b_this_url : '/hotel/at/myhotel.html?label=gen173nr-1FCAsoDkIcbmV1ZS1wb3N0LWhvbHpnYXUtaW0tbGVjaHRhbEgHYgVub3JlZmgOiAEBmAEHuAEHyAEM2AEB6AEB-AEDkgIBeagCAw;sid=58ccf750fc4acb908e20f0f28544c903;checkin=2017-10-12;checkout=2017-10-13;dist=0;sb_price_type=total;type=total&',
If I echo the string from file_get_contents the string looks like:
b_this_url : '/hotel/at/myhotel.html',
So all parameters that I passed to the url with file_get_contents are gone and therefore I couldn't find any prices with my regex on the page ...
Does anyone have a solution for this problem?
The webpage is not completely generated server-side, but it relies heavily on JavaScript after the HTML part loads. If you are looking for rendering the page as it looks in browser, I think you should use php curl instead of file_get_contents() for this kind of web scraping thing. I generated an automatic code for you from Postman (a google chrome extension / standalone desktop app) for your given url. The response contains the full url with params. See the image and I posted the code for you also.
<?php
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://www.booking.com/hotel/at/hilton-innsbruck.de.html?checkin=2017-10-10%3Bcheckout%3D2017-10-11",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_HTTPHEADER => array(
"cache-control: no-cache",
"postman-token: 581a75a7-6600-6ed6-75fd-5fb09c25d927"
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}
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;