Include file and Functions PHP - php

i have 2 php files file1.php with some global varibles
and file2.php with several functions changing the files1 variables values after some x condition.
The only problem i have the file1.php which includes file2.php doesn't echo / return the values. The code is below:
file1.php
if ($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'], 160, 120);
} else {
$image = '';
$image_thumb = '';
}
$description = preg_replace(array("/\s\s/", "/\r\r/", "/\n\n/"), '<br />', trim($result['description']));
$vehicle_meta = rc_getVehicleMeta($vehicle_id);
global $GeneralPrice, $discount_price, $rent, $rent1, $rent2, $rent3,$rent4, $rent5, $rent6, $rent7, $rent8, $rent9, $rent10, $rent11, $rent12, $rent13, $rent14, $rent15, $rent16, $rent17, $rent18, $rent19, $rent20, $rent21, $rent22, $rent23, $rent24, $rent25, $rent26, $rent27, $rent28, $rent29, $rent30, $rent31, $rent32, $rent33, $rent34, $rent35, $rent36;
$rent = $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'];
include_once('files2.php');
$vehicle = 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'],
'total_price' => $rc_currency->format((($rental_days*$GeneralPrice )-($rental_days*$GeneralPrice)* ($discount_price)/100)+ $total_extras),
'total_price_return_fee' => $rc_currency->format((($rental_days*$GeneralPrice)-($rental_days*$GeneralPrice)* ($discount_price)/100)+ $xfee + $total_extras),
'total_price_return_fee' => $rc_currency->format((($rental_days*$GeneralPrice)-($rental_days*$GeneralPrice)* ($discount_price)/100)+ $xfee2 + $total_extras),
'daily_price' => $rc_currency->format((($GeneralPrice)-($GeneralPrice)* ($discount_price)/100)+ $excess_price),
'daily_price_return_fee' => $rc_currency->format((($GeneralPrice)-($GeneralPrice)* ($discount_price)/100)+ ( $xfee / $rental_days)),
'daily_price_return_fee2' => $rc_currency->format((($GeneralPrice)-($GeneralPrice)*($discount_price)/100)+ ( $xfee2 / $rental_days))
);
}
return $vehicle;
}
File2.php
<?php
//Out of Season function
function outofseason(){
global $rental_days, $GeneralPrice, $discount_price, $days1,$discount1, $days2, $discount2, $days3, $discount3, $rent;
//Discount with Duration
$days1 = get_field('days');
$discount1 = get_field('discount_days1');
$days2 = get_field('days2');
$discount2 = get_field('discount_days2');
$days3 = get_field('days3');
$discount3 = get_field('discount_days3');
$GeneralPrice = $rent;
if($rental_days > $days1 && $rental_days < $days2){
return $discount_price = $discount1;
}elseif($rental_days > $days2 && $rental_days < $days3){
return $discount_price = $discount1 + $discount2;
}elseif($rental_days > $days3 && $discount3 !=0){
return $discount_price = $discount1 + $discount2 + $discount3;
}else{
return $discount_price = 0;
}
}
//Seasons
function Seasonlow() {
global $rental_days, $GeneralPrice, $discount_price, $season_start_date_low, $season_end_date_low, $rent1, $rent2, $rent3, $rent4, $rent5, $rent6, $rent7, $rent8, $rent9;
//Date calculator
$datetime1 = '2014-02-05';
$datetime2 = '2014-04-15';
$duration = 86400 ;
$days_dur = ceil(strtotime($datetime2)-strtotime($datetime1))/$duration;
//$season_start_date_low = '05/02/2014';
//$season_end_date_low = '15/02/2014';
$pickupdate = $_GET['pickup_date'];
$returndate = $_GET['return_date'];
//if($pickupdate >= $season_start_date_low && $returndate <= $season_end_date_low){
if($rental_days == 1){
return $GeneralPrice = $rent1;
$discount_price = 0;
}elseif($rental_days == 2){
return $GeneralPrice = $rent2;
$discount_price = 0;
}elseif($rental_days == 3){
return $GeneralPrice = $rent3;
$discount_price = 0;
}elseif($rental_days == 4){
return $GeneralPrice = $rent4;
$discount_price = 0;
}elseif($rental_days == 5){
return $GeneralPrice = $rent5;
$discount_price = 0;
}elseif($rental_days == 6){
return $GeneralPrice = $rent6;
$discount_price = 0;
}elseif($rental_days >= 7 && $rental_days <= 13){
return $GeneralPrice = $rent7;
$discount_price = 0;
}elseif($rental_days >= 14 && $rental_days <= 20){
return $GeneralPrice = $rent8;
$discount_price = 0;
}elseif($rental_days >= 21){
return $GeneralPrice = $rent9;
$discount_price = 0;
}
//}else {
//outofseason();
//}
}
//Season Mid
function Seasonmid() {
global $rental_days, $GeneralPrice, $discount_price, $season_start_date_mid, $season_end_date_mid, $rent10, $rent11, $rent12, $rent13, $rent14, $rent15, $rent16, $rent17, $rent18;
//Date calculator
$datetime1 = '2014-02-05';
$datetime2 = '2014-04-15';
$duration = 86400 ;
$days_dur = ceil(strtotime($datetime2)-strtotime($datetime1))/$duration;
//$season_start_date_mid = '05/03/2014';
//$season_end_date_mid = '15/03/2014';
$pickupdate = $_GET['pickup_date'];
$returndate = $_GET['return_date'];
//if($pickupdate >= $season_start_date_mid && $returndate <= $season_end_date_mid){
if($rental_days == 1){
return $GeneralPrice = $rent10;
$discount_price = 0;
}elseif($rental_days == 2){
return $GeneralPrice = $rent11;
$discount_price = 0;
}elseif($rental_days == 3){
return $GeneralPrice = $rent12;
$discount_price = 0;
}elseif($rental_days == 4){
return $GeneralPrice = $rent13;
$discount_price = 0;
}elseif($rental_days == 5){
return $GeneralPrice = $rent14;
$discount_price = 0;
}elseif($rental_days == 6){
return $GeneralPrice = $rent15;
$discount_price = 0;
}elseif($rental_days >= 7 && $rental_days <= 13){
return $GeneralPrice = $rent16;
$discount_price = 0;
}elseif($rental_days >= 14 && $rental_days <= 20){
return $GeneralPrice = $rent17;
$discount_price = 0;
}elseif($rental_days >= 21){
return $GeneralPrice = $rent18;
$discount_price = 0;
}
//}else {
// outofseason();
//}
}
//Season Mid_B
function Seasonmid_B() {
global $rental_days, $GeneralPrice, $discount_price, $season_start_date_mid_B, $season_end_date_mid_B, $rent19, $rent20, $rent21, $rent22, $rent23, $rent24, $rent25, $rent26, $rent27;
//Date calculator
$datetime1 = '2014-02-05';
$datetime2 = '2014-04-15';
$duration = 86400 ;
$days_dur = ceil(strtotime($datetime2)-strtotime($datetime1))/$duration;
//$season_start_date_mid = '05/03/2014';
//$season_end_date_mid = '15/03/2014';
$pickupdate = $_GET['pickup_date'];
$returndate = $_GET['return_date'];
//if($pickupdate >= $season_start_date_mid && $returndate <= $season_end_date_mid){
if($rental_days == 1){
return $GeneralPrice = $rent19;
$discount_price = 0;
}elseif($rental_days == 2){
return $GeneralPrice = $rent20;
$discount_price = 0;
}elseif($rental_days == 3){
return $GeneralPrice = $rent21;
$discount_price = 0;
}elseif($rental_days == 4){
return $GeneralPrice = $rent22;
$discount_price = 0;
}elseif($rental_days == 5){
return $GeneralPrice = $rent23;
$discount_price = 0;
}elseif($rental_days == 6){
return $GeneralPrice = $rent24;
$discount_price = 0;
}elseif($rental_days >= 7 && $rental_days <= 13){
return $GeneralPrice = $rent25;
$discount_price = 0;
}elseif($rental_days >= 14 && $rental_days <= 20){
return $GeneralPrice = $rent26;
$discount_price = 0;
}elseif($rental_days >= 21){
return $GeneralPrice = $rent27;
$discount_price = 0;
}
//}else {
// outofseason();
//}
}
//Season Mid_B
function SeasonHigh() {
global $rental_days, $GeneralPrice, $discount_price, $season_start_date_mid_high, $season_end_date_high, $rent28, $rent29, $rent30, $rent31, $rent32, $rent33, $rent34, $rent35, $rent36;
//Date calculator
$datetime1 = '2014-02-05';
$datetime2 = '2014-04-15';
$duration = 86400 ;
$days_dur = ceil(strtotime($datetime2)-strtotime($datetime1))/$duration;
//$season_start_date_mid = '05/03/2014';
//$season_end_date_mid = '15/03/2014';
$pickupdate = $_GET['pickup_date'];
$returndate = $_GET['return_date'];
//if($pickupdate >= $season_start_date_mid && $returndate <= $season_end_date_mid){
if($rental_days == 1){
return $GeneralPrice = $rent28;
$discount_price = 0;
}elseif($rental_days == 2){
return $GeneralPrice = $rent29;
$discount_price = 0;
}elseif($rental_days == 3){
return $GeneralPrice = $rent30;
$discount_price = 0;
}elseif($rental_days == 4){
return $GeneralPrice = $rent31;
$discount_price = 0;
}elseif($rental_days == 5){
return $GeneralPrice = $rent32;
$discount_price = 0;
}elseif($rental_days == 6){
return $GeneralPrice = $rent33;
$discount_price = 0;
}elseif($rental_days >= 7 && $rental_days <= 13){
return $GeneralPrice = $rent34;
$discount_price = 0;
}elseif($rental_days >= 14 && $rental_days <= 20){
return $GeneralPrice = $rent35;
$discount_price = 0;
}elseif($rental_days >= 21){
return $GeneralPrice = $rent36;
$discount_price = 0;
}
//}else {
// outofseason();
//}
}
//low
$season_start_date_low = (get_option('rc_settings_season_start_date_low'));
$season_end_date_low = (get_option('rc_settings_season_end_date_low'));
$season_start_date_low_convert = str_replace('/', '-', $season_start_date_low);
$season_low_start = date('Y-m-d', strtotime($season_start_date_low_convert));
$season_end_date_low_convert = str_replace('/', '-', $season_end_date_low);
$season_low_end = date('Y-m-d', strtotime($season_end_date_low_convert));
//mid
$season_start_date_mid = get_option('rc_settings_season_start_date_mid');
$season_end_date_mid = get_option('rc_settings_season_end_date_mid');
$season_start_date_mid_B = get_option('rc_settings_season_start_date_mid_B');
$season_end_date_mid_B = get_option('rc_settings_season_end_date_mid_B');
$season_start_date_mid_convert = str_replace('/', '-', $season_start_date_mid);
$season_mid_start = date('Y-m-d', strtotime($season_start_date_mid_convert));
$season_end_date_mid_convert = str_replace('/', '-', $season_end_date_mid);
$season_mid_end = date('Y-m-d', strtotime($season_end_date_mid_convert));
$season_start_date_mid_B_convert = str_replace('/', '-', $season_start_date_mid_B);
$season_mid_B_start = date('Y-m-d', strtotime($season_start_date_mid_B_convert));
$season_end_date_mid_B_convert = str_replace('/', '-', $season_end_date_mid_B);
$season_mid_B_end = date('Y-m-d', strtotime($season_end_date_mid_B_convert));
//High
$season_start_date_high = get_option('rc_settings_season_start_date_high');
$season_end_date_high = get_option('rc_settings_season_end_date_high');
$season_start_date_high_convert = str_replace('/', '-', $season_start_date_high);
$season_high_start = date('Y-m-d', strtotime($season_start_date_high_convert));
$season_end_date_high_convert = str_replace('/', '-', $season_end_date_high);
$season_high_end = date('Y-m-d', strtotime($season_end_date_high_convert));
//Date calculator
//$datetime1 = '01/01/2014';
//$datetime2 = '04/02/2014';
//$duration = 86400 ;
//$days_dur = ceil(strtotime($season_start_date_low)- strtotime($season_end_date_low))/$duration;
//Dates Conversion
$pickupdate_final = $_GET['pickup_date'];
$pickupdate_final_convert = str_replace('/', '-', $pickupdate_final);
$pickup_dates = date('Y-m-d', strtotime($pickupdate_final_convert));
$returndate_final = $_GET['return_date'];
$returndate_final_convert = str_replace('/', '-', $returndate_final);
$return_dates = date('Y-m-d', strtotime($returndate_final_convert));
//Conditions
if($pickup_dates >= $season_low_start && $return_dates <= $season_low_end){
Seasonlow();
echo "low <br />";
}elseif($pickup_dates >= $season_mid_start && $return_dates <= $season_mid_end){
Seasonmid();
echo "mid <br />";
}elseif($pickup_dates >= $season_mid_B_start && $return_dates <= $season_mid_B_end){
Seasonmid_B();
echo "mid_B <br />";
}elseif($pickup_dates >= $season_high_start && $return_dates <= $season_high_end){
SeasonHigh();
echo "High <br />";
}else{
outofseason();
echo "out <br />";
}
?>

