Reverb
Reverb

Reputation: 1041

Time() function in PHP

I just wanted to ask, since I'm coding a script, and I'm using time() as a salt for what I am doing.

Now what's happening is I'm salting the data sent from server 1, to server 2. Server 2 checks to see if the data = submitted_data + time() matches exactly. And I wanted to know, since my script will be used on different servers, will the time() function return the same value (if they're located in different parts of the world?)

A code example from the client is:

if($return == md5("true" . time()))

And a code example, where if the data that's submitted correctly, will return this:

echo md5('true' . time());

Both are on different servers in different parts of the world, but I wanted to know if using the time() will mess up the way my system's going to work..?

Upvotes: 3

Views: 120

Answers (2)

sandeep Kumar
sandeep Kumar

Reputation: 121

Why don't you try following :

echo date("Y-m-d H:i") echo strtotime(date("Y-m-d H:i"));

Value of strtotime(date("Y-m-d H:i")); would not change until you pass the next minute OR you can remove "i" based on your requirement.

Hope that helps.

Upvotes: 1

Nathaniel Ford
Nathaniel Ford

Reputation: 21249

This won't work, because time() relies on the system's local clock, which is pretty much guaranteed to not be in sync between any two computers/clocks. Secondly, you cannot guarantee when a given process will be given time by the operating system to run; therefore one server may be milliseconds off simply because it was doing something else intensive. Then you have network latency, etc. etc.

This is a significant issue with distributed systems, which have to keep things 'in sync' without knowing precisely when which actions occurred. (Should this update to the db happen before that one, if the database is spread across multiple servers?) It is best to not rely on time for that reason, but perhaps some other thing, such as a revision number (which is then incremented). For instance:

  • The server sends down data with revision id = 142 (Note '142' is arbitrary for this example)
  • The client makes a change, increments the revision and hashes that.
  • The client sends the data to the server with the hashed revision number.
  • The server increments it's own revision id and hashes it. This should now equal what the client sent.
  • If it doesn't, the server rejects the data send.

This gets you the ability to simulate time without relying on an inconsistent external resource.

Upvotes: 0

Related Questions