Laravel 5.6 Ajax Post 500 Internal Server Error - php

Hello i am sending large string data via Ajax Post Request and its working fine on localhost but not working on live server i am sending some image data then this image data is converted to images on server..also its taking so much time to send this data average data size is between 4 to 7 MB..also can you suggest a better way so it can be done quickly..also things are setup properly i am including CSRF token and URL is also good but don't know why this error is occurring
Error => Status Code: 500 Internal Server Error
My controller code where i am sending request
$pid = $request->input('id');
$pt_id = $request->input('pt_id');
$pname = $request->input('name');
$isBack = $request->input('isBack');
$qty = $request->input('qty');
$paper = $request->input('paper');
$previewFront = $request->input('previewFront');
$previewBack = $request->input('previewBack');
$PrintDataFront = $request->input('PrintDataFront');
$PrintDataBack = $request->input('PrintDataBack');
$cart_item_id = uniqid();
//Store Img Data
$pf = str_replace('data:image/png;base64,', '', $previewFront);
$pf = str_replace(' ', '+', $pf);
$pf_n = $cart_item_id.'_f_.'.'png';
\File::put(public_path(). '/cart_preview/' . $pf_n, base64_decode($pf));
$pb = str_replace('data:image/png;base64,', '', $previewBack);
$pb = str_replace(' ', '+', $pb);
$pb_n = $cart_item_id.'_b_.'.'png';
\File::put(public_path(). '/cart_preview/' . $pb_n, base64_decode($pb));
$pdf = str_replace('data:image/png;base64,', '', $PrintDataFront);
$pdf = str_replace(' ', '+', $pdf);
$pdf_n = $cart_item_id.'_f_.'.'png';
\File::put(public_path(). '/orders/' . $pdf_n, base64_decode($pdf));
$pdb = str_replace('data:image/png;base64,', '', $PrintDataBack);
$pdb = str_replace(' ', '+', $pdb);
$pdb_n = $cart_item_id.'_b_.'.'png';
\File::put(public_path(). '/orders/' . $pdb_n, base64_decode($pdb));
//Get Prices and qty
$opriceitem = PriceTableItem::find($qty);
$itemQty = $opriceitem->qty;
$basePrice = $opriceitem->total;
if($isBack == 'true') {
$backPrice = $opriceitem->total_back;
$itemPrice = $opriceitem->total + $opriceitem->total_back;
$pricePerPiece = $opriceitem->item_price + $opriceitem->item_price_back;
}else {
$backPrice = 'INCLUDED';
$itemPrice = $opriceitem->total;
$pricePerPiece = $opriceitem->item_price;
}
if($paper == 'Premium White') {
$paperPrice = ($itemPrice/100) *60;
$itemPrice = $itemPrice + ($itemPrice/100) *60;
} else {
$paperPrice = 'INCLUDED';
}
//Get all Available Qty
$allQty = PriceTableItem::where('tid', $pt_id)->get();
$allAvailableQty = array();
foreach($allQty as $allqtyarry) {array_push($allAvailableQty, $allqtyarry->qty);}
//Create Cart Object
$item = [
"id" => $cart_item_id,
"pid" => $pid,
"name" => $pname,
"qty" => $itemQty,
"price_table_id" => $pt_id,
"paperType" => $paper,
"backCharges" => $backPrice,
"paperCharges" => $paperPrice,
"isBack" => $isBack,
"pricePerPiece" => $pricePerPiece,
"basePrice" => $basePrice,
"totalPrice" => $itemPrice,
"allQty" => $allAvailableQty,
];
$request->session()->put('cart.items.' . $cart_item_id, $item);
return 'Success';

Blockquote
Are you getting only error 500 and nothing else? If so, enable debug so you can get better description of the error. Make sure your php.ini file is set up properly and also permissions are fine for your server folders (I always get problems with the storage folder).

Related

UPS Shipment API. Can't make multipackage shipment

