How to parse and write .ini file in codeigniter PHP? - php

I am uploading a INI file in Codeigniter.
I file upload a file with some parameters but its values are blank, and i store the file and file-path in database.
Now, I want to let user write some values to that file.
So i open the file and let user add some values to it.
But when i save the file its doesn't get stored the way i want.
Current Result
SipUserName = ""
SipAuthName = ""
DisplayName = ""
Password = ""
Domain = ""
Proxy = ""
Port = ""
ServerMode = ""
UCServer = 123456
UCPassword = 123456
DP_Exception = 123456
DP_Rule1 = 123456
DP_Rule2 = 123456
OperationMode = 123456
MutePkey = 123456
Codec = 123456
PTime = 123456
AudioMode = 123456
SoftwareAEC = 123456
EchoTailLength = 123456
PlaybackBuffer = 123456
CaptureBuffer = 123456
JBPrefetchDelay = 123456
JBMaxDelay = 123456
SipToS = ""
RTPToS = 123456
LogLevel = 123456
Expected Result:
[INIDetails]
SipUserName =
SipAuthName =
DisplayName =
Password =
Domain =
Proxy =
Port =
ServerMode =
UCServer = 123456
UCPassword = 123456
[DialPlan]
DP_Exception = 123456
DP_Rule1 = 123456
DP_Rule2 = 123456
[Advanced]
OperationMode = 123456
MutePkey = 123456
Codec = 123456
PTime = 123456
AudioMode = 123456
SoftwareAEC = 123456
EchoTailLength = 123456
PlaybackBuffer = 123456
CaptureBuffer = 123456
JBPrefetchDelay = 123456
JBMaxDelay = 123456
SipToS =
RTPToS = 123456
LogLevel = 123456
Below is my code:
public function edit_ini($id)
{
/*The ID wen get from View's URI*/
$path = "./uploads/";
$site = $this->session->userdata('site');
/*Set the path to open the file*/
$this->db->select('*');
$this->db->where('site_key',$site);
$this->db->where('id',$id);
/*Here the id it the ID we got in URI from View*/
$this->db->from('base_ini');
$query = $this->db->get();
$result = $query->row();
$filename= $result->base_ini_filename;
$path= $result->file_path;
echo $this->db->last_query();
/*Setting the Path and the filename from database.*/
file_get_contents($path.$filename);
/*Get All The Contents from that file*/
$this->data['params'] = $this->parameter_m->get();
/*Getting the parameters to display on view*/
$this->data['parameters'] = parse_ini_file($path.$filename,true);
$insert = array(
'SipUserName' => $this->input->post('SipUserName'),
'SipAuthName' => $this->input->post('SipAuthName'),
'DisplayName' => $this->input->post('DisplayName'),
'Password' => $this->input->post('Password'),
'Domain' => $this->input->post('Domain'),
'Proxy' => $this->input->post('Proxy'),
'Port' => $this->input->post('Port'),
'ServerMode' => $this->input->post('ServerMode'),
'UCServer' => $this->input->post('UCServer'),
'UCPassword' => $this->input->post('UCPassword'),
'DP_Exception' => $this->input->post('DP_Exception'),
'DP_Rule1' => $this->input->post('DP_Rule1'),
'DP_Rule2' => $this->input->post('DP_Rule2'),
'OperationMode' => $this->input->post('OperationMode'),
'MutePkey' => $this->input->post('MutePkey'),
'Codec' => $this->input->post('Codec'),
'PTime' => $this->input->post('PTime'),
'AudioMode' => $this->input->post('AudioMode'),
'SoftwareAEC' => $this->input->post('SoftwareAEC'),
'EchoTailLength' => $this->input->post('EchoTailLength'),
'PlaybackBuffer' => $this->input->post('PlaybackBuffer'),
'CaptureBuffer' => $this->input->post('CaptureBuffer'),
'JBPrefetchDelay' => $this->input->post('JBPrefetchDelay'),
'JBMaxDelay' => $this->input->post('JBMaxDelay'),
'SipToS' => $this->input->post('SipToS'),
'RTPToS' => $this->input->post('RTPToS'),
'LogLevel' => $this->input->post('LogLevel')
);
$this->load->helper('file');
$file = $path.$filename;
function write_php_ini($array, $file)
{
$res = array();
foreach($array as $key => $val)
{
if(is_array($val))
{
$res[] = "[$key]";
foreach($val as $skey => $sval) $res[] = "$skey = ".(is_numeric($sval) ? $sval : '"'.$sval.'"');
}
else $res[] = "$key = ".(is_numeric($val) ? $val : '"'.$val.'"');
}
safefilerewrite($file, implode("\r\n", $res));
}
function safefilerewrite($fileName, $dataToSave)
{ if ($fp = fopen($fileName, 'w'))
{
$startTime = microtime(TRUE);
do
{ $canWrite = flock($fp, LOCK_EX);
// If lock not obtained sleep for 0 - 100 milliseconds, to avoid collision and CPU load
if(!$canWrite) usleep(round(rand(0, 100)*1000));
} while ((!$canWrite)and((microtime(TRUE)-$startTime) < 5));
//file was locked so now we can store information
if ($canWrite)
{ fwrite($fp, $dataToSave);
flock($fp, LOCK_UN);
}
fclose($fp);
}
}
/*Inserting The Data into .ini File*/
write_php_ini($insert,$file);
/*Back to you index page id data is submmited*/
if(isset($_POST['submit'] ))
{
redirect('customer/upload_ini/index');
}
$this->data['subview'] = 'customer/upload/edit_ini';
$this->load->view('customer/_layout_main', $this->data);
}
I want to print the sections into file.

