Results 1 to 10 of 10

Thread: Local User Time

  1. #1
    Join Date
    Apr 2012
    Location
    Central New Jersey
    Posts
    130
    Thanks
    49
    Thanked 0 Times in 0 Posts

    Lightbulb Local User Time

    I have a javascript script that determines the user's time of day and then uses that determination to generate "good morning" "good afternoon" or "good evening", depending on the time. I am pasting that script below.

    Mindful that not all visitors have javascript capability, I want to convert the javascript to PHP. The PHP scripts and functions that I've found seem to base time of day on my server or the visitor's server, either of which could be not the visitor's local time.

    The time of day information that I seek would appear to be available using the Execution operator. I have a few questions:

    1. Am I on the right track?

    2. If so, is Execution the optimal solution?

    3. Is there an existing PHP script equivalent to the javascript below?

    Thanks, as always.

    A.

    Code:
    <script type="text/javascript">
    //<!--						// hide script from primitive browsers
      var bigDisplay;				// will receive portion of day
      var timeis;					// will receive time of day
      var houris;					// will hold current hour
      var welcome;					// will hold line we will build
      var todaydate = new Date();			// instantiate Date object
      timeis = todaydate.getTime();			// apply getTime method to it
      todaydate.setTime(timeis);			// extract time
      houris = todaydate.getHours();		// extract hour
      bigDisplay = "morning";			// set default to "morning."
      if (houris > 11) bigDisplay = "afternoon";	// override default if past morning
      if (houris > 17) bigDisplay = "evening";	// override override if past afternoon
      welcome = ("Good " + bigDisplay + ".");	// set up welcome line
      document.write(welcome);			// write welcome line to document
    //End hiding of (now completed) script -->
    </script>
    <noscript>Welcome.</noscript>&nbsp;&nbsp;Well, maybe it's not so good.

  2. #2
    Join Date
    Apr 2008
    Location
    So.Cal
    Posts
    3,643
    Thanks
    63
    Thanked 517 Times in 503 Posts
    Blog Entries
    5

    Default

    Here's the thing: PHP (executing on your server) has no idea what time it is on the user's computer.

    You could try to "lookup" the timezone based on IP, but this will only be a vaguely educated guess (i.e., likely to often be completely wrong). I don't know of any existing lookup tables/ utilities, but I'm sure they exist somewhere.

    Honestly, I think the <noscript>Welcome.</noscript> you've got is the best solution. If your website is local (e.g., a local business or organization), you could always default to your own timezone (possibly with a mild disclaimer, like "Good Morning from New Jersey!").

  3. #3
    Join Date
    Apr 2012
    Location
    Central New Jersey
    Posts
    130
    Thanks
    49
    Thanked 0 Times in 0 Posts

    Default

    Quote Originally Posted by traq View Post
    Here's the thing: PHP (executing on your server) has no idea what time it is on the user's computer.
    Traq, I missed that simple and elementary fact. Thank you.

    OK, no PHP function can mimic the Javascript. That disposes of question three and, probably, two, also. That still leaves the Execution operator. I see no reason why that can't be harnessed for that purpose. If I can make it work, I'll post my solution.

    A.

  4. #4
    Join Date
    Apr 2008
    Location
    So.Cal
    Posts
    3,643
    Thanks
    63
    Thanked 517 Times in 503 Posts
    Blog Entries
    5

    Default

    I'm sorry; I missed that part of your question. (You do mean the ` operator, yes?)

    No, you don't need to execute a system call to get the time. You can use the DateTime class.
    PHP Code:
    <?php

    $dt 
    = new DateTime'@'.time() );
    $hr $dt->format'G' );
    if( 
    $hr 12 ){
        
    $welcome 'Good Morning'
    }elseif( 
    $hr 18 ){
        
    $welcome 'Good Afternoon'
    }else{
        
    $welcome 'Good Evening'
    }
    Last edited by traq; 12-18-2012 at 01:21 AM. Reason: forgot '@' in DateTime arg

  5. The Following User Says Thank You to traq For This Useful Post:

    marain (12-16-2012)

  6. #5
    Join Date
    Mar 2006
    Location
    Illinois, USA
    Posts
    12,162
    Thanks
    263
    Thanked 690 Times in 678 Posts

    Default

    To help clarify a bit: wherever the code is executing, it knows the time of that computer. So if the code is operating on the server (eg, PHP) then it knows the server's (local) time (which is therefore the same for any user anywhere in the world). And if the code is operating in the browser on the user's computer (eg, Javascript) then it knows the local time on the user's computer, which is relative to where the user is located and will differ for different users.

    Note that it is also possible, through an indirect process, to use the server's time in Javascript, or the browser's time in PHP.
    For the former situation, you would have the server (with PHP) generate the time as a variable in the Javascript code. Basically it would tell the Javascript "it's currently 5pm".
    For the latter situation, you would need to have the Javascript somehow submit the time to the server, which is slightly trickier. This can be done using Ajax or submitting a form. But note that it must involve the user's cooperation and will only work AFTER it has been submitted.


    And Javascript isn't secure-- the visitor can reprogram it as desired, disable it, etc. Usually it will work, but you can't rely on it, especially for something like security. Therefore, the only "secure" system is one involving only PHP. (For example, if you want to forcefully block access to your website at night, it would need to be through PHP, and would not be possible to do this based on the user's time, unless you hoped the information from Javascript was reliable and not manipulated by the user to get around the restriction.)


    Most systems rely on server time, and as needed create a timezone offset for the user. So my server may be in New York. But if you visit from London, then you will have a +5 offset, meaning it is 5 hours later there then on the server. So on my server I would store "+5" for you (with your cooperation), and then the server would know your local time. That's how a forum works, for example. this can either be done based on Javascript and doing the math, or it can be done with the user's help-- "please select your timezone/time offset".


    I hope that helps a bit. It may not directly answer your question (I think traq already has!), but it should clear things up on a few of these topics.
    Daniel - Freelance Web Design | <?php?> | <html>| espa˝ol | Deutsch | italiano | portuguŕs | catalÓ | un peu de franšais | some knowledge of several other languages: I can sometimes help translate here on DD | Linguistics Forum

  7. #6
    Join Date
    Apr 2012
    Location
    Central New Jersey
    Posts
    130
    Thanks
    49
    Thanked 0 Times in 0 Posts

    Default

    Well I've taken the balls that both you and Traq have so kindly thrown, and tried to run with them. They're not working :-(

    When I plug in Traq's code, the page loads, but incompletely, and processing stops. The backtic operator, by itself does not stop the processing, but the PHP code that uses it is ignored. And quite parenthetically, when I attempt to debug it, first by wrapping ALL PHP in html comments, the processor tries to process the PHP anyway! When I comment out all the PHP individual statements, the page (not surprisingly) runs perfectly.

    The most recent attempt follows. You can run this on http://www.marainlaw.com/page.php?here=test. Page source shows no clue that PHP is involved.

    Finally, if I am abusing your kindness with my return visits, please feel free to tell me so.

    Best,

    A.

    Code:
    <?php
    $lastUpdate = date( 'j F Y', filemtime( 'pageContent/index.txt' ) );
    ?>
    <br />
    Mark One.
    
    
    <?php
    echo "<br />
    <br />
    Begin grand experimentation.
    <br />
    <br />
    ";
    $dosdata = `time`;
    echo $dosdata;
    $dosdata = `dir`;
    echo $dosdata;
    echo 'Mark Two.';
    ?>
    <br />
    <br />
    Mark Three.
    <br />
    <br />
    <?php
    #$dt = new DateTime( time() );
    #$hr = $dt->format( 'G' );
    #if( $hr < 12 ){
    #    $welcome = 'Good Morning'; 
    #}elseif( $hr < 18 ){
    #    $welcome = 'Good Afternoon'; 
    #}else{
    #    $welcome = 'Good Evening'; 
    #}
    #echo $welcome;
    ?>
    
    
    <br />
    <br />
    End of traq-suggested coding
    <br />
    <br />
    A.

  8. #7
    Join Date
    Apr 2008
    Location
    So.Cal
    Posts
    3,643
    Thanks
    63
    Thanked 517 Times in 503 Posts
    Blog Entries
    5

    Default

    Quote Originally Posted by marain View Post
    When I plug in Traq's code, the page loads, but incompletely, and processing stops.
    I formatted the DateTime() argument incorrectly. I've corrected it now (and in my code below).

    Quote Originally Posted by marain View Post
    The backtic operator, by itself does not stop the processing, but the PHP code that uses it is ignored.
    I would still recommend against using the backtick operator: it's both unnecessary, and adds a layer of complexity.

    Quote Originally Posted by marain View Post
    And quite parenthetically, when I attempt to debug it, first by wrapping ALL PHP in html comments, the processor tries to process the PHP anyway!
    Why would you try to comment out PHP code by using HTML comment tags?

    Quote Originally Posted by marain View Post
    The most recent attempt follows. You can run this on http://www.marainlaw.com/page.php?here=test. Page source shows no clue that PHP is involved.
    Nor should it. HTML has no clue that PHP even exists. Perhaps we need to clear this up:

    • PHP executes first, on the server.
      PHP writes text (usually HTML). When PHP is done, it outputs the result to the browser.
      .
    • HTML is parsed by the browser, on the user's computer.
      At this point, PHP is "no more" - there is absolutely no way for the browser to distinguish between HTML generated by PHP, or the same markup coded statically by hand. Neither can the two interact.


    Quote Originally Posted by marain View Post
    Finally, if I am abusing your kindness with my return visits, please feel free to tell me so.
    not at all.

    ----------------------
    Could you try two things?

    First, try running this, *all by itself* in a new php file, and share the results.
    PHP Code:
    <?php
    $dt 
    = new DateTime'@'.time() );
    $hr $dt->format'G' );
    if( 
    $hr 12 ){
        
    $welcome 'Good Morning'
    }elseif( 
    $hr 18 ){
        
    $welcome 'Good Afternoon'
    }else{
        
    $welcome 'Good Evening'
    }
    echo 
    $welcome;
    Second, add this to the *very top* of your script, and see if you get any error messages.
    PHP Code:
    <?php
    error_reporting
    ( -);
    ini_set'display_errors','On' );
    ?>
    Last edited by traq; 12-18-2012 at 04:16 AM.

  9. #8
    Join Date
    Mar 2006
    Location
    Illinois, USA
    Posts
    12,162
    Thanks
    263
    Thanked 690 Times in 678 Posts

    Default

    Finally, if I am abusing your kindness with my return visits, please feel free to tell me so.
    Same here-- no problem. I'm particularly busy at the moment so that's why I'm not more actively participating in the conversation, and traq clearly has it covered anyway. But you're not asking too much of us I don't think
    Daniel - Freelance Web Design | <?php?> | <html>| espa˝ol | Deutsch | italiano | portuguŕs | catalÓ | un peu de franšais | some knowledge of several other languages: I can sometimes help translate here on DD | Linguistics Forum

  10. #9
    Join Date
    Apr 2012
    Location
    Central New Jersey
    Posts
    130
    Thanks
    49
    Thanked 0 Times in 0 Posts

    Default

    Traq,

    This responds to your request for feedback: The code that you asked me to try ran, except that it echo'd "Good afternoon" even though it ran before 9:00 a.m. local time.

    Inserting

    PHP Code:
    <?php
    error_reporting
    ( -);
    ini_set'display_errors','On' );
    ?>
    ... and running, yielded over 100 error messages. Only one of them related to this thread:

    Strict Standards: DateTime::__construct() [datetime.--construct]: It is not safe to rely on the system's timezone settings. Please use the date.timezone setting, the TZ environment variable or the date_default_timezone_set() function. In case you used any of those methods and you are still getting this warning, you most likely misspelled the timezone identifier. We selected 'America/Denver' for 'MST/-7.0/no DST' instead in /var/www/html/pageContent/test.txt on line 10

    All of the other message related to a single line in an included file. The error reporting lines are still on the test file in case on some wild impulse you care to run it yourself. (I'll be looking more deeply into that at some future time.)

    As to
    Why would you try to comment out PHP code by using HTML comment tags?
    , for debugging purposes, I wanted to try to isolate the problem by removing everything, and then restoring portions, piece by piece. My thinking was this: I am in html and not PHP until <?php comes along. But if <?php comes along in code that has been commented out, it would be treated as part of the html comment. (Wrong!)

    A.

  11. #10
    Join Date
    Apr 2008
    Location
    So.Cal
    Posts
    3,643
    Thanks
    63
    Thanked 517 Times in 503 Posts
    Blog Entries
    5

    Default

    Quote Originally Posted by marain View Post
    The code that you asked me to try ran, except that it echo'd "Good afternoon" even though it ran before 9:00 a.m. local time.
    You used the time(), correct? The timestamp should be forcing DateTime to use UTC (which is always a good idea for servers; you can convert to local time afterwards). Try this instead:
    PHP Code:
    $dt = new DateTime'now',new DateTimeZone'UTC' ) ); 
    It should give you UTC time (i.e., +0:00). If you want to use a local time to start, use one of these instead of "UTC."
    Quote Originally Posted by marain View Post
    yielded over 100 error messages. Only one of them related to this thread
    Life is great, huh? Welcome to the wonderful world of debugging!

    The shell_exec error refers to your use of the backtic operator (which is _exactly_ the same as using shell_exec()): you web host has disabled it. This is not uncommon at all, especially on shared hosts, since it gives full access to the server's system.

    Most of the other warnings are about missing variables. You need to go through each script, near the lines the error mentions, and backtrack to make sure you've defined those variables somewhere.

    Quote Originally Posted by marain View Post
    As to , for debugging purposes, I wanted to try to isolate the problem by removing everything, and then restoring portions, piece by piece. My thinking was this: I am in html and not PHP until <?php comes along. But if <?php comes along in code that has been commented out, it would be treated as part of the html comment. (Wrong!)
    Well, good thinking (debugging)! However, as I mentioned in my last post, you don't switch "back and forth" between PHP and HTML. It's all PHP, and then the output is all HTML. I blogged about this a while back, if you're interested.

    To comment out PHP code, you need to use PHP comments:
    PHP Code:
    <?php
    // single-line comment

    /*
    multi
    line
    comment
    */

    # alternate single-line comment
    # (I only use these when I want to differentiate from other comments, 
    #  such as making my comments look different than another person's comments.)

  12. The Following User Says Thank You to traq For This Useful Post:

    marain (12-18-2012)

Similar Threads

  1. Local Time Script - Time Format
    By MizzBia in forum Dynamic Drive scripts help
    Replies: 8
    Last Post: 06-20-2011, 12:37 PM
  2. Local Time script not displaying time at all
    By kittiekat in forum Dynamic Drive scripts help
    Replies: 6
    Last Post: 01-26-2010, 01:46 AM
  3. Format time stamp to Local time zone
    By unitedlocalbands in forum JavaScript
    Replies: 2
    Last Post: 09-18-2007, 06:00 PM
  4. Replies: 2
    Last Post: 10-22-2006, 01:25 PM
  5. Local Time Script - Military time?
    By ebrad in forum Dynamic Drive scripts help
    Replies: 4
    Last Post: 11-23-2005, 07:08 PM

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •