tim.baker
tim.baker

Reputation: 3307

Set Date() to something specific while script executes

I have picked up some legacy code which uses date() all over the place. On the 31st of each month (if applicable) the script has a bug which I need to be able to replicate to fix. In order to do this I need the script to think that it is the 31st today.

Obviously I could parse the date and give it a string of the date that I want, but that would have to be on every instance of date() - which would be very difficult to change and I could miss one all to easily.

Is there a means therefore at the top of the script to specify what "Today's date" is? Or does date() get the date from the server each and every time, rendering this impossible?

Edit

For clarification this script is hosted on Azure App Services which means I can't change the time of the system unfortunately.

Upvotes: 3

Views: 1255

Answers (3)

Amar Pratap
Amar Pratap

Reputation: 1018

Changing the system time is usually restricted to root-level accounts. PHP will be running under the user id of the webserver, which SHOULD NOT BE root. You'll have to use sudo to let the webserver run with elevated privileges for this purpose. See this

Assuming the server is running on windows I believe you could do exec('date 11/24/2013'). If it is a linux based server I think you can do something like this: exec('date -s "24 NOV 2013 12:38:00"').

Command line : Linux Set Date Command Example

Use the following syntax to set new data and time:

date --set="STRING"

For example, set new data to 2 Oct 2006 18:00:00, type the following command as root user:

# date -s "2 OCT 2006 18:00:00"

OR u can also simplify format using following syntax:

# date +%Y%m%d -s "20081128"

Upvotes: -1

maxhb
maxhb

Reputation: 8855

There is an outdated pecl extension called apd which provides a function override_function() which does exactly what you want. Did not test it but it probably won't work anymore.

Another approach is so called monkey patching, making use of phps namespaces. See http://till.klampaeckel.de/blog/archives/105-Monkey-patching-in-PHP.html for example and explanation.

namespace myNameSpace;

function date($format, $timestamp = '') {
    echo 'Would have returned "' . \date($format, $timestamp) . '"';
}
echo date('d.m.Y', time());

As we are in namespace \myNameSpace php will first search for \myNameSpace\date() and use that instead of \date().

Upvotes: 2

Gino Pane
Gino Pane

Reputation: 5011

Maybe you should try to redeclare date for testing purposes? Of course, PHP itself will not allow this, but you can use runkit's runkit_function_redefine():

runkit_function_redefine('date','', 'return "XX-YY-ZZZZ";');

Just note that:

By default, only userspace functions may be removed, renamed, or modified. In order to override internal functions, you must enable the runkit.internal_override setting in php.ini.

Upvotes: 0

Related Questions