This is not a complete solution, but some corrections to do to your code
First thing : please avoid the ternary operator, your code must always be as clear as possible, also you haven't planned the case where your value is null/empty
please try as follow
foreach($val as $skey => $sval) {
$configPrefix = $skey . ' = ';
if (!is_null($sval) && !empty($sval)) {
if (is_numeric($sval)) {
$res[] = $configPrefix . $sval;
}
else if (is_string($sval)) {
$res[] = $configPrefix . "'" .
$sval . "'" ;
}
else {
// TODO Log/throw exception for your unhandled case ...
}
}
}
Also you didn't decomposed your $insert array by sections, so use this and adapt your code to write sections in your ini file
$insert = array(
'INIDetails' => array(
'SipUserName' => $this->input->post('SipUserName'),
'SipAuthName' => $this->input->post('SipAuthName'),
'DisplayName' => $this->input->post('DisplayName'),
'Password' => $this->input->post('Password'),
'Domain' => $this->input->post('Domain'),
'Proxy' => $this->input->post('Proxy'),
'Port' => $this->input->post('Port'),
'ServerMode' => $this->input->post('ServerMode'),
'UCServer' => $this->input->post('UCServer'),
'UCPassword' => $this->input->post('UCPassword')
),
'DialPlan' => array(
'DP_Exception' => $this->input->post('DP_Exception'),
'DP_Rule1' => $this->input->post('DP_Rule1'),
'DP_Rule2' => $this->input->post('DP_Rule2')
),
'Advanced' => array(
'OperationMode' => $this->input->post('OperationMode'),
'MutePkey' => $this->input->post('MutePkey'),
'Codec' => $this->input->post('Codec'),
'PTime' => $this->input->post('PTime'),
'AudioMode' => $this->input->post('AudioMode'),
'SoftwareAEC' => $this->input->post('SoftwareAEC'),
'EchoTailLength' => $this->input->post('EchoTailLength'),
'PlaybackBuffer' => $this->input->post('PlaybackBuffer'),
'CaptureBuffer' => $this->input->post('CaptureBuffer'),
'JBPrefetchDelay' => $this->input->post('JBPrefetchDelay'),
'JBMaxDelay' => $this->input->post('JBMaxDelay'),
'SipToS' => $this->input->post('SipToS'),
'RTPToS' => $this->input->post('RTPToS'),
'LogLevel' => $this->input->post('LogLevel')
)
);

parse_ini_file(), and work on the associative array.
sample:
$ini_array = parse_ini_file("sample.ini", true);
print_r($ini_array);
you have to pass true as second argument to get correct format.

Related

how to cek array php