I downloaded UPS Shipping API for PHP from DEV center.
Everything woks, except I can make only 1 package shipment. But i need to make multipackage shipments.
There has to be few tags with all Child info for each box in shipment.
But due to tags name are array keys, i can't make duplicate tags.
Can anyone help me to solve this?
<?php
//Configuration
$access = "xxx";
$userid = "xxx";
$passwd = "A123xxx
$wsdl = "WSDLs_Shipping/Ship.wsdl";
$operation = "ProcessShipment";
$endpointurl = 'https://wwwcie.ups.com/webservices/Ship';
//$endpointurl = 'https://onlinetools.ups.com/webservices/Ship';
$outputFileName = "XOLTResult.xml";
function processShipment()
{
//create soap request
$requestoption['RequestOption'] = 'nonvalidate'; //Valid values: nonvalidate = No street level address validation would be performed, but Postal Code/State combination validation would still be performed. validate = No street level address validation would be performed, but City/State/Postal Code/ combination validation would still be performed.
$request['Request'] = $requestoption;
$shipment['Description'] = 'Spare parts'; //The Description of Goods for the shipment. Applies to international and domestic shipments. Provide a detailed description of items being shipped for documents and non-documents. Examples: "annual reports" and "9 mm steel screws".
$shipper['Name'] = 'FD'; //Shippers company name. For forward Shipment 35 characters are accepted, but only 30 characters will be printed on the label.
$shipper['AttentionName'] = 'Andriy'; //попробую убрать Shippers Attention Name. For forward Shipment 35 characters are accepted, but only 30 characters will be printed on the label.
//$shipper['TaxIdentificationNumber'] = '123456'; //Shipper’s Tax Identification Number. Conditionally required if EEI form (International forms) is requested and ship From is not mentioned.
$shipper['ShipperNumber'] = 'xxxxxx'; //Account number
$address['AddressLine'] = 'Polevaya 61a'; //The Shipper street address including name and number (when applicable). Up to three occurrences are allowed; only the first is printed on the label. 35 characters are accepted, but for the first occurrence, only 30 characters will be printed on the label for return shipments.
$address['City'] = 'Kiev';
//$address['StateProvinceCode'] = 'MD'; //Shipper's state or province code. For forward Shipment 5 characters are accepted, but only 2 characters will be printed on the label.For US, PR and CA accounts, the account must be either a daily pickup account, an occasional account, or a customer B.I.N account.
$address['PostalCode'] = '03067';
$address['CountryCode'] = 'UA';
$shipper['Address'] = $address;
$phone['Number'] = '+38067611212';
$phone['Extension'] = '';
$shipper['Phone'] = $phone;
$shipment['Shipper'] = $shipper;
$shipment['ReturnService'] = '1';
$ReturnService['Code'] = '8'; //Return Service types: 2 = UPS Print and Mail (PNM) 3 = UPS Return Service 1-Attempt (RS1) 5 = UPS Return Service 3-Attempt (RS3) 8 = UPS Electronic Return Label (ERL)
$shipment['ReturnService'] = $ReturnService;
//$package['Description'] = 'descr';
$shipto['Name'] = 'Vitaliy '; //Consignee’s company name.
$shipto['AttentionName'] = 'Vitaliy '; //Contact name at the consignee’s location.
$addressTo['AddressLine'] = 'Polevaya 61A'; //Address Line of the consignee. Required: Yes Type: String Max Allowed: 3 Length: 1…35.Max occurrence: 3 Only first two Address Lines will be printed on the label.
$addressTo['City'] = 'Kiev';
$addressTo['PostalCode'] = '03058';
$addressTo['CountryCode'] = 'UA';
$phone2['Number'] = '064655544';
$shipto['Address'] = $addressTo;
$shipto['Phone'] = $phone2;
$shipment['ShipTo'] = $shipto;
$shipfrom['Name'] = ' Sender 1'; //The ship from location’s name or company name. 35 characters are accepted, but for return Shipment only 30 characters will be printed on the label.
$shipfrom['AttentionName'] = 'Sender 1'; //The ship from Attention name. 35 characters are accepted, but for return Shipment only 30 characters will be printed on the label.
$addressFrom['AddressLine'] = '2311 York Rd'; //The Ship from street address including name and number (when applicable). 35 characters are accepted, but for return Shipment only 30 characters will be printed on the label. Required: Yes* Type: String Max Allowed: 3 Length: 1…35. Max occurrence: 3
$addressFrom['City'] = 'Timonium';
//$addressFrom['StateProvinceCode'] = 'MD'; //Origin locations state or province code. Required if ShipFrom tag is in the XML, and ShipFrom Country or territory is US. If ShipFrom country or territory is US or CA, then the value must be a valid US State/ Canadian Province code. If the country or territory is Ireland, the StateProvinceCode will contain the county.
$addressFrom['PostalCode'] = '21093';
$addressFrom['CountryCode'] = 'CN';
$phone3['Number'] = '1234567890';
$phone3['Extension'] = '';
$shipfrom['Address'] = $addressFrom;
$shipfrom['Phone'] = $phone3;
$shipment['ShipFrom'] = $shipfrom;
$shipmentcharge['Type'] = '01';
//$billshipper['CreditCard'] = $creditcard;
$billshipper['AccountNumber'] = 'xxxxxx';
$shipmentcharge['BillShiper'] = 'xxxxxx';
$shipmentcharge['BillShipper'] = $billshipper;
$paymentinformation['ShipmentCharge'] = $shipmentcharge;
$shipment['PaymentInformation'] = $paymentinformation;
$service['Code'] = '65';
$service['Description'] = 'Express Saver';
$shipment['Service'] = $service;
$product['NumberOfPackagesPerCommodity'] = '2';
$internationalForm['Product'] = $product;
$shpServiceOptions['InternationalForms'] = $internationalForm;
$shipment['ShipmentServiceOptions'] = $shpServiceOptions;
$shpLabelDeliveryEmail[LabelLinksIndicator] = ''; //Попробуем, чтобы прислало ссылку на ярлык
$EmailLabelDelivery[EMailAddress] = 'admin#test.ua';
$EmailLabelDelivery[UndeliverableEMailAddress] = 'admin#test.ua';
$EmailLabelDelivery[FromEMailAddress] = 'admin#test.ua';
$shpLabelDeliveryEmail[EMail] = $EmailLabelDelivery;
$shpLabelDelivery[LabelDelivery] = $shpLabelDeliveryEmail;
$shipment['ShipmentServiceOptions'] = $shpLabelDelivery;
$package['Description'] = 'desc'; //Merchandise description of package.Required for shipment with return service.
$packaging['Code'] = '02'; //02 = Customer Supplied package
$packaging['Description'] = 'Nails'; //Description of packaging type. Examples are letter, customer supplied, express box.
$package['Packaging'] = $packaging;
$unit['Code'] = 'CM';
$unit['Description'] = 'CM';
$dimensions['UnitOfMeasurement'] = $unit;
$dimensions['Length'] = '50';
$dimensions['Width'] = '50';
$dimensions['Height'] = '20';
$package['Dimensions'] = $dimensions;
$unit2['Code'] = 'KGS';
$unit2['Description'] = 'KGS';
$packageweight['UnitOfMeasurement'] = $unit2;
$packageweight['Weight'] = '10';
$package['PackageWeight'] = $packageweight;
$shipment['Package'] = $package;
//$shipment['NumOfPiecesInShipment'] = '3';
$labelimageformat['Code'] = 'GIF';
$labelimageformat['Description'] = 'GIF';
$labelspecification['LabelImageFormat'] = $labelimageformat;
$labelspecification['HTTPUserAgent'] = 'Mozilla/4.5';
$shipment['LabelSpecification'] = $labelspecification;
//print_r($shipment1);
// $shipment['DocumentsOnlyIndicator'] = '1'; // IF ONLY documents
$request['Shipment'] = $shipment;
echo "Request.......\n";
print_r($request);
echo "\n\n";
return $request;
}
function processShipConfirm()
{
//create soap request
}
function processShipAccept()
{
//create soap request
}
try
{
$mode = array
(
'soap_version' => 'SOAP_1_1', // use soap 1.1 client
'trace' => 1
);
// initialize soap client
$client = new SoapClient($wsdl , $mode);
//set endpoint url
$client->__setLocation($endpointurl);
//create soap header
$usernameToken['Username'] = $userid;
$usernameToken['Password'] = $passwd;
$serviceAccessLicense['AccessLicenseNumber'] = $access;
$upss['UsernameToken'] = $usernameToken;
$upss['ServiceAccessToken'] = $serviceAccessLicense;
$header = new SoapHeader('http://www.ups.com/XMLSchema/XOLTWS/UPSS/v1.0','UPSSecurity',$upss);
$client->__setSoapHeaders($header);
if(strcmp($operation,"ProcessShipment") == 0 )
{
//get response
$resp = $client->__soapCall('ProcessShipment',array(processShipment()));
//get status
echo "Response Status: " . $resp->Response->ResponseStatus->Description ."\n";
//save soap request and response to file
$fw = fopen($outputFileName , 'w');
fwrite($fw , "Request: \n" . $client->__getLastRequest() . "\n");
fwrite($fw , "Response: \n" . $client->__getLastResponse() . "\n");
fclose($fw);
}
else if (strcmp($operation , "ProcessShipConfirm") == 0)
{
//get response
$resp = $client->__soapCall('ProcessShipConfirm',array(processShipConfirm()));
//get status
echo "Response Status: " . $resp->Response->ResponseStatus->Description ."\n";
//save soap request and response to file
$fw = fopen($outputFileName , 'w');
fwrite($fw , "Request: \n" . $client->__getLastRequest() . "\n");
fwrite($fw , "Response: \n" . $client->__getLastResponse() . "\n");
fclose($fw);
}
else
{
$resp = $client->__soapCall('ProcessShipeAccept',array(processShipAccept()));
//get status
echo "Response Status: " . $resp->Response->ResponseStatus->Description ."\n";
//save soap request and response to file
$fw = fopen($outputFileName ,'w');
fwrite($fw , "Request: \n" . $client->__getLastRequest() . "\n");
fwrite($fw , "Response: \n" . $client->__getLastResponse() . "\n");
fclose($fw);
}
}
catch(Exception $ex)
{
print_r ($ex);
}
?>
Check this one UPS API wsdl soap call - cannot set multiple packages
Your problematic code:
$package['Description'] = 'desc'; //Merchandise description of package.Required for shipment with return service.
$packaging['Code'] = '02'; //02 = Customer Supplied package
$packaging['Description'] = 'Nails'; //Description of packaging type. Examples are letter, customer supplied, express box.
$package['Packaging'] = $packaging;
$unit['Code'] = 'CM';
$unit['Description'] = 'CM';
$dimensions['UnitOfMeasurement'] = $unit;
$dimensions['Length'] = '50';
$dimensions['Width'] = '50';
$dimensions['Height'] = '20';
$package['Dimensions'] = $dimensions;
$unit2['Code'] = 'KGS';
$unit2['Description'] = 'KGS';
$packageweight['UnitOfMeasurement'] = $unit2;
$packageweight['Weight'] = '10';
$package['PackageWeight'] = $packageweight;
$shipment['Package'] = $package; //Where is the second package?
Something like this should work:
$package['Shipment']['Package'] = array();
foreach ($packaging as $p) {
$pkg = array();
$pkg['PackagingType'] = array(
'Code' => '02',
'Description' => 'Nails'
);
$pkg['PackageWeight'] = array(
'Weight' => (int)$p["weight"],
'UnitOfMeasurement' => array('Code' => 'KGS', 'Description' => 'KGS')
);
$pkg['Dimensions'] = array(
'Length' => (int)$p["length"],
'Width' => (int)$p["width"],
'Height' => (int)$p["height"],
'UnitOfMeasurement' => array('Code' => 'CM', 'Description' => 'CM')
);
array_push($package['Shipment']['Package'], $pkg);
}

