Why is necessary two requests to transfer the file? - php

I have this method below to download a file from an API server. But its not working properly, when the user clicks in the button that calls the getFile() method it appears at first in the page the error
Trying to get property of non-object
But if the user click in the browser refresh button the file is downloaded.
So it seems that for the file be generated is necessary send two requests and in the first appears
Trying to get property of non-object
In the second the file is transfered, in the third it appears again
Trying to get property of non-object
In the API says that to download the file is an asynchronous operation, which means that the file may not be ready immediately. I dont know if the issue can be because of that.
Code:
public function getFile($regId){
$client = new \GuzzleHttp\Client();
$user = Auth::user();
$registration = $user->registrations()->with(["proforma"])->where("id", $regId)->first();
$proforma = $registration->proforma->proforma_number;
$getProforma = $client->request('GET', 'https://...'.$proforma.'.json', [
'query' => ['api_key' => '...'],
]);
$response = $getProforma->getBody()->getContents();
$url = null;
if(!empty($response)) {
$response = json_decode($response);
$url = !empty($response->output->pdfUrl) ? $response->output->pdfUrl : '';
}
header("Location: $url");
}

public function getFile($regId)
{
$registration = auth()->user()->registrations()->with(["proforma"])->where("id", $regId)->first();
$proforma = $registration->proforma->proforma_number;
$getProforma = json_decode(file_get_contents('https://...' . $proforma . '.json?api_key=.....'));
// $getProforma->output here was your problem so I advice you to: dd($getProforma);
$url = ! empty(optional($getProforma->output)->pdfUrl) ? optional($getProforma->output)->pdfUrl : '/'; // it will redict home if it couldn't find the PDF URL
return redirect($url);
}

Related

How to run an independent PHP script in Laravel?

I am new to laravel and PHP, so I apologize if something similar is asked before which I couldn't find as per my needs. I have an independent PHP script in public folder:
define('DB_HOST','localhost');
define('DB_USER','root');
define('DB_PASS','');
define('DB_NAME','fyp');
define('API_ACCESS_KEY', 'AAAAk4V5b8k:APA91bFUo5crCI-gmfhlB9znAWpxdy9bdvA-29VBgLdRmQtYvjNuUe4xi7lkmyAmTOuhuCaaSphaGTvULTq6oREJEUwNNRBW9AKiadl9zzjbXFnEwINlfJzGFIpZojWim2cTT2D7rKJz');
//$registrationIds = 'f4tul16ETjK6wR64Nix7HO:APA91bGPa4ijApEp_vrDcAr-NEzUU-WcovjLhpxtwSiNv94aZ-aOMVek0AbTHNFHCmwZrXOzeqocFglWOlABWcjcDXnDdmh2qEsIgh0X7MkXcN_YD6qBREP5QyS1WlGn27qGiyYTdpoV';
$id = $_POST['id'];
$status = $_POST['status'];
$case_id = $_POST['case_id'];
What I want is to pass the values to this script and execute when I press a button on my page e.g.
When I press save, the following function in the controller executes:
public function storedetail(Request $req, $id)
{
$detail = Detail::firstOrNew(['case_id' => $id,]);
$detail->lawyerName = $req->input('lawyerName');
$detail->event = $req->input('proc_type');
$detail->room = $req->input('room');
$detail->eventDate = $req->input('date');
$detail->status = 1;
// $data = Cases::find($id);
$detail->case_id = $id;
// $data->details()->save($detail);
$detail->save();
return redirect()->back();
}
What is the simplest way to pass the id, status and case_id to the PHP script and execute it?
As per I understand you just need to pass data from laravel controller to separate php file.
just pass all the parameters to the specific file path.
ex : xyz.com/public/phpfile.php?id=123&status=abc&case_id=45

Navigating forms and grabbing DOM-Elements from a website using Guzzle/Goutte (PHP, Debugging)