I have an array that I will insert into the item table, here I use multiple inserts
Array
(
[0] => Array
(
[id_service] => 2
[tracking_number] => RJC219384044389234035
)
[1] => Array
(
[id_service] => 1
[tracking_number] => RJC749944771469498146
)
)
in the item table, there is already id_service: 2
how to make validation, when one of the input is already in the item table, then all the input is false so it fails?
my code
public function nyobain()
{
$resi = $this->input->post('kode'); //tracking_number
$expld = explode(' ', $resi);
$data = $this->M_outbound_destinasi->dbGet($expld); //get 'id_service' where tracking_number
// $db = $this->db->query("SELECT id_service FROM `tabel_items`")->result();
// foreach ($db $key) {
// $temp=array($key->id_service);
// }
// how to cek ? if id_service already in the item table
foreach ($data as $key) {
$idnya = $key['id_service'];
$id_outbound = $key['id_outbound'];
$id_indes = $key['id_indes'];
$id_outbag = $key['id_outbag'];
$data_insert = array(
'jenis' => 'outbound-destinasi',
'id_service' => $idnya,
'id_indes' => $id_indes,
'id_outbound' => $id_outbound,
'id_outbag' => $id_outbag,
'id_admin' => $this->session->userdata('ses_id')
);
$this->db->insert('tabel_items', $data_insert);
}
echo json_encode($data);
}
You can use in_array to achieve this
public function nyobain(){
$resi = $this->input->post('kode');
$expld = explode(' ', $resi);
$data = $this->M_outbound_destinasi->dbGet($expld);
$db = $this->db->query("SELECT id_service FROM `tabel_items`")->result();
if(isset($data) && $data !== ''){//check if $data has a value and it not null
if (in_array($data ,$db, true)) {
return $data.'already exists in the DB!';
}else{
foreach ($data as $key) {
$idnya = $key['id_service'];
$id_outbound = $key['id_outbound'];
$id_indes = $key['id_indes'];
$id_outbag = $key['id_outbag'];
$data_insert = [
'jenis' => 'outbound-destinasi',
'id_service' => $idnya,
'id_indes' => $id_indes,
'id_outbound' => $id_outbound,
'id_outbag' => $id_outbag,
'id_admin' => $this->session->userdata('ses_id')
];
$this->db->insert('tabel_items', $data_insert);
}
return json_encode($data);
}
}
}

CSV file is not downloading in cakephp