include_once('files2.php');
Should be:
include_once('file2.php');

Related

Codeigniter controller cronjob

Hello im using codeigniter and this controller file for cronjob but somehow public function fiveminutes work and gives response(ok) but public function daily doesn’t work and no responses or errors it should give “ok daily” response can someone help please ?? i couldn’t solve this
Hope someone fan help me because its realy important for me and my users
<?php
defined('BASEPATH') or exit('No direct script access allowed');
class Cronjob extends Guess_Controller
{
public function __construct()
{
parent::__construct();
$this->load->model(['m_admin', 'm_cronjob', 'm_leaderboard']);
}
public function fiveminutes()
{
if (time() >= $this->data['settings']['leaderboard_date']) {
$topClaimer = $this->m_leaderboard->getTopClaimer($this->data['settings']['admin_username']);
$topReferral = $this->m_leaderboard->getTopReferral($this->data['settings']['admin_username']);
$topFaucet = $this->m_leaderboard->getTopFaucet($this->data['settings']['admin_username']);
$topShortlink = $this->m_leaderboard->getTopShortlink($this->data['settings']['admin_username']);
$topOfferwall = $this->m_leaderboard->getTopOfferwall($this->data['settings']['admin_username']);
$activityRewards = explode('|', $this->data['settings']['activity_contest_reward']);
$referralRewards = explode('|', $this->data['settings']['referral_contest_reward']);
$faucetRewards = explode('|', $this->data['settings']['faucet_contest_reward']);
$shortlinkRewards = explode('|', $this->data['settings']['shortlink_contest_reward']);
$offerwallRewards = explode('|', $this->data['settings']['offerwall_contest_reward']);
$nextTime = (date("Y-m-d", strtotime('Sunday')) == date("Y-m-d", time())) ? strtotime('Sunday') + 7 * 86400 : strtotime('Sunday');
$this->m_cronjob->updateLeaderboardDate($nextTime);
$this->m_cronjob->resetLeaderboard();
$this->cache->delete('leaderboard_info');
if (!empty($this->data['settings']['activity_contest_reward'])) {
for ($i = 0; $i < min(count($activityRewards), count($topClaimer)); ++$i) {
$this->m_core->addNotification($topClaimer[$i]['id'], currency($activityRewards[$i], $this->data['settings']['currency_rate']) . " from Activity Contest was credited to your balance.", 1);
$this->m_cronjob->updateUserBalance($topClaimer[$i]['id'], trim($activityRewards[$i]));
$this->m_core->addOtherLog($topClaimer[$i]['id'], 'Activity contest #' . ($i + 1), trim($activityRewards[$i]));
}
}
if (!empty($this->data['settings']['referral_contest_reward'])) {
for ($i = 0; $i < min(count($referralRewards), count($topReferral)); ++$i) {
$this->m_core->addNotification($topReferral[$i]['id'], currency($referralRewards[$i], $this->data['settings']['currency_rate']) . " from Referral Contest was credited to your balance.", 1);
$this->m_cronjob->updateUserBalance($topReferral[$i]['id'], trim($referralRewards[$i]));
$this->m_core->addOtherLog($topReferral[$i]['id'], 'Referral contest #' . ($i + 1), trim($referralRewards[$i]));
}
}
if (!empty($this->data['settings']['faucet_contest_reward'])) {
for ($i = 0; $i < min(count($faucetRewards), count($topFaucet)); ++$i) {
$this->m_core->addNotification($topFaucet[$i]['id'], currency($faucetRewards[$i], $this->data['settings']['currency_rate']) . " from Faucet Contest was credited to your balance.", 1);
$this->m_cronjob->updateUserBalance($topFaucet[$i]['id'], trim($faucetRewards[$i]));
$this->m_core->addOtherLog($topFaucet[$i]['id'], 'Faucet contest #' . ($i + 1), trim($faucetRewards[$i]));
}
}
if (!empty($this->data['settings']['shortlink_contest_reward'])) {
for ($i = 0; $i < min(count($shortlinkRewards), count($topShortlink)); ++$i) {
$this->m_core->addNotification($topShortlink[$i]['id'], currency($shortlinkRewards[$i], $this->data['settings']['currency_rate']) . " from Shortlink Contest was credited to your balance.", 1);
$this->m_cronjob->updateUserBalance($topShortlink[$i]['id'], trim($shortlinkRewards[$i]));
$this->m_core->addOtherLog($topShortlink[$i]['id'], 'Shortlink contest #' . ($i + 1), trim($shortlinkRewards[$i]));
}
}
if (!empty($this->data['settings']['offerwall_contest_reward'])) {
for ($i = 0; $i < min(count($offerwallRewards), count($topOfferwall)); ++$i) {
$this->m_core->addNotification($topOfferwall[$i]['id'], currency($offerwallRewards[$i], $this->data['settings']['currency_rate']) . " from Offerwall Contest was credited to your balance.", 1);
$this->m_cronjob->updateUserBalance($topOfferwall[$i]['id'], trim($offerwallRewards[$i]));
$this->m_core->addOtherLog($topOfferwall[$i]['id'], 'Offerwall contest #' . ($i + 1), trim($offerwallRewards[$i]));
}
}
echo 'ok 1';
}
if ($this->data['settings']['lottery_duration'] > 0) {
if (time() >= $this->data['settings']['lottery_date']) {
$lotteries = $this->m_cronjob->getAllLottery();
if (count($lotteries) > 0) {
$luckyNumber = rand(0, count($lotteries) - 1);
$reward = count($lotteries) * $this->data['settings']['lottery_reward'] + $this->data['settings']['lottery_base_reward'];
$this->m_cronjob->updateUserBalance($lotteries[$luckyNumber]['user_id'], $reward);
$this->m_cronjob->insertLotteryHistory($lotteries[$luckyNumber]['user_id'], $lotteries[$luckyNumber]['number'], $reward);
$user = $this->m_core->get_user_from_id($lotteries[$luckyNumber]['user_id']);
$this->m_core->addNotification($user['id'], currency($reward, $this->data['settings']['currency_rate']) . " from Lottery was credited to your balance.", 1);
$this->m_core->addOtherLog($user['id'], 'Lottery', $reward);
}
$this->m_cronjob->updateLotteryDate(time() + 86400 * $this->data['settings']['lottery_duration']);
$this->m_cronjob->resetLottery();
echo 'ok 2';
}
}
$offerHistory = $this->m_cronjob->getAvailableOffers();
foreach ($offerHistory as $history) {
$this->m_cronjob->updateUserBalance($history['user_id'], $history['amount']);
$this->m_cronjob->updateOfferwallHistoryStatus($history['id']);
$user = $this->m_core->get_user_from_id($history['user_id']);
$this->m_core->addExp($user['id'], $this->data['settings']['offerwall_exp_reward']);
$user['exp'] += $this->data['settings']['offerwall_exp_reward'];
if ($user['exp'] >= ($user['level'] + 1) * 100) {
$this->m_core->levelUp($user['id']);
}
}
echo 'ok 3';
$currencies = $this->m_cronjob->getCurrencyName();
$currencyName = [];
foreach ($currencies as $currency) {
array_push($currencyName, $currency['currency_name']);
}
if (!in_array("bitcoin", $currencyName)) {
array_push($currencyName, 'bitcoin');
}
$query = urlencode(implode(',', $currencyName));
$apiUrl = 'https://api.coingecko.com/api/v3/simple/price?ids=' . $query . '&vs_currencies=usd';
$result = #json_decode(get_data($apiUrl), TRUE);
foreach ($result as $name => $price) {
$this->m_cronjob->updatePrice($name, $price['usd']);
}
if (isset($result['bitcoin']) && isset($result['bitcoin']['usd'])) {
$this->m_cronjob->updateBtcPrice($result['bitcoin']['usd']);
}
echo 'ok 4';
}
public function daily()
{
$yesterday = strtotime('yesterday midnight');
$today = strtotime('today midnight');
$date = date("Y-m-d", strtotime('yesterday midnight'));
$todayData = [
'date' => date("Y-m-d", $today)
];
$yesterdayData = [
'date' => $date
];
if ($this->m_cronjob->isYesterdayExist($date)) {
$this->db->insert('faucet_stats', $yesterdayData);
}
if ($this->m_cronjob->checkYesterdayLog($date)) {
$yesterdayData['active_users'] = $this->m_cronjob->countActiveUsers($yesterday, $today);
$yesterdayData['new_users'] = $this->m_cronjob->countNewUsers($yesterday, $today);
$faucetStat = $this->m_cronjob->faucetStat($yesterday, $today);
$yesterdayData['faucet_count'] = $faucetStat['cnt'];
$yesterdayData['faucet_amount'] = $faucetStat['amount'];
$shortlinkStat = $this->m_cronjob->shortlinkStat($yesterday, $today);
$yesterdayData['shortlink_count'] = $shortlinkStat['cnt'];
$yesterdayData['shortlink_amount'] = $shortlinkStat['amount'];
$offerwallStat = $this->m_cronjob->offerwallStat($yesterday, $today);
$yesterdayData['offerwall_count'] = $offerwallStat['cnt'];
$yesterdayData['offerwall_amount'] = $offerwallStat['amount'];
$offerwallStat = $this->m_cronjob->ptcStat($yesterday, $today);
$yesterdayData['ptc_count'] = $offerwallStat['cnt'];
$yesterdayData['ptc_amount'] = $offerwallStat['amount'];
$diceStat = $this->m_cronjob->diceStat($yesterday, $today);
$yesterdayData['dice_count'] = $diceStat['cnt'];
$yesterdayData['dice_amount'] = $diceStat['amount'];
$depositStat = $this->m_cronjob->depositStat($yesterday, $today);
$yesterdayData['deposit_count'] = $depositStat['cnt'];
$yesterdayData['deposit_amount'] = $depositStat['amount'];
$depositStat = $this->m_cronjob->withdrawStat($yesterday, $today);
$yesterdayData['withdraw_count'] = $depositStat['cnt'];
$yesterdayData['withdraw_amount'] = $depositStat['amount'];
$coinflipStat = $this->m_cronjob->coinflipStat($yesterday, $today);
$yesterdayData['coinflip_count'] = $coinflipStat['cnt'];
$yesterdayData['coinflip_amount'] = $coinflipStat['amount'];
$achievementStat = $this->m_cronjob->achievementStat($yesterday, $today);
$yesterdayData['achievement_count'] = $achievementStat['cnt'];
$yesterdayData['achievement_amount'] = $achievementStat['amount'];
$wheelStat = $this->m_cronjob->wheelStat($yesterday, $today);
$yesterdayData['wheel_count'] = $wheelStat['cnt'];
$yesterdayData['wheel_amount'] = $wheelStat['amount'];
$this->db->set('active_users', $yesterdayData['active_users']);
$this->db->set('new_users', $yesterdayData['new_users']);
$this->db->set('faucet_count', $yesterdayData['faucet_count']);
$this->db->set('faucet_amount', $yesterdayData['faucet_amount']);
$this->db->set('shortlink_count', $yesterdayData['shortlink_count']);
$this->db->set('shortlink_amount', $yesterdayData['shortlink_amount']);
$this->db->set('ptc_count', $yesterdayData['ptc_count']);
$this->db->set('ptc_amount', $yesterdayData['ptc_amount']);
$this->db->set('offerwall_count', $yesterdayData['offerwall_count']);
$this->db->set('offerwall_amount', $yesterdayData['offerwall_amount']);
$this->db->set('dice_count', $yesterdayData['dice_count']);
$this->db->set('dice_amount', $yesterdayData['dice_amount']);
$this->db->set('coinflip_count', $yesterdayData['coinflip_count']);
$this->db->set('coinflip_amount', $yesterdayData['coinflip_amount']);
$this->db->set('achievement_count', $yesterdayData['achievement_count']);
$this->db->set('achievement_amount', $yesterdayData['achievement_amount']);
$this->db->set('deposit_amount', $yesterdayData['deposit_amount']);
$this->db->set('deposit_count', $yesterdayData['deposit_count']);
$this->db->set('deposit_amount', $yesterdayData['deposit_amount']);
$this->db->set('withdraw_amount', $yesterdayData['withdraw_amount']);
$this->db->set('wheel_amount', $yesterdayData['wheel_amount']);
$this->db->set('wheel_count', $yesterdayData['wheel_count']);
$this->db->set('is_done', 1);
$this->db->where('date', $date);
$this->db->update('faucet_stats');
$this->db->insert('faucet_stats', $todayData);
$this->m_cronjob->clearHistory();
$this->db->set('wheel_cnt', 0);
$this->db->set('today_faucet', 0);
$this->db->update('users');
echo 'ok daily';
}
}
}
Most likely this function
if($this->m_cronjob->checkYesterdayLog($date))
results to false. I recommend that you should test this first.
if($this->m_cronjob->checkYesterdayLog($date)){
echo 'okay daily';
}else{
echo 'not okay, daily';
}
You can also check if the cronjob actually calls the daily function.

