Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to force PHP/Apache to use another year?

Tags:

php

apache

So, I was handed an old project by another employee. It's horribly coded and almost made me quit my job. Twice. Because I don't have that much time (I was given 2 weeks for this task), I can't rewrite the entire thing. I modified it as I was asked, and currently, I'm doing the testings. The problem is, the code should alter it's behavior in other years. The problem with this problem is, that there is no central location where the current year is set, it's all over the code using date("Y") which would force me to change around 200 files.

So, the easiest solution would be to tell PHP in the beginning: "Hey, it's year 20xx". I tried date_default_timezone_set(), but this didn't help me at all. So what I'm looking for is:

  • A PHP-command which changes the current year to the set value (likeSet_Date("Y", 2016);)
  • An Apache-Servercommand which changes the current time (likesetdate -Y 2016)

Is there any way or at least a workaround to make the script think it's another year?

like image 629
Realitätsverlust Avatar asked Dec 04 '15 12:12

Realitätsverlust


4 Answers

You can redefine functions using runkit_function_redefine()
But you need to setup the runkit PECL extension

NOTE : i didn't test it !

<?php 
print date("Y");

$date = 'print "Hello, it is a new definition of date function <" . $Y . ">"; return 2014; ';
runkit_function_redefine('date', '$Y', $date);

date("Y");
like image 197
Halayem Anis Avatar answered Nov 11 '22 12:11

Halayem Anis


It's probably not suitable for your case but I thought I should share this abuse of namespaces:

<?php

namespace FakeTime;

function date($format, $time=null){
    return 2001;
}

var_dump(date('Y'));
like image 31
Álvaro González Avatar answered Nov 11 '22 12:11

Álvaro González


This is a combination of other users suggestion and how to I use libfaketime. No need for a PECL extension.

You can very easily fake the time by modifying /etc/apache2/envvars just add:

export FAKETIME="2015-12-04 12:41:15"
export LD_PRELOAD=/usr/lib/faketime/libfaketime.so.1

Make sure LD_PRELOAD points to the git source. Now restart your apache2 and you'll be back in time right at the point where you'd asked this question!

like image 2
cb0 Avatar answered Nov 11 '22 11:11

cb0


Frist compile libfaketime as suggested https://github.com/wolfcw/libfaketime

Dynamically load baked libfaketime into the scripts you need

if (!extension_loaded('libfaketime')) {
    dl('libfaketime.so');
}

Optional:

Use auto_prepend_file configuration to prepend the dl(.. comand to every file.

Other possible way is to simply compile a second PHP installation and modify the date functions: https://github.com/php/php-src/blob/master/ext/date/php_date.c

like image 1
Daniel W. Avatar answered Nov 11 '22 11:11

Daniel W.