I am new in cakephp framework.I want to generate csv file.Here I have result array like :
Array
(
[0] => Array
(
[User] => Array
(
[username] => yerica
[email] => amoreyerica#gmail.com
[phone] => 993643636
)
[DealPurchase] => Array
(
[deal_title] => Tour de Zaragoza
[original_price] => 30
)
)
[1] => Array
(
[User] => Array
(
[username] => Rama Test
[email] => rama#gmail.com
[phone] => 9652369854
)
[DealPurchase] => Array
(
[deal_title] => Tour de Zaragoza
[original_price] => 30
)
)
)
Here, I want to generate csv of this array.
Here, I have include CsvHelper.php file in view/helpers folder.This file contains :
<?php
class CsvHelper extends AppHelper
{
var $delimiter = ',';
var $enclosure = '"';
var $filename = 'Export.csv';
var $line = array();
var $buffer;
function CsvHelper()
{
$this->clear();
}
function clear()
{
$this->line = array();
$this->buffer = fopen('php://temp/maxmemory:'. (5*1024*1024), 'r+');
}
function addField($value)
{
$this->line[] = $value;
}
function endRow()
{
$this->addRow($this->line);
$this->line = array();
}
function addRow($row)
{
fputcsv($this->buffer, $row, $this->delimiter, $this->enclosure);
}
function renderHeaders()
{
header('Content-Type: text/csv');
header("Content-type:application/vnd.ms-excel");
header("Content-disposition:attachment;filename=".$this->filename);
}
function setFilename($filename)
{
$this->filename = $filename;
if (strtolower(substr($this->filename, -4)) != '.csv')
{
$this->filename .= '.csv';
}
}
function render($outputHeaders = true, $to_encoding = null, $from_encoding ="auto")
{
if ($outputHeaders)
{
if (is_string($outputHeaders))
{
$this->setFilename($outputHeaders);
}
$this->renderHeaders();
}
rewind($this->buffer);
$output = stream_get_contents($this->buffer);
if ($to_encoding)
{
$output = mb_convert_encoding($output, $to_encoding, $from_encoding);
}
return $this->output($output);
}
}
?>
In MerchantController(controller) function is looks like :
function download_csv($deal_id)
{
$options=array('fields'=>'User.username,User.email,User.phone,DealPurchase.deal_title,DealPurchase.original_price',
'joins' =>
array(
array(
'table' => 'deal_purchases',
'alias' => 'DealPurchase',
'type' => 'inner',
'foreignKey' => false,
'conditions'=> array('DealPurchase.user_id = User.id')
)));
$this->recursive = -1;
$data = $this->User->find('all', $options);
$this->set("users",$data);
$this->layout = null;
$this->autoLayout = false;
Configure::write('debug', '0');
}
Here,My view file code is :
<?php
$line= $users[0]['User'];
$this->CSV->addRow(array_keys($line));
foreach ($users as $user)
{
$line = $user['User'];
$this->CSV->addRow($line);
}
$filename='users';
echo $this->CSV->render($filename);
Here, my another function which contains link of download csv file and function looks like :
function deal_list(){
$this->_checkMerchantSession();
$this->set('title_for_layout', 'Deal List');
$this->layout = "after_login";
//echo $this->Session->read('userData.Merchant.id');
//$conditions = "Deal.merchant_id ='".$this->Session->read('userData.Merchant.id')."' AND Deal.isdeleted ='0' AND Deal.isapproved ='0' ";
$conditions = "Deal.merchant_id ='".$this->Session->read('userData.Merchant.id')."' AND Deal.isdeleted ='0' ";
//$ArDealdetails = $this->Deal->find('all', array('conditions'=>$conditions,'order'=>'Deal.modified DESC'));
$this->paginate = array('conditions' => $conditions,'limit' =>5,'order'=>'Deal.id DESC');
$ArDealdetails = $this->paginate('Deal');
$this->set('ArDealdetails',$ArDealdetails);
$condition1 = "Merchant.id ='".$this->Session->read('userData.Merchant.id')."'";
$merchant_detail = $this->Merchant->find('first',array('conditions'=>$condition1));
$this->set('merchant_detail',$merchant_detail);
}
Now, when I include helper as Csv like:
var $helpers = array('Html', 'Form','Javascript','Fck','Js','Paginator','Csv');
Then it will gives an error.So how can I resolve this problem?
Note : I have an error like : Error: The requested address '/merchant/deal_list' was not found on this server. I have added download csv link in deal_list view file. When I remove Csv from the helpers then this page is display.
Error: Undefined property: View::$Csv.
Casing is wrong on your csv helpers in the view. Should be $this->Csv
<?php
$line= $users[0]['User'];
$this->Csv->addRow(array_keys($line));
foreach ($users as $user)
{
$line = $user['User'];
$this->Csv->addRow($line);
}
$filename='users';
echo $this->Csv->render($filename);
Here I have just rename CsvHelper.php helper file to csv.php so its working. So can anybody explain me why its working because of csv.php name?

Looping through character data and items from MySQL DB in PHP

