I have a problem in relation with the time now in Codeigniter.
I'm using the timespan function in codeigniter. I have to get the current time and it returns a wrong current time now. My date in my pc(as of now) is 2013-07-04 3:21 PM but when I do this:
$now = time();
$human = unix_to_human($now);
echo $human;
The output is 2013-07-05 12:20 AM. Why is that?
place this code at the top of your index.php (bootstrap file).
if( ! ini_get('date.timezone') )
{
date_default_timezone_set('Asia/Dhaka');
}
instead of 'Asia/Dhaka' use your own time zone. should do the work.
It return the web server time, not your pc time. Try setting the time zone to your location.
I have solved this in CodeIgniter with a Helper class like this:
<?php
namespace App\Helpers;
use CodeIgniter\I18n\Time;
class DateHelper {
public static function getTime($dateString = 'now'){
$time = new Time($dateString);
if(!$time->getDst()){
$time = $time->subHours(1);
}
return $time;
}
public static function getNowString(){
return static::getTime()->format('Y-m-d H:i:s');
}
}
I basically use this function:
/**
* ( function from CodeIgniter\I18n\Time )
* Are we in daylight savings time currently?
*
* #return boolean
*/
public function getDst(): bool
To check if we are currently in daylight savings time,
if so I subtract 1 hour . This works for me, my timezone is Europe/Lisbon which is being used by default because I've configured it in app/config/App.php by changing the following variable:
public $appTimezone = 'Europe/Lisbon';.
Related
I am using Laravel 8 and Jdf and I want to convert the date and time to timestamp, but it is always 0, I do not know why.
I want the start date and end date to be timestamped
file AdminController.php
public function add_incredible_offers(Request $request)
{
$date1=$request->get('date1');
$date2=$request->get('date2');
$offers_first_time=getTimestamp($date1,'first');
$offers_last_time=getTimestamp($date2,'last');
return $offers_first_time;
}
file helpers.php
See the image here file helpers.php
You're sending parameters to the function in wrong order.
change
$offers_first_time=getTimestamp($date1,'first');
$offers_last_time=getTimestamp($date2,'last');
to
$offers_first_time=getTimestamp('first',$date1);
$offers_last_time=getTimestamp('last',$date2);
alternatively you can easily use Carbon.
$offers_first_time = \Carbon\Carbon::make($request->input('date1'))->timestamp;
$offers_last_time = \Carbon\Carbon::make($request->input('date1'))->timestamp;
In the database I have a salary for each of my staff.
I need to work out how much tax to deduct from the salary, but I don't think I would be correct to hardcode this into each view, something like...
{{($bob->salary - 12,000) * 0.2}}
It's obviously messy and repeated.
What I think I need to do is create a function where I can simply feed Bob's salary, it calculates the tax and returns the value.
Something like...
public function taxPayable($salary){
$taxThreshold = 12,000;
$taxRate = 0.2;
if($salary >= $taxThreshold){
$taxPayable = ($salary - $taxThreshold) * $taxRate;
} else {
$taxPayable = 0;
}
return $taxPayable;
}
Then simply..
{{Taxcalculator::taxPayable($bob->salary)}}
Would something like this be possible? Where would I put the function, in a controller or model? Obviosuly the code wouldn't work but just to show what I want to achieve, just wondering how I would achieve it, is this possible? thanks.
You can create a custom Helper class and use that in your Controller to perform the same:
Step 1: Create your Helpers (or other custom class) file and give it a matching namespace. Write your class and method:
<?php // Code within app\Helpers\Helper.php
namespace App\Helpers;
class Helper
{
public static function taxPayable($salary)
{
// perform your calculation here
return $taxPayable;
}
}
Step 2: Create an alias:
<?php // Code within config/app.php
'aliases' => [
...
'Helper' => App\Helpers\Helper::class,
...
Step 3: Run composer dump-autoload in the project root
Step 4: Use this class anywhere in your Laravel app:
<?php // Code within app/Http/Controllers/SomeController.php
namespace App\Http\Controllers;
use Helper;
class SomeController extends Controller
{
public function __construct()
{
Helper::taxPayable($bob->salary);
}
Even you can use this in your view also like:
{{Helper::taxPayable($bob->salary);}}
In your User model you can set accessor.
You may also use accessors to return new, computed values from existing attributes:
/**
* Get the user's tax payable regarding salary amount.
*
* #return float
*/
public function getTaxPayableAttribute()
{
$taxPayable = 0;
$taxThreshold = 12000;
$taxRate = 0.2;
if ($this->salary >= $taxThreshold) {
$taxPayable = ($this->salary - $taxThreshold) * $taxRate;
}
return $taxPayable;
}
Then simply you can use it as newly computed attrribute:
{{($bob->taxPayable}}
or anywhere in PHP code beside blade file. Docs.
Please help. I'm working on a site that debut at specific date and time. Tutorials are being displayed to every students on date set on each tutorials. However, I want the tutorials to debut not just by the date and time set on each tutorials but also based on the timezone set on each tutorial. For example, if a tutorial is set to debut today at 8:00pm Eastern Standard Time (EST) of the United States, it should debut at that time instead of debuting at the application set timezone.
I wrote the below code using Laravel collection filter() which seems to do the trick. However, the page is taking longer to load and I'm unable to use laravel paginate(). I need to use Laravel paginate() to reduce the number of records being pulled at once. There are over four thousand tutorials. Please help.
// upcoming tutorials
$tutorials = Tutorial::orderBy('id', 'desc)->paginate(20);
$futureTuts = $tutorials->filter(function ($value, $key) {
$today = new \DateTime('now');
$show_date = new \DateTime($value->show_date, new \DateTimeZone($value->timezones->name));
return $show_date > $today;
});
$upcoming_tuts = $futureTuts->all();
Please any solutions around this to be able to use Laravel default paginate(). I believe using Laravel pagination will cause the page to load faster. I'm using Laravel 5.4.
Thanks
try to use datatable can filter your data from database as api
here is package
yajra/laravel-datatables-oracle
and if you want to use as published try something different like this
add a column as published_at
$table->dateTime('published_at');
than in your model define your table
protected $dates = ['published_at'];
public function setPublishedAtAttribute($date){
$this->attributes['published_at'] = Carbon::createFromFormat('Y-m-d', $date);
}
public function scopePublished($query)
{
$query->where('published_at', '<=', Carbon::now());
}
public function scopeUnpublished($query)
{
$query->where('published_at', '>', Carbon::now());
}
public function getCreatedAtAttribute($date)
{
return $this->asDateTime($date)->toFormattedDateString();
}
now you can use published scope in your controller like this
$tutorials = Tutorial::orderBy('created_at', 'desc')->published()->paginate(5);
After the last two comments, I'll dump out my real code and maybe it will help out:
Here is the landing Controller:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Businessbuilder extends CI_Controller {
function __construct()
{
parent::__construct();
}
function index()
{
$RTR = $GLOBALS["RTR"];
// import the necessary libraries
$this->load->model("site_pages");
$RTR = $GLOBALS["RTR"];
// get the current site
$site = current_site();
// get the requesting url
$class = $RTR->uri->rsegments[1];
$function = $RTR->uri->rsegments[2];
// get the current function and class
$current_method = explode("::", __METHOD__);
// get the real class name that is going to be called
$site_page = $this->site_pages->get(array("display_name"=>$class, "id"=>$site->id));
$site_page = $site_page->result();
if(count($site_page) == 1)
{
$site_page = $site_page[0];
// set the class name to be called
$class = $site_page->class_name;
}
// only execute if the requested url is not the current url
if(!(strtolower($class) == strtolower($current_method[0]) && strtolower($function) == strtolower($current_method[1])))
{
if(!file_exists(APPPATH.'controllers/'.$RTR->fetch_directory().$class.EXT))
{
show_404($RTR->fetch_directory().$class);
exit;
}
// include the required file. I use require once incase it is a file that I've already included
require_once(APPPATH.'controllers/'.$RTR->fetch_directory().$class.EXT);
// create an instance of the class
$CI = new $class();
if(method_exists($CI, $function))
// call the method
call_user_func_array(array(&$CI, $function), array_slice($RTR->uri->rsegments, 2));
else
{
show_404($RTR->fetch_directory().$class);
exit;
}
}
}
}
here is an example of a dynamic controller that will be called:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Public_homepage extends CI_Controller {
function __construct()
{
parent::__construct();
}
function index()
{
echo "<br /><br /><br />";
$this->load->model("sites");
$style = $this->sites->get(array("id"=>1)); // fail here, sites not defined
//print_r($style);
exit;
$view_params = array();
$view_params["site_id"] = $this->site_id;
$this->load->view('public_homepage', $view_params);
}
}
Here is my model that I am using:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Sites extends CI_Model
{
function __construct()
{
parent::__construct();
}
function get($search = array())
{
return $this->db->query("SELECT * FROM sites"); // failure on this line, db undefined
}
}
the error that I am getting is either this (error1):
A PHP Error was encountered
Severity: Notice
Message: Undefined property: Public_homepage::$sites
Filename: controllers/public_homepage.php
Line Number: 15
Fatal error: Call to a member function get() on a non-object in /var/www/businessbuilderapp.com/public_html/application/controllers/public_homepage.php on line 15
or this (error2):
A PHP Error was encountered
Severity: Notice
Message: Undefined property: Businessbuilder::$db
Filename: core/Model.php
Line Number: 50
Fatal error: Call to a member function query() on a non-object in /var/www/businessbuilderapp.com/public_html/application/models/bba_model.php on line 25
My theory as to why I am getting these errors is because the instance of the object is different than the one that loaded the model and libraries. What's odd about that though is that arrays are carried over, but not objects. So in the core Loader.php of codeigniter array $_ci_models is populated with models that are not loaded in the Public_homepage class
Also what might help you is that from the first pass through the businessbuilder class, I am able to load and use the modules successfully, but when Public_homepage is called, that's when things start to fail.
What makes this confusing is that I'm trying to figure out 2 errors with one question which is probably my mistake. Here is a description of when I get the errors:
Error1:
When I run the code as is, I cannot call the sites property.
Error2:
When I change the
call_user_func_array(array(&$CI, $function), array_slice($RTR->uri->rsegments, 2));
to
eval($class . "->" . $function);
I understand that this is really confusing, especially when I explain it, but if you need more info, please let me know. Also note that the Public_homepage looks like that because I am testing. There's no need to dump more useless lines if the error can be produced with minimal code.
Update
After reading some of the answers, I realized that I didn't explain the code. What this code does is that it allows me to store different urls inside a database, but all the urls stored there can call the same page even though they are different. I guess an exact example would be changing the slug on wordpress.
What happens is that the businessbuilder class is set to accept ALL requests to the server. When it hits the businessbuilder class, it will access the database, find out what sub url you are using, find the real controller that the user is looking for, and access that controller.
So after lots of searching, I think I have a workaround. The issue what what I thought with the instance. After diving into the framework I realized that it is storing the instance into as static var, private static $instance. I modified the constructor to not overwrite if that var has been populated. On top of that, since there were some oddities still with the loading, for some reason objects would be marked as loaded but in reality were not, I had to add a new var to the controller, protected $ci_instance. In the end, I modified the CI_Controller to look like the following:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
* CodeIgniter
*
* An open source application development framework for PHP 5.1.6 or newer
*
* #package CodeIgniter
* #author ExpressionEngine Dev Team
* #copyright Copyright (c) 2008 - 2011, EllisLab, Inc.
* #license http://codeigniter.com/user_guide/license.html
* #link http://codeigniter.com
* #since Version 1.0
* #filesource
*/
// ------------------------------------------------------------------------
/**
* CodeIgniter Application Controller Class
*
* This class object is the super class that every library in
* CodeIgniter will be assigned to.
*
* #package CodeIgniter
* #subpackage Libraries
* #category Libraries
* #author ExpressionEngine Dev Team
* #link http://codeigniter.com/user_guide/general/controllers.html
*/
class CI_Controller {
private static $instance;
protected $ci_instance; // line added
/**
* Constructor
*/
public function __construct()
{
if(self::$instance == null) // line added
self::$instance =& $this;
$this->ci_instance =& get_instance(); // line added
// Assign all the class objects that were instantiated by the
// bootstrap file (CodeIgniter.php) to local class variables
// so that CI can run as one big super object.
foreach (is_loaded() as $var => $class)
{
$this->$var =& load_class($class);
}
$this->load =& load_class('Loader', 'core');
$this->load->_base_classes =& is_loaded();
$this->load->_ci_autoloader();
log_message('debug', "Controller Class Initialized");
}
public static function &get_instance()
{
return self::$instance;
}
}
// END Controller class
/* End of file Controller.php */
/* Location: ./system/core/Controller.php */
The only issue so far is that I cannot do $this->load->model("some_model");. Instead I have to use $this->ci_instance->load->model("some_model"); and everything will stem from there. I don't really care about the extra var, but what I don't like is modifying out of box solutions because it increases the complexity to do an upgrade.
for now I've marked this as an answer because it is what "I" have chosen to use as my solution, but I am still opened to a better solution than the one I am using. An exact description of what needs to be solved is as follows:
Copy all loaded properties from one instance to another. Basically do a merger of two instances if possible.
If someone can answer that with a better solution than mine, preferably without modifying the codeigniter core, I'd gladly change my answer because I am not happy with my solution because I don't know what effects I might encounter later on during development.
In your application/autoload.php set codeigniter to load database class.
$autoload['libraries'] = array('database', 'otherlibrary', 'otherlibrary2');
It must be all you need to solve your problem.
if u using HMVC just using
Class Models extends MX_Loader{
function getUser($username){
$sql="SELECT
*
FROM
user
WHERE username = ? "
return $this->db->query($sql,array($username))->row();
}
}
i have this code in my controller
class Upload_center extends Controller
{
function __construct()
{
parent::Controller();
$this->load->model('auth_model') ;
if(!$this->auth_model->authorize())
{
redirect('login');
}
}
and I have this code in my view
$('#swfupload-control').swfupload({
upload_url: "<?=base_url()?>index.php/upload_center/upload",
file_post_name: 'fileupload',
file_size_limit : "200000000",
file_types : "*.zip;*.rar;*.pdf;*.doc;*.docx;*.mp3;*.avi;*.wmv;*.docx;*.jpg;*.jpeg;*.JPG;*.JPEG;*.png;*.gif;*.bitmap;",
file_types_description : "zip files ",
post_params: {"PHPSESSID": "<?=$this->session->userdata('session_id');?>"} ,
file_upload_limit : 1,
flash_url : "<?=base_url()?>js/jquery-swfupload/js/swfupload/swfupload.swf",
button_image_url : '<?=base_url()?>js/jquery-swfupload/js/swfupload/wdp_buttons_upload_114x29.png',
button_width : 114,
button_height : 29,
button_placeholder : $('#button')[0],
debug: false
I want the user to upload their files after login, so I have a method that needs users to login before proceeding to upload files. Although I'm using flash uploader in my view, I think it doesn't pass the session value and PHP thinks the user is not logged in and it redirects him to the login page. I send phpsessionid by post but still no goes.
What's your session cookie expiration set to? There is a known bug in CodeIgniter where, if you stay on a page that makes AJAX requets past the cookie expiration, it will reset the session id in the database, but will not be able to set it in the browser cookie because it's an asynchronous request. This causes there to be a disconnect on the next non-asynchronous GET request, leading to the session library calling sess_destroy(). If this sounds like your situation, let me know. Otherwise, provide more detail, please.
Edit: I should, perhaps, also include the fix for this bug here. Create a file in /application/libraries called "MY_Session.php" (if it doesn't already exist). In there you can paste this:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/*
* Session Class Extension
*/
class MY_Session extends CI_Session {
/*
* Do not update an existing session on ajax calls
*
* #access public
* #return void
*/
function sess_update() {
if ( !isAjax() ){
parent::sess_update();
}
}
}
?>
That isAjax() function is a helper I have in /application/helpers/isajax_helper.php that looks like this:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
* is_ajax_call
*
* Determines if the current page request is done through an AJAX call
*
* #access public
* #param void
* #return boolean
*/
if ( ! function_exists('isAjax')) {
function isAjax() {
return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest';
}
}
?>
Which is referenced in my config file like this:
$autoload['helper'] = array('otherhelper1', 'isajax', 'otherhelper2');
By default, CI creates a new sessionid in a defined interval. Look at the config to see the default value (I believe it's 5 minutes). So $this->session->userdata('session_id') will always contain a different ID but CI still is able to know who you are.
I ran into the problem for the exact same reason. I know why the CI guys created this session refreshment but I feel like it is making things more complex. You can override this behaviour in your config by simply entering a higher value for the session refresh.
In one of my apps, it looks like this:
$config['sess_expiration'] = 7200;
//$config['sess_time_to_update'] = 300;
$config['sess_time_to_update'] = $config['sess_expiration'];
This way, I'm able to use sessions as I would do without the framework.
not possible. The Session class does not utilize native PHP sessions.
best practice I recommend you
contoller contain uploadpage {
function index(){
$dataview['session_id'] = $this->secureUpload();
$this->load->view('upload',$dataview);
}
function secureUpload(){
$user_id = $this->session->userdata('cuser_id');
$md5pass = $this->basemodel->_getEncrypPassFromDb($user_id);
$time =time();
$session = md5($user_id.$time.$md5pass)."x".$user_id."x".$time;
return $session;
}
}
upload page
('#swfupload-control').swfupload({
post_params: {"PHPSESSID": "<?=session_id?>"} ,
this way decryp you secure code
function upload_function(){
list($session2, $user_id, $time) = explode("x", $session);
$this->load->library('upload', $config);
$md5pass = $this->basemodel->_getMD5pass($user_id);
$session_server = md5($user_id.$time.$md5pass)."x".$user_id."x".$time;
if($session_server == $session){
upload file by flash upload
}
}
I was just having this problem, ajax calls destroying my logged in user session. Here's #treeface solution with CI 2.1.2 per Mr. Sturgeon's suggestion. I guess the input and load libraries are not autoloaded in CI_Session, so I had to get the instance of the CI object to make this work.
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/*
* Session Class Extension
*/
class MY_Session extends CI_Session {
protected $_CI;
/*
* Do not update an existing session on ajax calls
*
* #access public
* #return void
*/
function sess_update() {
$this->_CI =& get_instance();
if ( !$this->_CI->input->is_ajax_request() ){
parent::sess_update();
}
}
}
I think you should see this
http://ellislab.com/forums/viewthread/138823/
It explains to get rid of the problem