JSON increment doesn't work

I am working on a JSON file in which I want to increment instead of overwriting the data. However I cannot seem to do this (since it keeps on overwriting instead of adding data with an incremented ID).
The code underneath is: database_json.php (as u can see I include it in saveJson.php)
$databaseFile = file_get_contents('json_files/database.json');
$databaseJson = json_decode($databaseFile, true);
$database = $databaseJson['data'];
the below is the code of the file saveJson.php contains the following code:
// below starts a new page, the page that submits the form called saveJson.php
include_once('database_json.php');
$data = $_POST;
//Setup an empty array.
$errors = array();
if (isset($data)) {
$newExerciseData = $data;
$exerciseArray = $data['main_object'];
$databaseFile = 'json_files/database.json';
$textContent = file_get_contents($databaseFile);
$database = json_decode($textContent, true);
if ($data['id'] === 'new') {
if (count($database['data']) == 0) {
$ID = 0;
}
else {
$maxID = max($database['data']);
$ID = ++$maxID["id"];
}
$newJsonFile = 'jsonData_' . $ID . '.json';
$newJsonFilePath = 'json_files/' . $newJsonFile;
//Create new database exercise_txt
$newArrayData = array(
'id' => $ID,
// a lot of variables that aren't related to the problem
);
$database['data'][] = $newArrayData;
file_put_contents($databaseFile, json_encode($database, JSON_UNESCAPED_UNICODE, JSON_PRETTY_PRINT));
file_put_contents($newJsonFilePath, json_encode($newExerciseData, JSON_UNESCAPED_UNICODE, JSON_PRETTY_PRINT));
}
else {
$index = array_search((int) $_POST['id'], array_column($database['data'], 'id'));
$correctJsonFile = 'json_files/jsonData_' . $_POST['id'] . '.json';
$newJsonFile = 'jsonData_' . $_POST['id'] . '.json';
$newJsonFilePath = 'json_files/' . $newJsonFile;
//Create new database exercise_txt
$newArrayData2 = array(
'id' => (int) $_POST['id'],
// more not related to problem variables
);
$database['data'][$index] = $newArrayData2;
file_put_contents($databaseFile, json_encode($database, JSON_UNESCAPED_UNICODE));
file_put_contents($newJsonFilePath, json_encode($newExerciseData, JSON_UNESCAPED_UNICODE));
}
echo json_encode($newExerciseData, JSON_UNESCAPED_UNICODE);
}
so, what I wish for: To increment the IDs and NOT to overwrite the data.
I already did some research and didn't find any useful information besides this --> Auto increment id JSON, but to me it looks like I have the same principle applied.

