How to import php file to your controller and gather data - php

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

Related

Problem integrating the OpenAI API with my website using XAMPP and PHP

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.

Interrogate API until no results left

I am working with an API at the moment that will only return 200 results at a time, so I am trying to run some code that works out if there is more data to fetch based on whether or not the results have a offsetCursor param in them as this tells me that that there are more results to get, this offsetCursor is then sent a param in the next request, the next set of results come back and if there is an offsetCursor param then we make another request.
What I am wanting to do is push the results of each request into a an array, here is my attempt,
function get_cars($url, $token)
{
$cars = [];
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => $url,
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(
"Content-Type: application/x-www-form-urlencoded",
"Authorization: Bearer " . $token
)
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if($err) {
return false;
} else {
$results = json_decode($response, TRUE);
//die(print_r($results));
$cars[] = $results['_embedded']['results'];
if(isset($results['cursorOffset']))
{
//die($url.'&cursor_offset='.$results['cursorOffset']);
get_cars('https://abcdefg.co.uk/service/search1/advert?size=5&cursor_offset='.$results['cursorOffset'], $token);
//array_push($cars, $results['_embedded']['results']);
}
}
die(print_r($cars));
}
I assume I am doing the polling of the api correct in so mush as that if there is a cursor offet then I just call the function from within itself? But I am struggling to create an array from the results that isnt just an array within and array like this,
[
[result from call],
[resul from call 2]
]
what I really want is result from call1 right through to call n be all within the same sequential array.
using a do+while loop, you'll have only 1 instance of cars variable, that would work.
Since you're using recursion, when you call get_cars inside get_cars, you have 2 instances of cars variable, one per get_cars call.
IMHO, using a loop is better in your case.
But if you still want to use recursion, you should use the result of get_cars call, something like this:
if(isset($results['cursorOffset']))
{
//die($url.'&cursor_offset='.$results['cursorOffset']);
$newcars = get_cars('https://abcdefg.co.uk/service/search1/advert?size=5&cursor_offset='.$results['cursorOffset'], $token);
$cars = array_merge($cars, $newcars);
//array_push($cars, $results['_embedded']['results']);
}
(and get_cars should return $cars, instead of printing it with print_r)
Edit: here is an example of, untested, code with a while loop (no need for do+while here)
<?php
function get_cars($baseUrl, $token)
{
$cars = [];
// set default url to call (1st call)
$url = $baseUrl;
while (!empty($url))
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => $url,
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(
"Content-Type: application/x-www-form-urlencoded",
"Authorization: Bearer " . $token
)
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if($err)
{
// it was "return false" in your code
// what if it's the 3rd call that fails ?
// - "return $cars" will return cars from call 1 and 2 (which are OK)
// - "return false" will return no car (but call 1 and 2 were OK !!)
return $cars;
}
$results = json_decode($response, TRUE);
$cars[] = $results['_embedded']['results'];
if(isset($results['cursorOffset']))
{
// next call will be using this url
$url = $baseUrl . '&cursor_offset='.$results['cursorOffset'];
// DONT DO THE FOLLOWING (concatenating with $url, $url = $url . 'xxx')
// you will end up with url like 'http://example.com/path/to/service?cursor_offset=xxx&cursor_offset==yyy&cursor_offset==zzz'
// $url = $url . '&cursor_offset='.$results['cursorOffset'];
}
else
{
$url = null;
}
}
return $cars;
}

Problem getting post data in API via php curl call

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;
}

file_get_contents return: sorry! something went wrong

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;
}

PHP file_get_contents booking.com Site

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;
}

Categories