Add missing dates in array

I want to show current week's data. In databse I have some perticular date data I have fill the missing dates and in view page I am showing that by foreach loop because I want to set different values for them. But it is showing mutliple times data because of 2 foreach loop. I want to get result in one array. My code is:
public function cashflowdetails() {
$cashflow = CashModel::orderBy('payment_date','asc') ->get();
$cashflow_array = [];
$cashflowDate_array = [];
$now = Carbon::now();
if (Input::get('from') != '') {
$weekStartDate =Input::get('from') ;
}
else{
$weekStartDate = Carbon::now()->startOfWeek();
}
if (Input::get('to') != '') {
$weekEndDate = Input::get('to');
}
else{
$weekEndDate = Carbon::now()->endOfWeek()->addDay();
}
$period = CarbonPeriod::create($weekStartDate, $weekEndDate);
foreach ($period as $date) {
$dt = new DateTime($date->format("Y-m-d"));
if($dt->format('l')!= 'Sunday' && $dt->format('l')!= 'SUNDAY' && $dt->format('l')!= 'SATURDAY' && $dt->format('l')!= 'Saturday')
{
foreach($cashflow as $cash){
if($date->format("Y-m-d") === $cash->payment_date )
{
$dbData['id'] = $cash->id;
$dbData['payment_date'] = $cash->payment_date;
$d = new DateTime($cash->payment_date);
$dbData['day'] = $d->format('l');
$dbData['opening_balance'] = $cash->opening_balance;
$dbData['other_income'] = $cash->other_income;
$dbData['rent'] = $cash->rent;
$dbData['labour'] = $cash->labour;
$dbData['electricity'] = $cash->electricity;
$dbData['creditors'] = $cash->creditors;
$dbData['insurance'] = $cash->insurance;
$dbData['direct_debits'] = $cash->direct_debits;
$dbData['others'] = $cash->others;
$dbData['total_amount'] = $cash->total_amount;
$dbData['updated_at'] = $cash->updated_at;
$dbData['created_at'] = $cash->created_at;
print_r($cash->payment_date);
$cashflow_array[] = $dbData;
}
else{
$dbData['id'] = null;
$dbData['payment_date'] = $date->format("Y-m-d");
$d = new DateTime($date->format("Y-m-d"));
$dbData['day'] = $d->format('l');
$dbData['labour'] = 0;
$dbData['opening_balance'] = 0;
$dbData['other_income'] = 0;
$dbData['rent'] =0;
$dbData['electricity'] = 0;
$dbData['creditors'] = 0;
$dbData['insurance'] =0;
$dbData['direct_debits'] = 0;
$dbData['others'] = 0;
$dbData['total_amount'] = 0;
$dbData['updated_at'] = '';
$dbData['created_at'] = '';
$cashflowDate_array[] = $dbData;
}
//break;
}
}
}
$cashflow = array_replace($cashflowDate_array, $cashflow_array);
return $cashflow;
}
public function cashflowdetails() {
$cashflow = CashModel::orderBy('payment_date','asc') ->get();
$cashflow_array = [];
$cashflowDate_array = [];
$now = Carbon::now();
if (Input::get('from') != '') {
$weekStartDate =Input::get('from') ;
}
else{
$weekStartDate = Carbon::now()->startOfWeek();
}
if (Input::get('to') != '') {
$weekEndDate = Input::get('to');
}
else{
$weekEndDate = Carbon::now()->endOfWeek()->addDay();
}
$period = CarbonPeriod::create($weekStartDate, $weekEndDate);
foreach ($period as $date)
{
//add a flag to see if the code was executed or not
$isExecuted = false;
$dt = new DateTime($date->format("Y-m-d"));
if($dt->format('l')!= 'Sunday' && $dt->format('l')!= 'SUNDAY' && $dt->format('l')!= 'SATURDAY' && $dt->format('l')!= 'Saturday')
{
foreach($cashflow as $cash){
if( $date->format("Y-m-d") === $cash->payment_date )
{
$dbData['id'] = $cash->id;
$dbData['payment_date'] = $cash->payment_date;
$d = new DateTime($cash->payment_date);
$dbData['day'] = $d->format('l');
$dbData['opening_balance'] = $cash->opening_balance;
$dbData['other_income'] = $cash->other_income;
$dbData['rent'] = $cash->rent;
$dbData['labour'] = $cash->labour;
$dbData['electricity'] = $cash->electricity;
$dbData['creditors'] = $cash->creditors;
$dbData['insurance'] = $cash->insurance;
$dbData['direct_debits'] = $cash->direct_debits;
$dbData['others'] = $cash->others;
$dbData['total_amount'] = $cash->total_amount;
$dbData['updated_at'] = $cash->updated_at;
$dbData['created_at'] = $cash->created_at;
//if executed, assign it true
$isExecuted = true;
//psuh the values to array
$cashflow_array[] = $dbData;
//break the loop
break;
}
}
//if not found in database
if(!$isExecuted){
$dbData['id'] = NULL;
$dbData['payment_date'] = $date->format("Y-m-d");
$d = new DateTime($date->format("Y-m-d"));
$dbData['day'] = $d->format('l');
$dbData['labour'] = 0;
$dbData['opening_balance'] = 0;
$dbData['other_income'] = 0;
$dbData['rent'] =0;
$dbData['electricity'] = 0;
$dbData['creditors'] = 0;
$dbData['insurance'] =0;
$dbData['direct_debits'] = 0;
$dbData['others'] = 0;
$dbData['total_amount'] = 0;
$dbData['updated_at'] = '';
$dbData['created_at'] = '';
$cashflow_array[] = $dbData;
}
}
}
return $cashflow_array;
}
you can achieve it easily by using a variable storing your current date, and double checking if the date is repeating or not.
For example:
//all the below code goes inside the foreach($cashflow as $cash)
//declare variable
$flag = false;
$counter = 0;
if($counter == 0)
{
$dt = new DateTime($date->format("Y-m-d"));
$curDate = $dt;
}else{
$dt = new DateTime($date->format("Y-m-d"));
}
if($curDate == $dt && counter !=0)
{
$flag = true;
}
$counter++;
//on your if conditions if($dt->format('l')!= 'Sunday' && $dt->format('l')!= 'SUNDAY' && $dt->format('l')!= 'SATURDAY' && $dt->format('l')!= 'Saturday')
//please add the condition:
&& flag == false