Persist filter values in codeigniter with pagination library

I use the default codeiginter pagination library. I tried implementing this in a previously created page which shows all vacancies, but since we are getting TOO many on the site, the performance is terrible. This is why I need pagination on this page. Note that this is not the cleanest solution, there is a new track going on which overhauls the entire page and starts from scratch. This is a quick & dirty solution because we need to keep it working on our live environment until the rework is done.
This is the controller code I have:
public function overviewVacancies($city = null)
{
$this->is_logged_in();
// Load Models
$this->load->model('vacancy/vacancies_model');
$this->load->model('perk/interests_model');
$this->load->model('perk/engagement_model');
$this->load->model('user/userSavedVacancies_model');
// Passing Variables
$data['title'] = lang("page_title_activities_overview");
$data['description'] = lang('meta_desc_activities');
$data['class'] = 'vacancy';
$data['engagements'] = $this->engagement_model->getAll();
$data['interests'] = $this->interests_model->getAllInterests();
$data['bread'] = $this->breadcrumbmanager->getDashboardBreadcrumb($this->namemanager->getDashboardBreadName("0"), $this->namemanager->getDashboardBreadName("1"));
$data['tasks'] = $this->interests_model->getAllTasks();
// Set session data
$this->session->set_userdata('previous',"http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]");
$this->session->set_userdata('previous-title', "1");
$filterdata = array(
'interests' => $this->input->post('interests'),
'skills' => $this->input->post('skills'),
'fulldate' => $this->input->post('daterange'),
'location' => $this->input->post('location'),
'city' => $this->input->post('sublocality_level_1'),
'capital' => $this->input->post('locality')
);
if (!empty($filterdata['interests'])) {
$filterdata['interests'] = rtrim($filterdata['interests'], ";");
$filterdata['interests'] = str_replace(' ', '', $filterdata['interests']);
$filterdata['interests'] = str_replace(';', ',', $filterdata['interests']);
}
if (!empty($filterdata['skills'])) {
$filterdata['skills'] = str_replace(' ', '', $filterdata['skills']);
$filterdata['skills'] = explode(",", $filterdata['skills']);
}
//Manually clear the commune and city variables if the location was empty
if (empty($filterdata['location'])) {
$filterdata['city'] = '';
$filterdata['capital'] = '';
}
if($city == null){
$orgId = $this->organization_model->getOrgIdByName(LOCATION);
}
else{
$orgId = $this->organization_model->getOrgIdByName($city);
$data['bread'] = $this->breadcrumbmanager->getLocalBreadcrumb($this->namemanager->getDashboardBreadName("0"), $city, $data['title'], $data['vacancydetails']);
}
//Set the location to the subdomain automatically (e.g. when the link is clicked) so the activities of that subdomain only show up
if (!empty(LOCATION)) {
$data['title'] = sprintf(lang('page_title_local_activities'), ucwords(LOCATION));
$data['description'] = sprintf(lang('meta_desc_local_activities'), ucwords(LOCATION));
$filterdata['location'] = LOCATION;
$data['bgcolor'] = $this->localSettings_model->getBgColorHexValueForOrgId($orgId->org_id);
}
if (!empty($filterdata['fulldate'])) {
$splitfromandto = explode(" - ", $filterdata['fulldate']);
$filterdata['datefrom'] = $splitfromandto[0];
$filterdata['dateto'] = $splitfromandto[1];
} else {
$filterdata['datefrom'] = null;
$filterdata['dateto'] = null;
}
//Put these variables in the data variable so we can prefill our filters again with the previous values
//This is necessary because we don't use AJAX yet
$data['filterdata'] = $filterdata;
//Pagination : We do it here so we can re-use the filter query to count all our results
$this->load->library('pagination');
$data['all_vacancies'] = $this->vacancies_model->getFilteredVacancies($filterdata);
$pagconfig['base_url'] = base_url().VACANCY_OVERVIEW;
$pagconfig['total_rows'] = count($data['all_vacancies']);
$pagconfig['per_page'] = 1;
$pagconfig['uri_segment'] = 2;
$pagconfig['use_page_numbers'] = TRUE;
$this->pagination->initialize($pagconfig);
$data['links'] = $this->pagination->create_links();
$start = max(0, ( $this->uri->segment(2) -1 ) * $pagconfig['per_page']);
//This variable contains all the data necessary for a vacancy to be displayed on the vacancy overview page
$data['vacancies'] = $this->vacancies_model->getFilteredVacancies($filterdata, false, null, false, null, false, false, $pagconfig['per_page'], $start);
// Template declaration
$partials = array('head' => '_master/header/head', 'navigation' => '_master/header/navigation_dashboard', 'content' => 'dashboard/vacancy/overview', 'footer' => '_master/footer/footer');
$data['vacancygrid'] = $this->load->view('dashboard/vacancy/vacancygrid', $data, TRUE);
$this->template->load('_master/master', $partials, $data);
}
As you can see in the code i keep a variable called $filterdata, this contains all data which is used in our filters, since we don't use AJAX in this version, we need to pass it to the view every time to fill it up again and present it to the visitor.
However, using pagination this breaks because it just reloads my controller method and thus the values in $filterdata are lost.
How do I go about this?
Note: it does not have to be a clean solution, it just needs to work since this page is going offline in a couple of weeks anyway.
Thanks a lot in advance!