I'm fairly new to PHP and playing around with Goutte/Guzzle to grab some basic information from a website after filling out a few forms.
However I have problems finding issues (there might be a ton of them) since I could not find a way to display or console log any of the results or problems. The script finishes with Code 0 but does not return anything. A tip on how to print out what is currently stored in $client would already go a long way.
Here is the whole code I'm trying to run with a bunch of comments for clarification. I'm sorry for using such a large block, but any of this could have issues.
<?php
use Goutte\Client;
use GuzzleHttp\Client as GuzzleClient;
class grabPlate
{
// WKZ
public function checkPlate
{
$goutteClient = new Client();
$guzzleClient = new GuzzleClient(array(
'cookies' => true,
'timeout' => 60,
));
$goutteClient->setClient($guzzleClient);
$crawler = $goutteClient->request('GET', 'https://kfz-portal.berlin.de/kfzonline.public/start.html?oe=00.00.11.000000');
//Click the first "Start" in the top left
$link = $crawler
->filter('a:contains("Start")')
->eq(0)
->link()
;
$crawler = $client->click($link);
//Check checkbox, fill in name and press the button
$buttonCrawlerNode = $crawler->selectButton('Weiter');
$form = $buttonCrawlerNode->form();
$form['gwt-uid-1']->tick();
$form['select2-hidden-accessible']->select('Herr');
$form['gwt-uid-4'] = 'John';
$form['gwt-uid-5'] = 'Doe';
$client->submit($form);
//Fill some Data into the forms and search
$buttonCrawlerNode = $crawler->selectButton('Button-3616');
$form = $buttonCrawlerNode->form();
$form['.kfzonline-KennzeichenGrossEb'] = 'AB';
$form['.kfzonline-KennzeichenGrossEn'] = '123';
$client->submit($form);
//Extract collection
$info = $crawler->extract('.collection');
//return 1 if something is inside collection, 0 if it's empty
if($info == NULL) {
return 1;
} else {
return 0;
}
}
}
?>
As I said just running the script in PHPStorm returns the status 0. However when plugging it into an API and accessing it, I get a server timeout response.
You should either use a Debugging. Install xDebug to do so in PHP. This is also easy to integrate into Phpstorm.
Alternatively use var_dump() for printing out debug information about variables of any type to console.
You can display the requested page inside your php page, you have to add this snippet :
$client = new GuzzleHttp\Client();
$res = $client->request('GET', 'https://www.facebook.com/');
echo $res->getBody();

Dropbox api not working in codiegniter?

public function request_dropbox()
{
$params['key'] = 'gr3kempuvsiqsli';
$params['secret'] = 'qtdl8lmm9r0rlk1';
$this->load->library('dropbox', $params);
$data = $this->dropbox->get_request_token(base_url());
$this->session->set_userdata('token_secret', $data['token_secret']);
redirect($data['redirect']);
}
//This method should not be called directly, it will be called after
//the user approves your application and dropbox redirects to it
public function access_dropbox()
{
$params['key'] = 'gr3kempuvsiqsli';
$params['secret'] = 'qtdl8lmm9r0rlk1';
$this->load->library('dropbox', $params);
$oauth = $this->dropbox->get_access_token($this->session->userdata('token_secret'));
$this->session->set_userdata('oauth_token', $oauth['oauth_token']);
$this->session->set_userdata('oauth_token_secret', $oauth['oauth_token_secret']);
redirect('welcome/test_dropbox');
}
//Once your application is approved you can proceed to load the library
//with the access token data stored in the session. If you see your account
//information printed out then you have successfully authenticated with
//dropbox and can use the library to interact with your account.
public function test_dropbox()
{
$params['key'] = 'gr3kempuvsiqsli';
$params['secret'] = 'qtdl8lmm9r0rlk1';
$params['access'] = array('oauth_token'=>urlencode($this->session->userdata('oauth_token')),
'oauth_token_secret'=>urlencode($this->session->userdata('oauth_token_secret')));
$this->load->library('dropbox', $params);
$dbobj = $this->dropbox->account();
print_r($dbobj);
}
Blockquote
i have used Dropbox library https://github.com/jimdoescode/CodeIgniter-Dropbox-API-Library
When i call to function request_dropbox() it gives me error in api "Fatal error: Call to undefined function curl_init() in C:\xampp\htdocs\reports\application\libraries\Dropbox.php on line 478"
please help me how to access dropbox files.
Please look at your errors more carefully, it turns out that curl is not enabled on your Xampp environment.
This should help you out to enable CURL and get you going again.
How to enable curl in xampp?

SOAP error. Not getting correct structure returned

I have a website that contains a form that makes various SOAP requests at certain points. One of these requests gets a list of induction times returned and displays them to the user in order for them to pick one.
I am getting results returned fine from the SOAP service but unfortunately it seems to be not showing information correctly and even not displaying returned object keys at all.
I have liased with one of the devs at the SOAP end and he says the service is fine and spitting out the cirrect information. He has provided a screentshot:
Here is my code to pull call the method I need for this information:
public function getInductionTimes($options) {
$client = $this->createSoapRequest();
$inductionTimes = $client->FITinductionlist($options);
//die(print_r($inductionTimes));
return $inductionTimes;
}
private function createSoapRequest() {
$url = 'https://fitspace.m-cloudapps.com:444/FITSPACE/MHservice.asmx?WSDL';
$options["connection_timeout"] = 25;
$options["location"] = $url;
$options['trace'] = 1;
$options['style'] = SOAP_RPC;
$options['use'] = SOAP_ENCODED;
$client = new SoapClient($url, $options);
//die(print_R($client->__getFunctions()));
return $client;
}
As you can see I print_r the code right after I have received it to check what I am getting returned and it is this:
As you can see this IDdtstring field is getting completely ignored.
Does anyone have any ideas as to why this may be happening? Is it something to do with encoding? I can't seem to get anywhere on this issue!
Thanks
I was able to retrieve the fields correctly, including IDdtstring, using your basic code. Perhaps you are not sending the parameters correctly?
function getInductionTimes($options) {
$client = createSoapRequest();
$inductionTimes = $client->FITinductionlist($options);
die(print_r($inductionTimes));
return $inductionTimes;
}
function createSoapRequest() {
$url = 'https://fitspace.m-cloudapps.com:444/FITSPACE/MHservice.asmx?WSDL';
$options["connection_timeout"] = 25;
$options["location"] = $url;
$options['trace'] = 1;
$options['style'] = SOAP_RPC;
$options['use'] = SOAP_ENCODED;
$client = new SoapClient($url, $options);
//die(print_R($client->__getFunctions()));
return $client;
}
getInductionTimes(array("IDDate" => "2013-06-28T13:00:00+01:00", "GYMNAME" => "Bournemouth"));
I managed to solve this issue by adding the line of code into my SOAP options array which I then presume was an issue with my WSDL being cached in PHP:
$options['cache_wsdl'] = WSDL_CACHE_NONE;

Why is JSON not being returned from GiantBomb API

Im trying to use the GiantBomb api to query video games, and currently when I enter the URL into a browser, it works just fine. The Json data shows up.
Heres an example url..
http://www.giantbomb.com/api/search/?api_key=83611ac10d0dfghfgh157177ecb92b0a5a2350c59a5de4&query=Mortal+Kombat&format=json
But when I try to use my php wrapper that Im just starting to build, it returns html??
Heres the start of my wrapper code....(very amateur for now)
You'll notice in the 'request' method, Ive commented out the return for json_decode($url), because when I uncomment it, the page throws a 500 error??? So I wanted to see what happends when I just echo it. And it echos an html page. Surely it should just echo what is shown, when you just enter that url into the browser, no?
However...if I replace the url with say a GoogleMap url, it echoes out Json data just fine, without using json_decode. Any ideas as to wahts going on here????
class GiantBombApi {
public $api_key;
public $base_url;
public $format;
function __construct() {
$this->format="&format=json";
$this->api_key = "83611ac10d0d157177ecb92b0a5a2350c59a5de4";
$this->search_url = "http://www.giantbomb.com/api/search/?api_key=".$this- >api_key."&query=";
}
public function search($query){
$query = urlencode($query);
$url = $this->search_url.$query.$this->format;
return $this->request($url);
}
public function request($url) {
$response = file_get_contents($url);
echo $response;
//return json_decode($response, true);
}
}
//TESTING SECTION
$games = new GiantBombApi;
$query = $_GET['search'];
echo $games->search($query);
I ran a few requests through Postman and it seems that the api looks at the mime-type as well as the query string. So try setting a header of "format" to "json".

Categories