Why does this code take a long time to execute?

I would appreciate some guidance on the following issue. I am by no means an expert in php. The code below takes almost 10 seconds to execute! Is there anything I am doing that is wrong or bad practice?
$data = [];
$today = date("Y/m/d");
$ThisYear = Date('Y'); //get current Year
$ThisMonth = Date('m'); //get current month
$Tday = '01'; //first day of month
$Tmonth = '09'; //September
if (8 < $ThisMonth && $ThisMonth < 13) {
$AcYear = $ThisYear; }
else {
$AcYear = $ThisYear - 1; // sets start of academic year to be last year
}
$AcFullYear = $AcYear.'/'.$Tmonth.'/'.$Tday;
//find rank in all school
$students_rank = [];
$school_id = Student::model()->findByAttributes(['user_master_id' => Yii::app()->user->id])->school_master_id;
$criteria1 = new CDbCriteria;
$criteria1->with = array('user');
$criteria1->condition = "t.school_master_id=:school_master AND user.status ='1'";
$criteria1->params = array(':school_master' => $school_id);
$school_students_details = Student::model()->findAll($criteria1);
foreach ($school_students_details as $key => $value) {
$student_name = StudentDetails::model()->findByAttributes(['user_master_id' => $value->user_master_id]); //student details with year group
$criteria2 = new CDbCriteria;
$criteria2->with = array('homeworkMaster');
$criteria2->condition = "t.student_id=:student_id AND homeworkMaster.question_type_id<>:question_type_id";
$criteria2->params = array(':student_id' => $value->user_master_id, ':question_type_id' => 6);
$HW_assignment_track = HomeworkAssignmentTrack::model()->findAll($criteria2);
$total_HW = count((array)$HW_assignment_track);
$student_score = 0;
$student_rank = 0;
$student_total_score = 0;
$total_HW_marks = 0;
$under_deadline_HW = 0;
$criteria3 = new CDbCriteria();
$criteria3->condition = "student_id =:student_id AND status=:status AND created_at >= '$AcFullYear' AND created_at <= '$today'";
$criteria3->params = [':student_id' => $value->user_master_id, ':status' => 2];
$student_completed_HW = HomeworkStudentAnswere::model()->findAll($criteria3);
$i = 1;
foreach ($student_completed_HW as $s_c_h_K => $s_c_h_V) {
if ($s_c_h_V->homework->homework_type == 2) {
$total_HW -= 1;
} elseif ($s_c_h_V->homework->homework_type == 1) {
$HW_questions = HomeworkQuestion::model()->findAllByAttributes(['homework_master_id' => $s_c_h_V->homework_id, 'status' => 1]);
foreach ($HW_questions as $qKey => $qVal) {
if ($qVal->question_type_id ==3) {
$total_HW_marks += 2;
} else {
$total_HW_marks += $qVal->marks;
}
}
$assignment = HomeworkAssignmentTrack::model()->findByAttributes(['id' => $s_c_h_V->assignment_track_id]);
$homeworks_within_validate = Assignment::model()->findByPk($assignment->assignment_id);
if ($homeworks_within_validate->valid_date === '0' && $homeworks_within_validate->deadline >= date('Y-m-d')) {
$total_HW -= 1;
}
if ($homeworks_within_validate->valid_date === '1' || (($homeworks_within_validate->valid_date === '0') && ($homeworks_within_validate->deadline >= date('Y-m-d', strtotime($s_c_h_V->created_at))) && ($homeworks_within_validate->deadline < date('Y-m-d')))) {
if ($s_c_h_V->review_status === '2') {
$student_total_score += $s_c_h_V->score;
}
}
$homework_submit = HomeworkCompleteNotification::model()->findByAttributes(['homework_id' => $s_c_h_V->homework_id, 'assignment_track_id' => $s_c_h_V->assignment_track_id, 'student_id' => $value->user_master_id]);
if (($homeworks_within_validate->valid_date === '0') && ($homeworks_within_validate->deadline >= date('Y-m-d', strtotime($homework_submit->created_at))) && ($s_c_h_V->review_status === '2')) {
$under_deadline_HW += 10;
}
if ($total_HW_marks !=0) {
$student_score += round(($student_total_score / $total_HW_marks) * 100);
} else {
$student_score = 0;
}
}
$i += 1;
}
//add revision scores to rank score
$criteria4 = new CDbCriteria();
$criteria4->condition = "user_id =:user_id AND date_created >= '$AcFullYear' AND date_created <= '$today'";
$criteria4->params = [':user_id' => $value->user_master_id];
$revision_score = RevisionScores::model()->findAll($criteria4);
$sum = 0;
foreach($revision_score as $item) {
$sum += $item['score'];
} //end of adding revision scores
$students_rank[$key]['student_id'] = $value->user_master_id;
$students_rank[$key]['year_group'] = $student_name->year_group_id; //added year group to model array
if ($student_score > 0) {
$student_rank += round($student_score / $total_HW, 0) + $under_deadline_HW;
$students_rank[$key]['rank'] = $student_rank + $sum;
} else {
$students_rank[$key]['rank'] = $sum;
}
}
$model = $this->multid_sort($students_rank, 'rank');
$rank_score = round(array_column($model, 'rank', 'student_id')[Yii::app()->user->id],0);
$year_rank =[];
$current_st = StudentDetails::model()->findByAttributes(['user_master_id' => Yii::app()->user->id]);
$current_st_year = $current_st->year_group_id;
$rank_list = [];
foreach ($model as $key => $value) {
$rank_list[] = $value['student_id'];
if ($value['year_group'] == $current_st_year) {
$year_rank[] = $value['student_id'];
}
}
$user = Yii::app()->user->id;
$sch_position = array_search($user,$rank_list);
$yr_position = array_search($user,$year_rank);
$final_rank = $sch_position + 1;
$yr_rank = $yr_position + 1;
$sch_rank = $final_rank;
$ends = array('th','st','nd','rd','th','th','th','th','th','th');
if (($sch_rank %100) >= 11 && ($sch_rank%100) <= 13) {
$sc_abbreviation = 'th';
$yr_abbreviation = 'th';
} else {
$sc_abbreviation = $ends[$sch_rank % 10];
$yr_abbreviation = $ends[$yr_rank % 10];
}
$models = UserMaster::model()->findByPk(Yii::app()->user->id);
$year_name = $models->studentDetails->yearGroup->name;
$data['type'] = 'success';
$data['score'] = '<div>Ranking Score: '.$rank_score.'</div>';
$data['yr_rank'] = '<div><i class="fa fa-trophy rank-i"></i><span class="rank-number">' .$yr_rank. '</span><sup class="script-top" id="year_rank_abb">' .$yr_abbreviation. '</sup></div><div id="year_name">In ' .$year_name. '</div>';
$data['school_rank'] = '<div><i class="fa fa-trophy rank-i"></i><span class="rank-number">' .$sch_rank. '</span><sup class="script-top" id="year_rank_abb">' .$sc_abbreviation. '</sup></div><div id="year_name">In School</div>';
$data['rank_revise'] ='<div>'.$rank_score.'</div>';
$data['yr_rank_revise'] = '<span>'.$yr_rank.'</span><sup class="superscript" style="left:0">'.$yr_abbreviation.'</sup>';
$data['sch_rank_revise'] = '<span>'.$sch_rank.'</span><sup class="superscript" style="left:0">'.$sc_abbreviation.'</sup>';
$_SESSION['rank'] = $rank_score;
$_SESSION['accuracy'] = $rank_score;
echo json_encode($data);
exit;
The above is used in an Yii application. It runs perfectly fine on localhost, but on live site, takes over 10 seconds to execute.
Your help and guidance is appreciated.
Thank