Forecast.io service unavailable

I am using forecast.io API to deliver weather data to my website. Sometimes the forecast.io API is down, which causes every single page on my website which uses the forecast.io API to return "Service Unavailable, unable to get file content errors"
This is what I'm using to gather the weather data from the API
<?php
include("assets/php/forecast.php");
$api_key = '123123123';
$latitude = $data->getLatitude();
$longitude = $data->getLongitude();
$forecast = new ForecastIO($api_key);
/*
* GET CURRENT CONDITIONS
*/
$condition = $forecast->getCurrentConditions($latitude, $longitude);
$temp = $condition->getTemperature();
$temp = $temp + 2;
$summ = $condition->getSummary();
$icon = $condition->getIcon();
$icon2 = $condition->getIcon();
$icon = str_replace('-', '_', $icon);
$icon2 = str_replace('-', ' ', $icon2);
$icon = strtoupper($icon);
$icon2 = ucfirst($icon2);
?>
I would like to include some sort of error handler where if the forecast.io API is unavailable, then this code doesn't get called.
This is the site where I had the problem
https://seek.estate/
https://seek.estate/buy/422-melbournes-most-liveable-home-sea-views-elevator-designer-masterpiece
This is what I changed
$forecast = new ForecastIO($api_key);
$request_url = 'https://api.forecast.io/forecast/';
$content = file_get_contents($request_url);
if (!empty($content)) {
return condition = $forecast->getCurrentConditions($latitude, $longitude);
} else {
return false;
}