I have the following code:
include "config.php";
error_reporting(0);
$idSuccess = 0;
if(isset($_POST['userName']))
{
$usr = $_POST['userName'];
$pwd = $_POST['userPwd'];
$sqlQ = "SELECT * FROM dr_users where dr_user_name='$usr' AND dr_user_pwd='$pwd' LIMIT 1";
$q = mysql_query($sqlQ);
if(mysql_num_rows($q) > 0)
{
$userO = mysql_fetch_assoc($q);
$userData = array('userID' => $userO['dr_user_id'], 'userName' => $userO['dr_user_name'], 'userPwd' => $userO['dr_user_pwd'], 'userEml' => $userO['dr_user_email'], 'privLvl' => $userO['dr_user_priv_level']);
$idSuccess = 1;
$uID = $userO['dr_user_id'];
$charQ = mysql_query("SELECT * FROM dr_chars WHERE dr_user_id='$uID'");
while($char = mysql_fetch_array($charQ))
{
$chars[] = $char;
$charID = $char['dr_char_id'];
$itemQ = mysql_query("SELECT * FROM dr_items WHERE dr_char_id='$charID'");
while($item = mysql_fetch_array($itemQ))
{
$itemData[] = array('itemID' => $item['dr_item_id'], 'itemName' => $item['dr_item_name'], 'itemDesc' => $item['dr_item_desc'], 'itemType' => $item['dr_item_type'], 'itemCost' => $item['dr_item_cost'], 'itemCurType' => $item['dr_item_cur_type'], 'itemAtk' => $item['dr_item_stat_atk'], 'itemDef' => $item['dr_item_stat_def'], 'itemEnd' => $item['dr_item_stat_end'], 'itemLuck' => $item['dr_item_stat_luck'], 'itemFileURL' => $item['dr_item_file_url'], 'itemStaff' => $item['dr_item_staff'], 'itemEquipped' => $item['dr_char_eqp'], 'spX' => $item['dr_static_pos_x'], 'spY' => $item['dr_static_pos_y']);
}
$charData[] = array('charID' => $char['dr_char_id'], 'charName' => $char['dr_char_name'], 'charRace' => $char['dr_char_race'], 'charLvl' => $char['dr_char_lvl'], 'charItems' => $itemData);
}
$resData = array('idSuccess' => $idSuccess, 'user' => $userData, 'chars' => $charData);
} else {
$resData = array('idSuccess' => $idSuccess);
}
echo json_encode($resData);
}
?>
I have successfully loaded character data from the table 'dr_chars' in my database. I'm trying to load the corresponding item data from the retrieved character ID and push it into the $charData array. So I can then easily encode & output it in a JSON format.
If my question isn't clear just ask and I'll try to explain the situation better. The JSON data is being outputted into flash for dynamic use.
I managed to fix this final code as follows:
<?php
include "config.php";
error_reporting(0);
$idSuccess = 0;
if(isset($_POST['userName']))
{
$usr = $_POST['userName'];
$pwd = $_POST['userPwd'];
$sqlQ = "SELECT * FROM dr_users where dr_user_name='$usr' AND dr_user_pwd='$pwd' LIMIT 1";
$q = mysql_query($sqlQ);
if(mysql_num_rows($q) > 0)
{
$userO = mysql_fetch_assoc($q);
$userData = array('userID' => $userO['dr_user_id'], 'userName' => $userO['dr_user_name'], 'userPwd' => $userO['dr_user_pwd'], 'userEml' => $userO['dr_user_email'], 'privLvl' => $userO['dr_user_priv_level']);
$idSuccess = 1;
$uID = $userO['dr_user_id'];
$charQ = mysql_query("SELECT * FROM dr_chars WHERE dr_user_id='$uID'");
$chars = array();
while($char = mysql_fetch_array($charQ))
{
$charID = $char['dr_char_id'];
$itemQ = mysql_query("SELECT * FROM dr_items WHERE dr_char_id='$charID'");
$items = array();
while($item = mysql_fetch_array($itemQ))
{
$items[] = array('itemID' => $item['dr_item_id'], 'itemName' => $item['dr_item_name'], 'itemDesc' => $item['dr_item_desc'], 'itemType' => $item['dr_item_type'], 'itemCost' => $item['dr_item_cost'], 'itemCurType' => $item['dr_item_cur_type'], 'itemAtk' => $item['dr_item_stat_atk'], 'itemDef' => $item['dr_item_stat_def'], 'itemEnd' => $item['dr_item_stat_end'], 'itemLuck' => $item['dr_item_stat_luck'], 'itemFileURL' => $item['dr_item_file_url'], 'itemStaff' => $item['dr_item_staff'], 'itemEquipped' => $item['dr_char_eqp'], 'spX' => $item['dr_static_pos_x'], 'spY' => $item['dr_static_pos_y']);
}
$chars[] = array('charID' => $char['dr_char_id'], 'charName' => $char['dr_char_name'], 'charRace' => $char['dr_char_race'], 'charLvl' => $char['dr_char_lvl'], 'charItems' => $items);
}
$resData = array('idSuccess' => $idSuccess, 'user' => $userData, 'chars' => $chars);
} else {
$resData = array('idSuccess' => $idSuccess);
}
echo json_encode($resData);
}
?>

Compare two arrays and append last values if they are the same else value zero