How to get the label in the result of an array

The following code works as expected to get the number of patients per age group.
It also gets the highest (or most common) age group.
$count_0_19 = 0;
$count_20_29 = 0;
$count_30_39 = 0;
$count_40_49 = 0;
$count_50_59 = 0;
$count_above_60 = 0;
$curr_year = date('Y');
$sql= "SELECT pt_dob FROM ptlist WHERE mid=$userID";
$stmt = $pdo->query($sql);
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$result = $pdo->query($sql);
$pt_dob = $row[ 'pt_dob' ];
while($row = $result->fetch(PDO::FETCH_ASSOC)) {
$pt_dob = explode('-', $row['pt_dob']);
$year = $pt_dob[0];
$month = $pt_dob[1];
$day = $pt_dob
$temp = abs($curr_year - $year);
if($temp >= 0 && $temp <= 19) {
$count_0_19++;
}
elseif($temp >= 20 && $temp <= 29) {
$count_20_29++;
}
elseif($temp >= 30 && $temp <= 39) {
$count_30_39++;
}
elseif($temp >= 40 && $temp <= 49) {
$count_40_49++;
}
elseif($temp >= 50 && $temp <= 59) {
$count_50_59++;
}
else {
$count_above_60++;
}
}
echo '0-19: '.$count_0_19.'<br>';
echo '20-29: '.$count_20_29.'<br>';
echo '30-39: '.$count_30_39.'<br>';
echo '40-49: '.$count_40_49.'<br>'; // example output is > 40-49: 7 (i.e. 7 patients in age group 40-49)
echo '50-59: '.$count_50_59.'<br>';
echo '60+: '.$count_above_60.'<br>';
// getting highest value
$a = array($count_0_19, $count_20_29, $count_30_39, $count_40_49, $count_50_59, $count_above_60);
$res = 0;
foreach($a as $v) {
if($res < $v)
$res = $v;
}
echo $res;
^^ This tells me that e.g. 9 patients are in the 30-39 age group - i.e. the highest number of patients are in this age group.
But $res gives me only the number (e.g. 9).
What I am asking your help with is to get $res to give me the text(or label) "30-39", instead of the number 9.
Please help.
continue from comment... you need to store $key into a variable.
$a = array('0-19'=>$count_0_19, '20-29'=>$count_20_29, '30-39'=>$count_30_39, '40-49'=>$count_40_49, '50-59'=>$count_50_59, '60+'=>$count_above_60);
$res = 0;
$label = '';
foreach($a as $key => $v) {
if($res < $v){
$res = $v;
$label = $key; //get label from key and store in a variable
}
}
echo 'label = '.$label . ' , Number = '.$res;
You can archived this by creating the array of labels and then incrementing it according and then find the greatest value form the $label array to get the key.
$label = [
"0_19" => 0,
"20_29" => 0,
"30_39" => 0,
"40_49" => 0,
"50_59" => 0,
"above_60" => 0,
];
while ($row4 = $result4->fetch(PDO::FETCH_ASSOC)) {
$pt_dob = explode('-', $row4['pt_dob']);
$year = $pt_dob[0];
$month = $pt_dob[1];
$day = $pt_dob$temp = abs($curr_year - $year);
if ($temp >= 0 && $temp <= 19) {
$label['0_19'] = $label['0_19'] +1;
}
elseif ($temp >= 20 && $temp <= 29) {
$label['20_29'] = $label['20_29'] +1;
}
elseif ($temp >= 30 && $temp <= 39) {
$label['30_39'] = $label['30_39']+1;
}
elseif ($temp >= 40 && $temp <= 49) {
$label['40_49'] = $label['40_49'] +1;
}
elseif ($temp >= 50 && $temp <= 59) {
$label['50_59'] = $label['50_59']+1;
}
else {
$label['above_60']= $label['above_60']+1;
}
}
echo $maxs = array_keys($label, max($label));
echo "<br/>";
foreach($label as $k => $v);
echo "key $k count $v <br/>";

