Please forgive me, I'm just beginning to study PHP, but I'm pretty well stuck on this sample project that my tutor gave me to figure out.
The goal is to first display the local time of 4 preset timezones, then allow for the user to enter a time manually and on submit, display the time for each of the 4 times relative to the time that was manually entered.
It's also important to do a check that the user input is valid and not just pass any input on regardless of what it may be.
Something is not correct with my IF statement and no input matches, but I haven't been able to see the issue..
Would appreciate if anyone could point me in the right direction. I've been reading thru the documentation on PHP.net quite extensively and have read thru everything on dateTime already but perhaps I'm just not putting it all together yet.
<?php
$timezones = array(
'EST' => -5*3600, //equador
'UTC' => 0, //london
'CCT' => +8*3600, //beijing
'PST' => -8*3600, //los angeles
);
foreach ($timezones as $time) {
$now = time();
$now += $time;
print gmstrftime('DATE: %B %d %Y and TIME: %r <br/>',$now);
}
$nowM = date('m');
$nowD = date('d');
$nowY = date('Y');
$nowHr = date('h');
$nowMin = date('i');
$nowSec = date('s');
?>
<form action="homework2.php" method="post">
<label>Sync Timecode</label>
<input type="text" name="month" placeholder="Month <?php $nowM ?>" value="<?php $nowM ?>" />
<input type="text" name="day" placeholder="Day <?php $nowD ?>" value="<?php $nowD ?>" />
<input type="text" name="year" placeholder="Year <?php $nowY ?>" value="<?php $nowY ?>" />
<input type="text" name="hour" placeholder="Hours <?php $nowHr ?>" value="<?php $nowHr ?>" />
<input type="text" name="min" placeholder="Minutes <?php $nowMin ?>" value="<?php $nowMin ?>"/>
<input type="text" name="sec" placeholder="Seconds<?php $nowSec ?>" value="<?php $nowSec ?>"/>
<input type="submit" id="button">
</form>
<?php
$format = 'd-m-Y h:i:s';
$queryTime = $_POST['day'] . "-" . $_POST['month'] . "-" . $_POST['year'] . " " . $_POST['hour'] . ":" . $_POST['min'] . ":" . $_POST['sec'];
if (date($format,strtotime($queryTime)) == $queryTime) {
$now = new DateTime(strtotime($queryTime), new DateTimeZone('America/Los_Angeles'));
} else {
echo "You entered:" . $queryTime . "<hr style='display:block;'>";
exit;
}
$timezones = array(
'EST' => new DateTimeZone('America/Panama'),
'UTC' => new DateTimeZone('Europe/London'),
'CCT' => new DateTimeZone('Asia/Hong_Kong'),
'PST' => new DateTimeZone('America/Los_Angeles'),
);
echo "You entered:" . $now->format($format) . "<hr style='display:block;'>";
foreach ($timezones as $zone) {
$now = new DateTime($now, new DateTimeZone($zone));
print "The time in" . $zone . "is" . $now->format($format) . "<br/>";
}
?>
your fault shall be forgiven :D
Seriously, I got your code working take a look at the result here:
http://sofia.bplaced.net/homework2.php
It wasn't THAT wrong.
I don't now how reliable this page is, but this shows every change i made:
http://www.diffchecker.com/cfdm0ppc
The new working code:
<?php
$timezones = array(
'EST' => -5*3600, //equador
'UTC' => 0, //london
'CCT' => +8*3600, //beijing
'PST' => -8*3600, //los angeles
);
foreach ($timezones as $time) {
$now = time();
$now += $time;
print gmstrftime('DATE: %B %d %Y and TIME: %r <br/>',$now);
}
$nowM = date('m');
$nowD = date('d');
$nowY = date('Y');
$nowHr = date('h');
$nowMin = date('i');
$nowSec = date('s');
?>
<form action="homework2.php" method="post">
<label>Sync Timecode</label>
<input type="text" name="month" placeholder="Month <?php $nowM ?>" value="<?php $nowM ?>" />
<input type="text" name="day" placeholder="Day <?php $nowD ?>" value="<?php $nowD ?>" />
<input type="text" name="year" placeholder="Year <?php $nowY ?>" value="<?php $nowY ?>" />
<input type="text" name="hour" placeholder="Hours <?php $nowHr ?>" value="<?php $nowHr ?>" />
<input type="text" name="min" placeholder="Minutes <?php $nowMin ?>" value="<?php $nowMin ?>"/>
<input type="text" name="sec" placeholder="Seconds<?php $nowSec ?>" value="<?php $nowSec ?>"/>
<input type="submit" id="button">
</form>
<?php
$format = 'd-m-Y H:i:s';
$queryTime = $_POST['day'] . "-" . date('m',strtotime($_POST['month'])) . "-" . $_POST['year'] . " " . $_POST['hour'] . ":" . $_POST['min'] . ":" . $_POST['sec'];
if (date($format,strtotime($queryTime)) == $queryTime) {
try {
$now = new DateTime(date("c",strtotime($queryTime)));
} catch (Exception $e) {
echo $e->getMessage();
exit(1);
}
} else {
echo "You entered: " . $queryTime . "<hr style='display:block;'>";
exit;
}
$timezones = array(
'EST' => 'America/Panama',
'UTC' => 'Europe/London',
'CCT' => 'Asia/Hong_Kong',
'PST' => 'America/Los_Angeles',
);
echo "You entered: " . $now->format($format) . "<hr style='display:block;'>";
foreach ($timezones as $zone) {
$now = new DateTime(date("c",strtotime($queryTime)));
date_timezone_set($now, timezone_open($zone));
echo "The time in " . $zone . " is " . $now->format($format." \G\M\TP") . "<br/>";
}
?>
I had to alter the following things:
Your IF-statement was wrong, you compared a 12h Value to a 24H value
line 35:
"h" to "H" //altered hour-format
I expected you wanted your user to enter a month like "April" and not like "04"
line 36:
"$_POST['month']" to "date('m',strtotime($_POST['month']))" //altered month-format
You should always fetch error-exeptions - this way your code may go on in case of an error
line 36:
altered to "try{...}"
line 41:
"You entered: " //added a spacer
line 45 ot 50:
modified the array as you tried to print these in line 56 and used them as parameter in 55
line 52:
"You entered: " //added a spacer
line 55:
"DateTime()" to "date_timezone_set()" //altered the command. The new cmd is part of the same function-set
line 56:
"print" to "echo" //I like uniform code
line 56(2 and 3):
"The time in " and "is " //added spacers
line 56(4):
" \G\M\TP" //relative time to GMT
you wrote something about "...display the time for each of the 4 times relative to the time that was manually entered."
"\G\M\T" will print as "GMT"
"P" will result in the time relative to GMT$
This should work for you.
Aiyion.Prime
Related
I have a problem that I don't quite understand how to solve, and I came here to see if you can help me.
The thing is that I have the calendar of
and I need to block intermediate dates
example of this would be:
dates from 2022/11/01 to 2022/11/10 and I have to discard the dates from 2022/11/02 to 2022/11/05 and 2022/11/07 to 2022/11/09
and what it should show is in a single input the remaining dates
I mean the dates
2022/11/01,2022/11/06,2022/11/10
<?php
$reservSQL = new ReservSQL();
$reservList = $reservSQL->GetReservbyIdKeeper($idKeeper);
if ($reservList == null) {
?>
<td>
<input type="date" name="dateStart" min="<?php echo $keeper->getTypeUserKeeper()->getDateStart(); ?>" max="<?php echo $keeper->getTypeUserKeeper()->getDateFinish(); ?>" placeholder="START" required>
</td>
<td>
<input type="date" name="dateFinish" min="<?php echo date('Y-m-d', strtotime($keeper->getTypeUserKeeper()->getDateStart() . "+1 day")); ?>" max="<?php echo $keeper->getTypeUserKeeper()->getDateFinish(); ?>" placeholder="FINISH" required>
</td>
<?php
}
elseif($reservList!=null){
$reserv=new Reserv();
foreach ($reservList as $reserv) {}
?>
<tbody>
<td>
<input type="date" name="dateStart"
min="<?php echo date('Y-m-d', strtotime($reserv->getDateFinish() . "+1 day")); ?>"
max="<?php echo $keeper->getTypeUserKeeper()->getDateFinish(); ?>"
placeholder="START" required>
</td>
<td>
<input type="date" name="dateFinish"
min="<?php echo date('Y-m-d', strtotime($reserv->getDateFinish() . "+1 day")); ?>"
max="<?php echo $keeper->getTypeUserKeeper()->getDateFinish(); ?>" placeholder="FINISH" required>
</td>
</tbody>
<?php
}
?>
The thing is that I receive 2 date arrays and I try to get the dates that are reserved using min and max, it gets complicated because it reaches a point where the logic does not do what I want.
I hope you can help me.
I know, I should put more time in programming in PHP, so please find a way to improve this (incomplete) code:
$dates = ['2022/11/01','2022/11/02','2022/11/03','2022/11/04','2022/11/05','2022/11/06','2022/11/07','2022/11/08','2022/11/09','2022/11/10'];
$skip1 = ['2022/11/02','2022/11/05'];
$skip2 = ['2022/11/07','2022/11/09'];
$i = new DateInterval("P1D");
$d = $skip1[0];
while ($d<=$skip1[1]) {
$a=array_search($d,$dates);
unset($dates[$a]);
$t = date_create_from_format('Y/m/d', $d);
print $t->format('Y/m/d')."\n";
date_add($t,date_interval_create_from_date_string("1 days"));
$d = date_format($t,"Y/m/d");
}
var_dump($dates);
When $skip1 contain a start- and end-date, this code will delete that range from $dates. The output:
array(6) {
[0] =>
string(10) "2022/11/01"
[5] =>
string(10) "2022/11/06"
[6] =>
string(10) "2022/11/07"
[7] =>
string(10) "2022/11/08"
[8] =>
string(10) "2022/11/09"
[9] =>
string(10) "2022/11/10"
}
The code should be improved to repeat the step using $skip2, and from the code you will see that I am NOT experienced in PHP.
I am getting all types of errors on the following code. I want to post data from my form and store in a $_SESSION array for future processing
Illegal string offset 'SurveyDate'
Illegal string offset 'Income'
<input class="formFields" type="date" id="txtDateOfSurvey" name="mycensus[0][SurveyDate]"
<input class="formFields" type="numeric" id="txtIncome" name="mycensus[0][Income]"
<?php
session_start();
if( !isset($_SESSION['mycart2']))
{
$_SESSION['mycart2'] = array();
}
$_SESSION['mycart2'] = array_merge($_SESSION['mycart'], $_POST['mycensus']);
foreach($_SESSION['mycart2'] as $v)
{
echo $v['SurveyDate'] . ' was born on ' . $v['Income'] . '<br>';
}
?>
I want the array mycart2 to contain all the entries that I enter on my form.
<?php
session_start();
if(is_array(mycensus)){
$survey_date = mycensus[0]['SurveyDate'];
$Income = mycensus[0]['Income'];
}
?>
<input class="formFields" type="date" id="txtDateOfSurvey" name="survey_date" value="<?php echo $survey_date; ?>">
<input class="formFields" type="numeric" id="txtIncome" name="income" value="<?php echo $Income; ?>">
<?Php
if( !isset($_SESSION['mycart2']))
{
$_SESSION['mycart2'] = array();
}
$_SESSION['mycart2'] = array_merge($_SESSION['mycart'], $_POST['mycensus']);
foreach($_SESSION['mycart2'] as $v)
{
echo $v['SurveyDate'] . ' was born on ' . $v['Income'] . '<br>';
}
?>
Exactly what the title says. My PHP written after an the an if statement to check if a text portion of a form has any value is not running. It works fine in one written earlier in my code, but not the second time.
Here is my whole code:
<?php include '../header.php'; include '../navigation.php'; ?>
<div id="pageContent">
<form name="format" method="POST" action="phpFunctions.php">
Please input date:
<input type="date" name="date" value="<?php echo date('Y-m-d'); ?>" />
<input type="submit" name"submit1" value="Format" />
</form>
<?php
if (isset($_POST['date'])) {
$new_date = $_POST['date'];
$date = new DateTime($new_date);
echo 'M-D-Y Format: ' . $date->format('m-d-Y') . '<br>';
echo 'D-M-Y Format: ' . $date->format('d-m-Y');
}
?>
<form name="stringStuff" method="POST" action="phpFunctions.php">
Enter string:
<input type="text" name"yourString">
<input type="submit" name"submit2" value="Parse" />
</form>
<?php
if (isset($_POST['yourString']) && !empty($_POST['yourString'])) {
echo 'ayyyyyy lmao';
$new_string = $_POST['theString'];
$trimmed_string = trim($new_string);
echo 'ayyyyyy lmao';
echo 'String Length: ' . strlen($new_string) . '<br>';
echo 'Trim Whitespace: ' . $trimmed_string . '<br>';
echo 'Lowercased: ' . strtolower($new_string) . '<br>';
if(strpos($new_string, 'DMACC') !== false) {
echo 'String contains DMACC';
}
else {
echo 'String does not contain DMACC';
}
}
?>
</div>
<?php include '../footer.php'; ?>
The portion of the code that isn't working is this portion after what I mentioned
if (isset($_POST['yourString']) && !empty($_POST['yourString'])) {
echo 'ayyyyyy lmao';
$new_string = $_POST['theString'];
$trimmed_string = trim($new_string);
echo 'ayyyyyy lmao';
echo 'String Length: ' . strlen($new_string) . '<br>';
echo 'Trim Whitespace: ' . $trimmed_string . '<br>';
echo 'Lowercased: ' . strtolower($new_string) . '<br>';
if(strpos($new_string, 'DMACC') !== false) {
echo 'String contains DMACC';
} else {
echo 'String does not contain DMACC';
}
}
you missed = , name="yourString"
<form name="stringStuff" method="POST" action="test_index.php">
Enter string:
<input type="text" name="yourString">
<input type="submit" name="submit2" value="Parse" />
</form>
It seems you are missing name="yourString"
<input type="text" name="yourString">
<input type="submit" name="submit2" value="Parse" />
I am using the hidden.php to pass two values to the "hidden_handler.php" for them to be displayed on a webpage. The two variables being used are $user and $time in the hidden.php . However, when they are passed over to the hidden_handler.php, the two values are shown as
" $user" and "$time"and not their assigned values , which are "Hunt" and the actual time.
I have tried to figure out for quite a while but could not find out what is the cause of it. Thanks in advance for any valuable feedback.
Below are the two files with their code.
hidden.php
<?php
date_default_timezone_set(' UTC ');
$time = date(' H:i, F j');
$user = 'Hunt';
?>
<form action = "hidden_handler.php" method = "POST">
<fieldset>
<legend>Send us your comments</legend>
<textarea rows="5" cols="20" name="comment">
</textarea>
<input type="hidden" name="user" value="$user">
<input type="hidden" name="time" value="$time">
</fieldset><p><input type="submit" ></p></form>
?>
hidden_handler.php
<?php
if (!empty($_POST['comment'])) {
$comment = $_POST['comment'];
} else {
$comment = NULL;
echo 'You must enter a comment';
}
$time = (!isset($_POST['time']) ) ? NULL : $_POST['time'];
$user = (!isset($_POST['user']) ) ? NULL : $_POST['user'];
if (( $comment != NULL ) &&
( $time != NULL ) && ( $user != NULL )) {
echo "<p>Comment received :\" $comment\" <br>
From $user at $time </p>";
}
?>
When the hidden.php is run and I key in the comment as "test"
while $user and $time are hard-coded [ $user = 'Hunt' and $time = date(' H:i, F j') ].
And the result is as shown below:
Comment received :" test"
From $user at $time
you should use:
<input type="hidden" name="user" value="<?php echo $user;?>">
<input type="hidden" name="time" value="<?php echo $time?>">
Using just quotes in HTML sees the values inside as strings, they are not interpreted as PHP variables.
When you
<input type="hidden" name="user" value="$user">
<input type="hidden" name="time" value="$time">
you are doing it in HTML, not in PHP, so those values are taken literally - the variables are not substituted.
You need to
<?php
echo "<input type=\"hidden\" name=\"user\" value=$user>"
echo "<input type=\"hidden\" name=\"time\" value=$time>"
?>
I've created a form that submits data to a MySQL database but the Date, Time, Year and Month fields constantly revert to the exact same date (1st January 1970) despite the fact that when I submit the information to the database the form displays the current date, time etc to me. I've already set it so that the time and date fields automatically display the current time and date. Could someone please help me with this.
Form:
<html>
<head>
<title>Ultan's Blog | New Post</title>
<link rel="stylesheet" href="css/newposts.css" type="text/css" />
</head>
<body>
<div class="new-form">
<div class="header">
<img src="images/edit-home-button.png">
</div>
<div class="form-bg">
<?php
if (isset($_POST['submit'])) {
$month = htmlspecialchars(strip_tags($_POST['month']));
$date = htmlspecialchars(strip_tags($_POST['date']));
$year = htmlspecialchars(strip_tags($_POST['year']));
$time = htmlspecialchars(strip_tags($_POST['time']));
$title = htmlspecialchars(strip_tags($_POST['title']));
$entry = $_POST['entry'];
$timestamp = strtotime($month . " " . $date . " " . $year . " " . $time);
$entry = nl2br($entry);
if (!get_magic_quotes_gpc()) {
$title = addslashes($title);
$entry = addslashes($entry);
}
mysql_connect ('localhost', 'root', 'root') ;
mysql_select_db ('tmlblog');
$sql = "INSERT INTO php_blog (timestamp,title,entry) VALUES ('$timestamp','$title','$entry')";
$result = mysql_query($sql) or print("Can't insert into table php_blog.<br />" . $sql . "<br />" . mysql_error());
if ($result != false) {
print "<p class=\"success\">Your entry has successfully been entered into the blog. </p>";
}
mysql_close();
}
?>
<?php
$current_month = date("F");
$current_date = date("d");
$current_year = date("Y");
$current_time = date("H:i");
?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<input type="text" name="month" value="<?php echo $current_month; ?>" />
<input type="text" name="date" value="<?php echo $current_date; ?>" />
<input type="text" name="year" value="<?php echo $current_year; ?>" />
<input type="text" name="time" id="time" size="5"value="<?php echo $current_time; ?>" />
<input class="field2" type="text" id="title" value="Title Goes Here." name="title" size="40" />
<textarea class="textarea" cols="80" rows="20" name="entry" id="entry" class="field2"></textarea>
<input class="field" type="submit" name="submit" id="submit" value="Submit">
</form>
</div>
</div>
</div>
<div class="bottom"></div>
<!-- //End Wrapper!-->
</body>
</html>
</html>
For some reason the posts are being submitted without a timestamp and are reverting to a default timestamp.
Sounds like your form is giving your database a very low amount of "Ticks". Notice you have an with name="date" and id="date" three times. This is most likely your problem. Change those names and ids, do use month, year, date (according to your "postback").
You have three text boxes named date. Since $_POST['month'] and $_POST['year'] are not set, strtotime() cannot figure out the correct timestamp and the SQL query looks like this:
INSERT INTO php_blog (timestamp,title,entry) VALUES ('','Title Goes Here.','')
Change the names of the input elements to what your PHP code is expecting:
<input type="text" name="month" value="<?php echo $current_month; ?>" />
<input type="text" name="date" value="<?php echo $current_date; ?>" />
<input type="text" name="year" value="<?php echo $current_year; ?>" />
After you've done this, strtotime() will be able to parse the date and insert the correct value into the query.
INSERT INTO php_blog (timestamp,title,entry) VALUES ('1272738360','Title Goes Here.','')
It could be that strtotime fails to recognize the format you are submitting your date in.
Try a classic YYYY/MM/DD format:
$timestamp = strtotime("$year/$month/$date $time");
Looks like strtotime don't understand the format you feeding to it.
Use mktime instead.
Anyway you have to always debug your code, i.e. print out the query to see if anything goes wrong.
Or consider to use mysql-supported type colymn, date or datetime
You may be confused an unix timestamp which is just number ans mysql timestamp type column which is string of 2010-05-01 00:00:00