I have two string values namely $late_array and $wrong_array. The values are comma delimited.
What I would like to do is compare the two arrays and if the first two elements are the same add the value to the end else make it zero. The arrays I have:
$late_array = array(
[0] => 140610d,Richard,12
[1] => 140610a,Dave,22
[2] => 140610n,Noddy,121
[3] => 140610a,Nick,15
)
$wrong_array = array(
[0] => 140610d,Richard,2
[1] => 140610d,Mary,60
[2] => 140610a,Dave,11
[3] => 140610n,Noddy,90
)
The end result should be:
$combined_array = array(
[0] => 140610d,Richard,12,2
[1] => 140610d,Mary,0,60
[2] => 140610a,Dave,22,11
[3] => 140610a,Nick,15,0
[4] => 140610n,Noddy,121,90
)
I have so far formed a foreach and used the '===' operators to check if the date and name match then output as I want but I have not been able to get it to work if the name is not present in one array but another to make the value zero.
EDIT: Just to clear it up, hopefully. If the value is present in both arrays then the date,name,late value,wrong value should show. But if the value is present in late only then the value for wrong should be 0, same visa versa. Added "Nick" to try and explain a bit better.
This is what I did to solve the problem so far:
$wrong_val = array();
foreach($out as $wrong_value) {
$wrong_tosearch[] = substr($wrong_value,0,strrpos($wrong_value,","));
$w_id = substr($wrong_value,0,strrpos($wrong_value,","));
$wrong_val[$w_id] = substr($wrong_value,strrpos($wrong_value,",")+1,strlen($wrong_value));
}
foreach($sql_late_array as $late_value) {
$late_tosearch[] = substr($late_value,0,strrpos($late_value,","));
$l_id = substr($late_value,0,strrpos($late_value,","));
$late_val[$l_id] = substr($late_value,strrpos($late_value,",")+1,strlen($late_value));
}
$merge = array_merge($wrong_tosearch,$late_tosearch);
$sort = array_values(array_unique($merge));
$combined_array = array();
foreach ($sort as $search_val) {
if (array_key_exists($search_val,$wrong_val) !== FALSE) {
foreach ($wrong_val as $w_key=>$w_val) {
$combined_array[$w_key]['late'] = "0";
$combined_array[$w_key]['wrong'] = $w_val;
}
}
if (array_key_exists($search_val,$late_val) !== FALSE) {
foreach ($late_val as $l_key=>$l_val) {
$combined_array[$l_key]['wrong'] = "0";
$combined_array[$l_key]['late'] = $l_val;
}
}
}
print_r($combined_array);
Check if below code solves your problem.
$late_array = array(
"0" => "140610d,Richard,12",
"1" => "140610a,Dave,22",
"2" => "140610n,Noddy,121"
);
$wrong_array = array(
"0" => "140610d,Richard,2",
"1" => "140610d,Mary,60",
"2" => "140610a,Dave,11",
"3" => "140610n,Noddy,90"
);
foreach($wrong_array as $wv)
{
$tosearch = substr($wv,0,strrpos($wv,",")-1);
$valtoadd = substr($wv,strrpos($wv,",")+1,strlen($wv));
$added=false;
foreach($late_array as $lv)
{
if(strstr($lv, $tosearch) !== false)
{
$combined_array[] = $lv.",".$valtoadd;
$added=true;
break;
}
}
if(!$added)
$combined_array[] = $tosearch.",0,".$valtoadd;
}
$tcombined_array = $combined_array;
foreach($late_array as $wv)
{
$added = false;
foreach($tcombined_array as $cv)
if(strstr($cv,$wv))
$added = true;
if(!$added) $combined_array[] = $wv.",0";
}
print_r($combined_array);
May be big but works
<?php
$late_array = array(
0 => "140610d,Richard,12",
1 => "140610a,Dave,22",
2 => "140610n,Noddy,121",
);
$wrong_array = array(
0 => "140610d,Richard,2",
1 => "140610d,Mary,60",
2 => "140610a,Dave,11",
3 => "140610n,Noddy,90"
);
$pattern = "/[0-9]*[a-zA-Z]*,[0-9]*[a-zA-Z]*,/";
$combined_array = $late_array;
foreach($wrong_array as $wrong_index => $wrong_value){
foreach($late_array as $late_index => $late_value){
preg_match_all($pattern, $late_value, $late_matches);
preg_match_all($pattern, $wrong_value, $wrong_matches);
if($late_matches[0] == $wrong_matches[0]){
$explode = explode(',',$wrong_value);
$combined_array[$late_index] = $combined_array[$late_index].','.$explode[2];
$matchedValues[] = $wrong_index;
}
}
}
$unmatched_values = array_diff(array_keys($wrong_array), array_values($matchedValues));
foreach($unmatched_values as $key => $value){
$combined_array[] = $wrong_array[$value].',0';
}
echo '<pre>';
print_r($combined_array);
?>

Pass variables through include (another php file) in php