Fatal error: Call to undefined method DateTime::diff()

When my code is moved from local server to live server it shows an error like this :
Fatal error: Call to undefined method DateTime::diff()
Code:
<?php
date_default_timezone_set('Asia/Calcutta');
$sFinalDate = date('Y-m-d', strtotime($sDate));
$sNow = new DateTime();
$iRemain = new DateTime( $sFinalDate.$sTime);
$iInterval = $iRemain->diff($sNow);
$sTimeCounter = $iInterval->format("%h: %i :%s ");
$sCalculate = $iInterval->format("%a:%h:%i");
?>
Though I found a number of people who ran into the issue of 5.2 and
lower not supporting this function, I was unable to find any solid
examples to get around it. Therefore I hope this can help some others:
<?php
function get_timespan_string($older, $newer) {
$Y1 = $older->format('Y');
$Y2 = $newer->format('Y');
$Y = $Y2 - $Y1;
$m1 = $older->format('m');
$m2 = $newer->format('m');
$m = $m2 - $m1;
$d1 = $older->format('d');
$d2 = $newer->format('d');
$d = $d2 - $d1;
$H1 = $older->format('H');
$H2 = $newer->format('H');
$H = $H2 - $H1;
$i1 = $older->format('i');
$i2 = $newer->format('i');
$i = $i2 - $i1;
$s1 = $older->format('s');
$s2 = $newer->format('s');
$s = $s2 - $s1;
if($s < 0) {
$i = $i -1;
$s = $s + 60;
}
if($i < 0) {
$H = $H - 1;
$i = $i + 60;
}
if($H < 0) {
$d = $d - 1;
$H = $H + 24;
}
if($d < 0) {
$m = $m - 1;
$d = $d + get_days_for_previous_month($m2, $Y2);
}
if($m < 0) {
$Y = $Y - 1;
$m = $m + 12;
}
$timespan_string = create_timespan_string($Y, $m, $d, $H, $i, $s);
return $timespan_string;
}
function get_days_for_previous_month($current_month, $current_year) {
$previous_month = $current_month - 1;
if($current_month == 1) {
$current_year = $current_year - 1; //going from January to previous December
$previous_month = 12;
}
if($previous_month == 11 || $previous_month == 9 || $previous_month == 6 || $previous_month == 4) {
return 30;
}
else if($previous_month == 2) {
if(($current_year % 4) == 0) { //remainder 0 for leap years
return 29;
}
else {
return 28;
}
}
else {
return 31;
}
}
function create_timespan_string($Y, $m, $d, $H, $i, $s)
{
$timespan_string = '';
$found_first_diff = false;
if($Y >= 1) {
$found_first_diff = true;
$timespan_string .= pluralize($Y, 'year').' ';
}
if($m >= 1 || $found_first_diff) {
$found_first_diff = true;
$timespan_string .= pluralize($m, 'month').' ';
}
if($d >= 1 || $found_first_diff) {
$found_first_diff = true;
$timespan_string .= pluralize($d, 'day').' ';
}
if($H >= 1 || $found_first_diff) {
$found_first_diff = true;
$timespan_string .= pluralize($H, 'hour').' ';
}
if($i >= 1 || $found_first_diff) {
$found_first_diff = true;
$timespan_string .= pluralize($i, 'minute').' ';
}
if($found_first_diff) {
$timespan_string .= 'and ';
}
$timespan_string .= pluralize($s, 'second');
return $timespan_string;
}
function pluralize( $count, $text )
{
return $count . ( ( $count == 1 ) ? ( " $text" ) : ( " ${text}s" ) );
}
?>
source http://php.net/manual/en/function.date-diff.php
if you using php 5.3 then there would be another issue
working above example on php>=5.3

Categories