PHP - Time Differences
I am making a php/ajax chat, when a post is sent to the chat, a timestamp using mktime() is stored in the database to show when that post was sent. My concern is that I am from England and my timestamp is GMT +0. Will people from different locations around the world see the wrong times that other users post into the chat? If so what do I need to do to make this work ideally?
Thanks Similar Tutorials
What are the differences and implications of UTC time and Zulu time? <?php function getArr(string $time):array { $dateTime = new \DateTime($time); return [ 'time'=>$time, 'timestamp'=> $dateTime->getTimestamp(), 'dateTime' => $dateTime ]; } $arr = getArr('2020-08-05'); $arr_z = getArr('2020-08-05T00:00:00Z'); print_r($arr); print_r($arr_z); echo('equal timestamps: '.($arr['timestamp'] === $arr['timestamp']?'true':'false'));
Array ( [time] => 2020-08-05 [timestamp] => 1596585600 [dateTime] => DateTime Object ( [date] => 2020-08-05 00:00:00.000000 [timezone_type] => 3 [timezone] => UTC ) ) Array ( [time] => 2020-08-05T00:00:00Z [timestamp] => 1596585600 [dateTime] => DateTime Object ( [date] => 2020-08-05 00:00:00.000000 [timezone_type] => 2 [timezone] => Z ) ) equal timestamps: true
With a prior version of Php, this code was acceptable.
$query = sqlsrv_query($conn, $sql);if ($query === false){ exit("<pre>".print_r(sqlsrv_errors(), true));}while ($row = sqlsrv_fetch_array($query)){ $sumUsageKWH += $row[totalUsage];}sqlsrv_free_stmt($query);?>Now, with php 5.6.3, I have to add a couple of things. $query = sqlsrv_query($conn, $sql);if ($query === false){ exit("<pre>".print_r(sqlsrv_errors(), true));}while ($row = sqlsrv_fetch_array($query)){ $sumUsageKWH += $row['totalUsage'];}sqlsrv_free_stmt($query);?>due to an error prompt. Once I make the corrections, I have a new errors all over the place. Is there a difference in defining a variable with 5.6.3? Edited by Butterbean, 10 January 2015 - 01:49 PM. Hi All, I created a website which runs perfectly on one server but now I transferred the website to another server I get all kinds of errors like, Undefined variables and so on. How is this possible. I thought it was all in the code. Marco Hi, I have 2 db fields with timestamp datatype (ClockingInDate and ClockingOutDate) and i am trying to get the difference between them then update the new db called duration with float datatype field. PHP: if (isset($_POST["clockout"])){ $result3=mysqli_query($con, "select * from attendance_records where OracleID='$session_id'")or die('Error In Session'); $row3=mysqli_fetch_array($result3); $end_date = $row3['ClockingOutDate']; $startdate = $row3['ClockingInDate']; $diff = strtotime($end_date) - strtotime($startdate); $fullDays = floor($diff/(60*60*24)); $fullHours = floor(($diff-($fullDays*60*60*24))/(60*60)); $fullMinutes = floor(($diff-($fullDays*60*60*24)-($fullHours*60*60))/60); $duration = $fullMinutes; $query3=mysqli_query($con, "update attendance_records set Duration = '$duration' where OracleID='$session_id' and isdone='$isdone'")or die('Error In Session'); header('location:index.php'); }
* come to think of that again, i always get zero, is it because it never reaches days in my program! I am using this for attendance system so only hours and minutes are used. Please help. Edited March 13, 2020 by ramiwahdanthoughts After being forced to have the server upgraded I am having problems with my 'reset password' pages. What I wondered is, has there been any changes to PHP or MySQL between these versions ? The PHP version was 5.2.9 and is now 5.2.14 The MySQL version was Client API version 5.0.45 and is now Client API version 5.0.90 Some one clicks a link like this. www.site.com/resetpw.php?pwr=a1b2c3d4e5f6 the code would be a 32 char hash that is checked against the database, but my code now (which was never changed before or after the server change) seems to find the database line and update it but show the message that it was invalid ? instead of showing the the message, your password will be sent to you after changing the DB does anyone have any ideas ? Code: [Select] <?php include('includes/connection.php'); include('includes/functions.php'); date_default_timezone_set('Europe/London'); if(isset($_POST['reset']) && trim($_POST['reset']) == 'Reset') { $email = mysql_real_escape_string($_POST['email']); $checkVerify = mysql_query("SELECT account_id FROM customers WHERE email='$email' AND verified='No' LIMIT 1"); $checkBanned = mysql_query("SELECT account_id FROM customers WHERE email='$email' AND suspended='Yes' LIMIT 1"); if(!$email) { $thisError = 'Please enter your e-mail address.'; } else if(!$password) { $thisError = 'Please enter your password.'; } else if(mysql_num_rows($checkVerify)) { $thisError = 'Your account has not been approved by an Admin.'; } else if(mysql_num_rows($checkBanned)) { $thisError = 'Your account has been suspended by an Admin.'; } else { $password = md5($password); $checkAccount = mysql_query("SELECT account_id FROM customers WHERE email='$email' AND password='$password' LIMIT 1"); if(mysql_num_rows($checkAccount)) { $_SESSION['FM_user'] = $email; header('Location: members.php'); exit; } else { $thisError = 'Your e-mail address and/or password is incorrect.'; } } } include('includes/header.php'); ?> <body> <div class="headerBar"> <?php include('includes/navigation.php');?> </div> <?php headerText(); ?> <div class="content"> <div class="widthLimiter contentStyle"> <div class="formWrapper"> <?php if(isset($thisError)) { echo '<div class="errorDiv">',$thisError,'</div>'; } ?> <?php if(isset($thisSuccess)) { echo '<div class="successDiv">',$thisSuccess,'</div>'; } ?> <span class="subHeader">Initiate Password Reset</span> <?php // include("sendmail2010.php"); $securitycode = ($_GET['pwr']); //echo("53:security:".$securitycode.":<br>"); if ($securitycode != "") { $sql = "SELECT * FROM `customers` WHERE `changeofpasswordcode` = '".mysql_real_escape_string($securitycode)."' LIMIT 1"; //echo("54:sql:".$sql.":<br>"); $res = mysql_query($sql) or die(mysql_error()); //echo("57:<br>"); if (mysql_num_rows($res) != 0) { //echo("59:sql:".$sql.":<br>"); $customerName = mysql_result($res, 0 ,'fullname'); $email = mysql_result($res, 0 ,'email'); $yourpasswordtologin = CreateNewPassword(); $format = 'Y-m-d H:i:s'; $date = date( $format ); $sql = "UPDATE `customers` SET `password` = '" . md5($yourpasswordtologin) . "', `password2` = '" . mysql_real_escape_string($yourpasswordtologin) . "', `changeofpasswordcode` = '', `newpasswordrequestedon` = '" . $date . "' WHERE `changeofpasswordcode` = '" . mysql_real_escape_string($securitycode) . "' LIMIT 1"; //echo("65:sql:".$sql.":<br>"); $res = mysql_query($sql) or die(mysql_error()); $_SESSION['customerName'] = $customerName; $_SESSION['customerEmail'] = $email; $_SESSION['generatePass'] = $yourpasswordtologin; //echo("send email"); $sendemailnow = createEmailSend('newPassword', 'Your new password', 'customer'); //echo("email sent ".$sendemailnow); ?><div style="margin: 30px;">Thank you for completing your password reset process.<br><br>An email with a randomly generated password has been sent to your email address, please check your email account for this email as you will need this password to access your <?=$_SESSION['siteName'];?> account.<br><br><strong><em>Please check your 'spam folder' in case our emails are showing up there.</em></strong><br><br>You may now <a href="<?=$_SESSION['webAddress'];?>">sign in</a> to your account.</div><?php //echo("72:end of IF send email<br>"); } else { //echo("74 bad link<br>"); ?><div style="margin: 20px;">Sorry the link you clicked is and old password reset link or is not valid, please delete the email.<br><br>If you were trying to reset your password, please click the<br>'Member Login' link on our site and then click the 'Reset Password' link.</div><?php //echo("end of IF bad<br>"); } //echo("78:end of first IF<br>"); } ?> </div> </div> </div> <?php include('includes/footer.php');?> </body> </html> I don't know if this is the correct type of question to ask here - I built a sandbox about 3 months ago with the latest XAMPP. I know that it came with PHP 5.x [5.2 I think]. I am not at home right now to check it. I just found out that the host server is running 4.4.9. I have no control over the host, or host selection. I am going to attempt to get a database online using basic [I hope] PHP scripts to query the otherwise static database. Are there major differences in the versions that I need to watch out for? I realize that I will now have to get 4.4.9 installed on my sandbox. I plan on using Dreamweaver CS5 to get my pages built. The main site is built and managed by another person using Expression Web 2. I am also unaware if the master.dwt built in Expression can be somehow brought into my PHP for site consistency. I am open to all comments and suggestions. Can someone explain the difference between the following? function a(array $var) { } function a($var = array()) { } function a(Array $var) { } I have seen these recently in a script I am modifying, but not 100% sure as to what each one does. Well I know what the middle one does, but am a little confused on the 1st and 3rd one. Thanks! Dennis I have Win 7 home premium, Apache 2.2 (installed using the .msi) and PHP 5.2.14 (downloaded as "php-5.2.14-Win32-VC6-x86.zip", installed manually, it works) on both machines. The other is 32-bit and the other is 64-bit, both Windows 7 Home Premium. When I run the exactly same script on one machine, it does what it is supposed to (32-bit), but on the 64-bit it does not. Basically this appears in two situations (so far): I have a script that reads a (xml) file into a simplexml object, and if this is not successful, it prints an error message. On the 32-bit machine I can import (read) another xml file at once once the first one is processed (into a sqlite database), but on the 64-bit machine it gives me an error originating from the fact that the script did not manage to create the simplexml object. The other situation is when I want to open a specific PDF - file in a browser window (Firefox, the newest one, on the 32-bit machine, IE something newish on the 64-bit). The file exists, the path to the folder is in the Path environment variable, I can open it normally etc on the 64-bit machine, but when I click on a link that is supposed to open the file in a browser window I only get an error message saying that the file does not start with "%PDF.... Needless to say, the precisely same script works just fine on the 32 bit machine. $path_to_image="D:\\path_to_folder\\"; $file_name=$_GET['file_name']; header("Content-disposition: inline; filename=".$path_to_image.$file_name); header("Content-type: application/pdf"); readfile($path_to_image.$file_name); The above code is from the part that receives the file name from a form (other file). Anyone noticed anything like this? Any suggestions? Have been trying to figure this out for days, now... Oh, forgot: In both cases the thing is accessed as/from "localhost". Hello, I am working on a caching class and all I have left to figure out now is the string compression. I am storing files locally on the server and may eventually expand the option for storing it in the database. But I want to reduce file size while not sacrificing speed as much as possible. The first function I used was the bzip2 bzcompress function. It did a great job with a 92% compression rate, but I noticed a half-second to full-second delay in the decompression. So what I would like to know is does anyone know which compression functions offer the most speed and what their compression ratios look like? This is for a simple string (well XML that I have reduced with some string replacements), so there is no pre-compression to it. The compression libraries available to me on my server are these: zlib, zip, and bz2 Thoughts? Thanks, Patrick PHP date and time function is not showing correct time on my local system I have the following php code date_default_timezone_set("Africa/Lagos"); $date = date('d-m-y h:i:s'); echo "Server Time ".$date ."<br>"; echo "The time is " . date("h:i:sa")."<br>"; $current_datetime = date("Y-m-d") . ' ' . date("H:i:s", STRTOTIME(date('h:i:sa'))); echo "Current time1: ".$current_datetime . "<br>";
Output
Server Time 21-05-21 09:55:39
Expected Output
Server Time 21-05-21 10:55:39
Any help would be appreciated. Edited May 21 by Ponel I am trying to simulate an ad expiration and carry out an action if the ad is expired. And I cannot get the if/else to work properly... I've tried many variations and I cannot see what I am doing wrong here. Any tips please 3 hours and counting of no solution! $ad_start = time()-14 . "<br />"; // 14 days from today in the past (negative) echo $ad_start; $current_time = time() . "<br />"; // current epoch time echo $current_time; $days_past = $ad_start - $current_time; // days past echo "<br />$days_past days have past since the ad started!<br />"; if($days_past <= 14) { echo "<br />Ad is less than 14 days. Not expired."; } else { echo "<br />Ad is over 14 days. Expired."; } Basically I have recently been playing around with parsing a csv file. What I am looking to do at this point is simply take the date/timestamp (part of the csv file), which is in the following format:DD/MM HH:MM:SS.100th/s For the sake of argument, lets say I have this in an array string called $csv[0] and the file has several lines that span the course of a couple hours. I wouldn't mind having to use explode() to breakup/remove the date or 100th/s IF that would make things a lot simpler. So where would I start in trying to achieve this?. The result I am looking for will simply return "X Seconds". Storing this in a string variable would be a bonus, as I plan to use this to divide a separate piece of information. Any examples or ideas would be great. Thank you. ps: Here is an example time from the csv file itself: Code: [Select] 11/19 22:23:18.143 Hello, I tried to implement some PHP code to enable a web page to show "Dinner" specials versus "Lunch" specials based on the time. The business is located in the Eastern Time Zone, so I only need to routine to work based on Eastern Time (New York). What I am noticing is that the server is processing the lines of code so fast that the command to establish the correct time for the remaining code is not always being acknowledged. This line of code appears to be processing too fast for the remaining lines of code: date_default_timezone_set ( "America/New_York" ); Is there some additional code I can put in place to make sure the correct time is always ascertained? I need the $hourmin variable to always return a combination of hour + minute based on 24-hour time and Eastern Time zone. My code is as follows: <?php $name8 = file_get_contents("test/special8name.txt"); date_default_timezone_set ( "America/New_York" ); $gethour = date("H"); $getminutes = $gettimedate["minutes"]; $gettimedate = date(); $hourmin = $gethour . $getminutes; $currentday = date("l", time()); $currentdate = date("M j, Y"); if ($hourmin < 1500 && $currentday <> "Saturday" && $currentday <> "Sunday") { echo "<span class=\"namesred\">$name8 </span>"; } else if ( $hourmin > 1500 && $hourmin < 2300 && $currentday <> "Saturday" && $currentday <> "Sunday") { echo "<span class=\"namesblue\">$name8 </span>"; } else if ( $currentday == "Saturday" or $currentday == "Sunday") { echo "<span class=\"namesblue\">$name8 </span>"; } ?> PHP 5.2.6 We rent PHP server space on a server in California. Several of my pages generated by PHP show the current date and time, so when the page is printed, the user knows when the data was printed. Our users could be anywhere in the US, I am in Michigan. How do I convert the server time (PDT) into local time, regardless of where the user is? Thanks. This topic has been moved to Application Design. http://www.phpfreaks.com/forums/index.php?topic=316461.0 OK So I've got a datepicker that sends a date in d/m/y format. My DB stores the data in Unix Timestamp Which I can convert the date to with strtotime however this does the exact date & time. All I want is the actual day. I've spent hours trying to convert this with just the day with mixed results... Thanks. I am having a problem with PHP displaying the correct date and time. It updates as it should, but is fast by 4min and is always displaying a date in 2004. I ran a basic php script to make sure the application im using itself is not wrong. go to lunenburgledger.com/time.php Anybody had any ideas on where to check? The system time on the Windows Server 2003 is correct. The only thing I can think of is that it was converted to a virtual machine on vmware esxi, but the system time stayed right. Any ideas? Thanks! Let's say I am buying a share for $10. If I sell the share on the same day BEFORE 3:30PM, it will be sold for $10, but if I keep the share past 3:30PM, I want the code to automatically add $1 (Taxes and such) once in the the price of the share in database, after that no matter how many days pass by, the price will remain the same.
I've thought about CRON jobs, but I have no idea how to make/use them or set them up.
Any direction or help is appreciated.
I am making a time clock, and I was wondering what is the best way to calculate the number of hours an employee worked? I have a table called "statuses" it holds names of punch types: - id = the auto_inc - status = "in/out/break/lunch" text statuses - paid = whether or not the punch is paid or not (true/false) I have another table called "logging" This table holds the information about the punch type: - id = the auto_inc - owner = the member id - ip = members ip - inout = the punch type from the statuses table - location = the city/state of where the punch took place - date = the time the member punched Maybe I am over thinking this, but what is the best way to calculate the hours a person has worked? Right now I am getting all the punches for for a particular member between a date range. then loop through the data to display it and passing it to a method in a class called Calc. I want to then add the times from punch in to punch out, then the next punch in to punch out. Any suggestions? I have this: $sql = mysqli_query($conn, "SELECT ip , page , CASE WHEN referrer = '' THEN 'N/A' ELSE referrer END as referrer , DATE_FORMAT(date, '%m/%d/%y') as date , TIME_FORMAT(time, '%T') as time FROM tblTraffic ORDER BY date DESC, time DESC"); most of my traffic report contains the correct times, my time, which is CST in the USA. but some records are off by a lot. Does the time() function capture the time of the actual location from which the visitor is coming from? if so, what could I do to return my timezone for any visitor? w3 schools and php.net don't mention this. |