I'm working on a php web application for a website, and I would like to pass some variables from one php file to another. I have tried the old fashion way with the include file but was not successful. I also tried to set the variables in global scope but still not working. The code in first.php file is:
function rc_getAvailableVehicles($pickup_timestamp, $return_timestamp, $vehicle_classes=array()) {
global
$wpdb;
$rc_currency = RC_Registry::get('rc_currency');
$where_classes = "";
if ($vehicle_classes) {
foreach($vehicle_classes as $vehicle_class) {
$where_classes[] = " v.class = '". $wpdb->escape($vehicle_class) ."'";
}
$where_classes = "AND (".implode(' OR ', $where_classes).") ";
}
$sql = "SELECT *
FROM ".$wpdb->rc_vehicles." v
WHERE v.quantity > (SELECT COUNT(*) FROM ".$wpdb->rc_bookings." b WHERE b.vehicle_id = v.vehicle_id AND ((UNIX_TIMESTAMP(b.pickup_date) >= '". (int)$pickup_timestamp ."' AND UNIX_TIMESTAMP(b.pickup_date) < '". (int)$return_timestamp ."') || (UNIX_TIMESTAMP(b.pickup_date) < '". (int)$pickup_timestamp ."' AND UNIX_TIMESTAMP(b.return_date) >= '". (int)$pickup_timestamp ."')) AND (b.status != 'new' AND b.status != 'canceled') AND b.trash = '0') ".$where_classes."AND v.status = '1' AND v.archive = '0'
ORDER BY v.rent ASC";
$results = $wpdb->get_results($sql,ARRAY_A);
$vehicles = array();
$rental_days = ceil(($return_timestamp-$pickup_timestamp)/91800);
$xfee = get_field('another_location_fee');
$xfee2 = get_field('return_to_another_location_fee_2');
if ($results) {
foreach ($results as $result) {
if ($result['image'] && file_exists(RC_UPLOADS_DIR . "vehicle_" . $result['image'])) {
$image = RC_UPLOADS_URL . 'vehicle_' . $result['image'];
$image_thumb = RC_UPLOADS_URL . 'cache/' . rc_image_resize(RC_UPLOADS_DIR . "vehicle_" . $result['image'], 220, 160);
} else {
$image = '';
$image_thumb = '';
}
$result['description'] = do_shortcode($result['description']);
$description = html_entity_decode($result['description'], ENT_QUOTES, 'UTF-8');
global $GeneralPrice, $discount_price, $rent1, $rent5;
include_once ('file2.php');
//$GeneralPrice = $result['rent'];
$rent1 = $vehicle_meta['rent1'];
$rent2 = $vehicle_meta['rent2'];
$rent3 = $vehicle_meta['rent3'];
$rent4 = $vehicle_meta['rent4'];
$rent5 = $vehicle_meta['rent5'];
$rent6 = $vehicle_meta['rent6'];
$rent7 = $vehicle_meta['rent7'];
$rent8 = $vehicle_meta['rent8'];
$rent9 = $vehicle_meta['rent9'];
$rent10 = $vehicle_meta['rent10'];
$rent11 = $vehicle_meta['rent11'];
$rent12 = $vehicle_meta['rent12'];
$rent13 = $vehicle_meta['rent13'];
$rent14 = $vehicle_meta['rent14'];
$rent15 = $vehicle_meta['rent15'];
$rent16 = $vehicle_meta['rent16'];
$rent17 = $vehicle_meta['rent17'];
$rent18 = $vehicle_meta['rent18'];
$rent19 = $vehicle_meta['rent19'];
$rent20 = $vehicle_meta['rent20'];
$rent21 = $vehicle_meta['rent21'];
$rent22 = $vehicle_meta['rent22'];
$rent23 = $vehicle_meta['rent23'];
$rent24 = $vehicle_meta['rent24'];
$rent25 = $vehicle_meta['rent25'];
$rent26 = $vehicle_meta['rent26'];
$rent27 = $vehicle_meta['rent27'];
$rent28 = $vehicle_meta['rent28'];
$rent29 = $vehicle_meta['rent29'];
$rent30 = $vehicle_meta['rent30'];
$rent31 = $vehicle_meta['rent31'];
$rent32 = $vehicle_meta['rent32'];
$rent33 = $vehicle_meta['rent33'];
$rent34 = $vehicle_meta['rent34'];
$rent35 = $vehicle_meta['rent35'];
$rent36 = $vehicle_meta['rent36'];
$vehicle_meta = rc_getVehicleMeta($result['vehicle_id']);
$vehicles[$result['vehicle_id']] = array(
'vehicle_id' => $result['vehicle_id'],
'title' => $result['manufacturer']." ".$result['series'],
'manufacturer' => $result['manufacturer'],
'series' => $result['series'],
'year' => $result['year'],
'class' => $result['class'],
'image' => $image,
'image_thumb' => $image_thumb,
'description' => $description,
'seats' => $vehicle_meta['seats'],
'doors' => $vehicle_meta['doors'],
'baggages' => $vehicle_meta['baggages'],
'conditioning' => $vehicle_meta['conditioning'],
'transmission' => $vehicle_meta['transmission'],
'rent1' => $vehicle_meta['rent1'],
'rent2' => $vehicle_meta['rent2'],
'rent3' => $vehicle_meta['rent3'],
'rent4' => $vehicle_meta['rent4'],
'rent5' => $vehicle_meta['rent5'],
'rent6' => $vehicle_meta['rent6'],
'rent7' => $vehicle_meta['rent7'],
'rent8' => $vehicle_meta['rent8'],
'rent9' => $vehicle_meta['rent9'],
'rent10' => $vehicle_meta['rent10'],
'rent11' => $vehicle_meta['rent11'],
'rent12' => $vehicle_meta['rent12'],
'rent13' => $vehicle_meta['rent13'],
'rent14' => $vehicle_meta['rent14'],
'rent15' => $vehicle_meta['rent15'],
'rent16' => $vehicle_meta['rent16'],
'rent17' => $vehicle_meta['rent17'],
'rent18' => $vehicle_meta['rent18'],
'rent19' => $vehicle_meta['rent19'],
'rent20' => $vehicle_meta['rent20'],
'rent21' => $vehicle_meta['rent21'],
'rent22' => $vehicle_meta['rent22'],
'rent23' => $vehicle_meta['rent23'],
'rent24' => $vehicle_meta['rent24'],
'rent25' => $vehicle_meta['rent25'],
'rent26' => $vehicle_meta['rent26'],
'rent27' => $vehicle_meta['rent27'],
'rent28' => $vehicle_meta['rent28'],
'rent29' => $vehicle_meta['rent29'],
'rent30' => $vehicle_meta['rent30'],
'rent31' => $vehicle_meta['rent31'],
'rent32' => $vehicle_meta['rent32'],
'rent33' => $vehicle_meta['rent33'],
'rent34' => $vehicle_meta['rent34'],
'rent35' => $vehicle_meta['rent35'],
'rent36' => $vehicle_meta['rent36'],
'total_price' => $rc_currency->format((($rental_days*$GeneralPrice)-(($rental_days*$GeneralPrice) * ($discount_price)/100)+ $utime)),
'total_price_return_fee' => $rc_currency->format((($rental_days*$result['rent']) - ($rental_days*$result['rent']) * ($discount_price)/100)+ $xfee),
'total_price_return_fee2' => $rc_currency->format((($rental_days*$result['rent']) - ($rental_days*$result['rent'])*($discount_price)/100)+ $xfee2),
'daily_price' => $rc_currency->format((($GeneralPrice)-($GeneralPrice)*($discount_price)/100)+ ($utime / $rental_days)),
'daily_price_return_fee' => $rc_currency->format(($result['rent']-($result['rent'])* ($discount_price)/100)+ ($xfee / $rental_days)),
'daily_price_return_fee2' => $rc_currency->format(($result['rent']-($result['rent'])*($discount_price)/100) + ($xfee2 / $rental_days))
);
}
}
return $vehicles;
}
and I want to echo all the $rent variables in file2.php
I have tried the
echo $rent; without success!
You have problems with the order of the code
$vehicle_meta = rc_getVehicleMeta($result['vehicle_id']);
Should be BEFORE you populate rent variables, and
include_once ('file2.php');
Should be AFTER you populated rent variables.
You need to call a function in file1.php that exists in file2.php
ex. in file1.php you could call the function return_rent
return_rent($rent);
in file2 then you make the function
function return_rent($var){
echo $rent;
}
$pass = "anything";
include_once ('file2.php');
From file2.php you can access $pass variable.

Categories