Simple PHP Cache - Can store data in array but how to retrieve items from that array cache?

I've been able to use the store function of this caching class but I am unable to retrieve a certain item out of the stored array.
$c->setCache("$appid")
->store("$appid", array(
'name' => "$gname",
'price' => "$price",
'logo' => "$glogo",
'link' => "$glink"
)
);
$gcache = $c->retrieve("$appid");
$cprice = $gcache->price; //not sure how to retrieve the price value only
https://github.com/cosenary/Simple-PHP-Cache
Here is the full code where I cannot seem to get the price from the stored array:
<?php
require_once 'cache.class.php';
// Setup 'default' Cache
$c = new Cache();
$glist = "http://steamcommunity.com/id/aksn1p3r/games?tab=all&xml=1";
$gxml = simplexml_load_file($glist);
$tprice = 0;
$i = 0; //just used to exit loop after 2 executions
foreach($gxml->games->game as $game) {
if($i >= 2) {
break;
}
$appid = $game->appID;
$glink = $game->storeLink;
$gname = $game->name;
$glogo = $game->logo;
$gjson = 'http://store.steampowered.com/api/appdetails/?appids=' . $appid;
$fgc = file_get_contents($gjson);
$jd = json_decode($fgc, true);
$gdata = $jd[intval($appid)]['data']; //$appid needs to be integer here, not string
$gdesc = $gdata['about_the_game'];
$gprice = $gdata['price_overview']['final'];
$price = number_format($gprice / 100, 2);
$c->setCache("$appid")
->store("$appid", array(
'name' => "$gname",
'price' => "$price",
'logo' => "$glogo",
'link' => "$glink"
)
);
// this part is where I dont understand how to get the price I stored.
$cprice = $c->retrieve["$appid"]['price'];
$tprice += $cprice;
$i++;
}
echo 'Total games: ' .$i. ' <br>';
echo 'Total Price: ' .$tprice;
?>
You are storing array expecting to get object
Replace
$gcache->price;
with
$gcache['price'];

Categories