Php age check form - php

I'm giving my first steps on php and I got this project where, although I understand what is being done, for some reason it does not work.
$app->post('/age/', function($lang) use($app) {
$action = $app->request()->post('action');
$remember = $app->request->post('remember') === 'on';
if ($action === 'Yes') {
setcookie('AgeCheck', 'true', time()+60*60*24*30, '/'); //Expire in 1 month
$_SESSION['age'] = 'true';
$app->redirect(urldecode($app->request()->get('return')) ?: "/$lang");
}
else if ($action === 'Enter') {
$limit = (60 * 60 * 24 * 365) * 18;
$dob = $app->request->post('dob');
if ($lang === 'us') {
$dob = \DateTime::createFormFormat('mdy', $dob);
$limit = (60 * 60 * 24 * 365) * 21;
}
else
{
$dob = \DateTime::createFromFormat('dmy', $dob);
}
if ((time() - $dob->getTimestamp()) >= $limit)
{
setcookie('AgeCheck', 1, (60*60*24*365)/12); //Expire in 1 month
$_SESSION['age'] = 1;
$app->redirect(urldecode($app->request()->get('return')) ?: "/$lang");
}
}
$app->redirect("/$lang/underage");
This should, in theory,redirect the user to the proper page if he passes the age restriction, but it always redirects him to the underage page.
The issue is, most definitely, in here: if ((time() - $dob->getTimestamp()) >= $limit)
What am I doing wrong?

Always check every line of your code.
Your key condition is:
if ((time() - $dob->getTimestamp()) >= $limit)
{
setcookie('DrambuieAgeCheck', 1, (60*60*24*365)/12); //Expire in 1 month
$_SESSION['age'] = 1;
$app->redirect(urldecode($app->request()->get('return')) ?: "/$lang");
}
So before that, just echo/var_dump $dob->getTimestamp(), and $limit. Everything will be clear for you.
If something wrong with $dob, check what is returned by $_POST['dob'].
Example:
var_dump($dob->getTimestamp());
var_dump($app->request->post('dob'));
var_dump($dob->getTimestamp());
var_dump(time());
echo 'condition result:';
var_dump(((time() - $dob->getTimestamp()));
if ((time() - $dob->getTimestamp()) >= $limit)
You will see most important variables in condition, and condition it self

Figured the issue. Everything was correct, but it wasn't even entering the if, since the $action was not enter, but submit. I'l still keep #Daimos answer as correct.
The more interesting part here is that ((time() - $dob->getTimestamp()) >= $limit) is actually true(in this context). So maybe the $action is not Enter? – Andrew
This was the key to solve it, after I've tried everything and checked that it was all correct.

Related

(PHP) Verifying if given date is between two other dates

I'm having an issue with some code that someone else has previously worked on.
The goal is to iterate through a directory and push any files that are within a certain date range to an array (files are in mmddyyy.txt format).
The (terribly named, not by my own doing) variables in the code represent the following:
$aYear - A given year, read in from a text file. This variable changes during every iteration of the loop. The same goes for $aMonth and $aDay.
$sYear1 - Start year. $sMonth1 and $sDay1 are used in respect to $sYear1.
$sYear2 - End year. $sMonth2 and $sDay2 are used in respect to $sYear2.
$isGood - File will be added to the array.
$isGood = false;
if($aYear >= $sYear1 && $aYear <= $sYear2)
{
if($aYear == $sYear1)
{
if($aMonth == $sMonth1)
{
if($aDay >= $sDay1 && $aDay <= $sDay2)
{
$isGood = true;
}
}
else
{
if($aMonth >= $sMonth1 && $aMonth <= $sMonth2)
{
$isGood = true;
}
}
}
else if($aYear == $sYear2)
{
if($aMonth == $sMonth2)
{
if($aDay <= $sDay2)
{
$isGood = true;
}
}
else
{
if($aMonth <= $sMonth2)
{
$isGood = true;
}
}
}
else
{
$isGood = true;
}
}
if($isGood)
{
//echo "Found good article";
$a = $a . "===" . $file;
array_push($result, $a);
}
I'm not getting the results that I expected. I'm looking for some help as to how I can simplify this code and get it working properly. I do need to keep this solution in PHP.
Thank you in advance.
It seems to me Month statement if($aMonth >= $sMonth1 && $aMonth <= $sMonth2) needs work
eg start date- 03 Aug 2013 end date- 04 Sep 2016 and check date say 08 Nov 2013
would make isGood=false whereas it should be true.
Removing && $aDay <= $sDay2 and && $aMonth <= $sMonth2 should work.
As #Sandeep pointed out you're issues are with:
if ($aMonth >= $sMonth1 && $aMonth <= $sMonth2)
and
if ($aDay >= $sDay1 && $aDay <= $sDay2)
as you don't need to be comparing the date with end dates as well.
That being said you can clear up your code completely by doing something like:
$date = (new DateTime)->setDate($aYear, $aMonth, $aDay);
$start = (new DateTime)->setDate($sYear1, $sMonth1, $sDay1);
$end = (new DateTime)->setDate($sYear2, $sMonth2, $sDay2);
if ($start <= $date && $date <= $end) {
//echo "Found good article";
$a = $a . "===" . $file;
array_push($result, $a);
}
Hope this helps!

PHP Session - Temporary login block function not working properly. Odd Error

I have this simple php code fired by Ajax that checks if an entered password is correct. Now for this function I would also want to have an ability to block login for 10 seconds after 5 failed attempts in entering.
Here is the code itself:
//Beforehand I started the session, and connected the $link to the mysql database
if(!isset($_SESSION['lim'])){
$_SESSION['lim'] = 5;
}
$p = $_POST['text']; //I WILL TAKE CARE OF VALIDATION LATER
//All of the passwords will be crypted, and the variable will be
//validated. Just after I'm done with this system.
if($_SESSION['lim']>0){
$result = mysqli_query($link, "SELECT id FROM passwd where pass = '".$p."' ;");
if( mysqli_num_rows($result) > 0){
echo 1;
$_SESSION["passed"] = "true";
}else{
echo 0;
--$_SESSION['lim'];
}
}else{
echo 2;
if(!isset($_SESSION['blockTime'])){$_SESSION['blockTime'] = time();}
}
if(($_SESSION['lim'] == 0) && (time() - $_SESSION['blockTime'] > 10)){
$_SESSION['lim'] = 5;
}
The problem is the code doesn't do the blocking part after 5 tries. Now the issue itself is most probably located in this bit:
if(($_SESSION['lim'] == 0) && (time() - $_SESSION['blockTime'] > 10)){
$_SESSION['lim'] = 5;
}
Because without this portion, the blocking works fine (apart from not enabling the login after 10 seconds). It seems the if statement is executed everytime instead of only when the lim is empty and 10 seconds have passed.
What could possibly be the issue here and how could I make the if work properly
you have a problem in your code. The last --$_SESSION['lim']; makes it to zero but it doen's set $_SESSION['blockTime'] to time() so... when it's compared in:
if(($_SESSION['lim'] == 0) && (time() - $_SESSION['blockTime'] > 10)){
$_SESSION['lim'] = 5;
}
it's ever true so the counter it's restored.
To avoid it just add ´$_SESSION['blockTime'] = time();´ every time you subtract a try.
if(!isset($_SESSION['lim'])){
$_SESSION['lim'] = 5;
}
$p = $_POST['text'];
if($_SESSION['lim']>0){
$result = mysqli_query($link, "SELECT id FROM passwd where pass = '".$p."' ;");
if( mysqli_num_rows($result) > 0){
echo 1;
$_SESSION["passed"] = "true";
}else{
echo 0;
--$_SESSION['lim'];
$_SESSION['blockTime'] = time();
}
}else{
$_SESSION['blockTime'] = time();
}
if(($_SESSION['lim'] == 0) && (time() - $_SESSION['blockTime'] > 10)){
$_SESSION['lim'] = 5;
}
Tested and working.
All in all please review comments made about injections and brute force are important.
Hope it helps!
when you re-init, ensure to reset your blockTime var as well :
if(($_SESSION['lim'] == 0) && (time() - $_SESSION['blockTime'] > 10)){
$_SESSION['lim'] = 5;
unset($_SESSION['blockTime']);
}

PHP Recursion Function not working as expected [duplicate]

This question already has answers here:
How to use return inside a recursive function in PHP
(4 answers)
Closed 9 months ago.
I have created a helper function to return the first valid payment date of the month. The day is not valid if it's a holiday (pulled from a list in a db table), a Saturday, or a Sunday. In this example the 1st January 2016 is a holiday.
I have created this recursive function in a CodeIgniter helper but I'm seeing really weird behaviour. What it should do is identify the 1st as a holiday, call itself to identify the 2nd as a Saturday, again to identify the 3rd as a Sunday, before eventually returning the 4th as the first valid day.
After the function calls itself, the part after the call will keep running in an infinite loop unless I insert a break;. If I do insert a break I get the following output:
2016-01-01: 1
2016-01-02: 2
2016-01-03: 3
Final: 2016-01-04: 4
Final: 2016-01-04: 4
Final: 2016-01-03: 3
Final: 2016-01-02: 2
before finally returning 2 (which is wrong).
function day_check($paymentDate, $paymentDay = 1) {
$CI =& get_instance();
$dateParts = explode("-", $paymentDate);
$holQ = $CI->db->query("SELECT * FROM holidays WHERE holidayDate = '$paymentDate'");
$holR = $holQ->row();
if ($paymentDay <= 0) {
$paymentDay = 1;
}
while (($holR->holidayDate == $paymentDate) || (date("l", strtotime($paymentDate)) == 'Saturday') || (date("l", strtotime($paymentDate)) == 'Sunday')) {
echo "$paymentDate: $paymentDay <br>";
$refinedDay = $dateParts[2] + 1;
if ($refinedDay < 10) {
$refinedDay = "0" . $refinedDay;
}
$paymentDate = $dateParts[0] . "-" . $dateParts[1] . "-" . ($refinedDay);
$paymentDay = $dateParts[2] + 1;
day_check($paymentDate, $paymentDay);
break;
}
echo "Final: $paymentDate: $paymentDay <br>";
return $paymentDay;
}
Initial $paymentDate provided to function is 2016-01-01
I've been looking at this for hours and I don't understand why this is happening. Is this a quirk of Codeigniter or do I completely misunderstand my recursion logic?
The problem is misunderstanding the logic. In your code the recursion call result is not used ever.
function day_check($paymentDate, $paymentDay = 1) {
$CI =& get_instance();
$dateParts = explode("-", $paymentDate);
$holQ = $CI->db->query("SELECT * FROM holidays WHERE holidayDate = '$paymentDate'");
$holR = $holQ->row();
if ($paymentDay <= 0) {
$paymentDay = 1;
}
// while -> if
if (($holR->holidayDate == $paymentDate) || (date("l", strtotime($paymentDate)) == 'Saturday') || (date("l", strtotime($paymentDate)) == 'Sunday')) {
echo "$paymentDate: $paymentDay <br>";
$refinedDay = $dateParts[2] + 1;
if ($refinedDay < 10) {
$refinedDay = "0" . $refinedDay;
}
$paymentDate = $dateParts[0] . "-" . $dateParts[1] . "-" . ($refinedDay);
$paymentDay = $dateParts[2] + 1;
return day_check($paymentDate, $paymentDay); // return!
// break; // no need
}
echo "Final: $paymentDate: $paymentDay <br>";
return $paymentDay;
}
Also change while to if since we don't need a loop there.

Wrong calculation

I got a weird problem.
I want a simple system which shows an error if there are more than 1 request in one second.
What i did:
if(!isset($_SESSION['protect']['mass_request_time']) || $_SESSION['protect']['mass_request_time'] = null) {
$_SESSION['protect']['mass_request_time'] = microtime(true);
$_SESSION['protect']['mass_request_request'] = 1;
} else {
$_SESSION['protect']['mass_request_request'] += 1;
if($_SESSION['protect']['mass_request_request'] >= 2 && microtime(true) - $_SESSION['protect']['mass_request_time'] < 1) {
die('Too many requests!');
} elseif(microtime(true) - $_SESSION['protect']['mass_request_time'] > 1) {
# Reset the counter since more than a second is over
$_SESSION['protect']['mass_request_time'] = null;
}
I have no clue what i did wrong, i guess the solution is pretty easy (maybe just a calculation error.. it's already 3 AM here).
Your first if statement isn't valid.
$time = $_SESSION['protect']['mass_request_time'];
if (!isset($time) || $time = null)
Your code just just sets the time to null. Use == instead.

Swap div visibility based on time / schedule

On my page I have two divs... one div I'd like to be visible from 10am to 6pm ( server time ).... and the other div for the remaining hours.
I tried a bunch of searches to find some sort of a javascript or jquery content swapper without any luck.. thanks for any suggestions?
<div id="day">content</div>
<div id="night">content</div>
I was able to get this working using only the following php:
<?php
$hour = strftime("%H");
if ($hour >= 02 && $hour < 05)
{
echo '<div id="div1">content block one </div>';
}
else
{
echo '<div id="div2">content block two</div>';
}?>
However this solution doesn't seem to work if I want to show the div from 8pm until 4am... is this because it is spanning more than one day? Thanks for any suggestions.
EDIT
The case you mentioned in your comment is a thorny one. So here is my revised-revised answer:
<?php
$t0 = 20; // from hour (inclusive) -- int, 0-23
$t1 = 4; // till hour (excluding) -- int, 0-23
$t = date('G'); // current hour (derived from current time) -- int, 0-23
if ($t0 == $t1) {
$in_range = NULL;
} elseif ($t0 < $t1) {
$in_range = ($t0 <= $t && $t < $t1);
} else {
$in_range = ($t1 <= $t && $t < $t0) == false;
}
/*
echo $in_range === NULL
? 'from and till dates must be different'
: ($in_range ? 'just in time' : 'wait till the time is right');
*/
if ($in_range === false) {
$s0 = mktime($t0, 0, 0); // lunch time
$s = time(); // current time
if ($s0 < $s) {
$s0 += 60 * 60 * 24; // late for lunch! now wait till tomorrow
}
$d0 = $s0 - $s;
$dh = floor($d0 / 60 / 60);
$dm = $d0 - $dh * 60 * 60; $dm = floor($dm / 60);
$ds = $d0 - $dh * 60 * 60 - $dm * 60;
echo sprintf("
Current date...: %s<br />
Target date....: %s<br />
Time to go.....: %d hours, %d minutes, %d seconds
",
date("Y-m-d h:i:s A", $s),
date("Y-m-d h:i:s A", $s0),
$dh,
$dm,
$ds
);
}
?>
If you need to set visibility based on server time, you should show and hide the divs from the server side.
Because no JavaScript can get the server time but the client (possible remote located) browser.
If you have a script in your site that can return the server time, then you could achieve this, but I think it would be more sensible to mark the HTML (php, jsp, whatever) code conditionally from scratch.
Just use $(document).ready() handler with Date() (eg. getHours() method) as I did with the following code: jsfiddle.net/c2TPZ. You can hide both blocks by default unless your JS sets CSS styles for them to be visible, eg. like this:
$('#box1').css({display: 'block'}); // sets display to 'block', eg. from 'none'
I would generally recommend this be done on the server, but it would look something like this in Javascript:
var pHour = Date.getHours();
if ((pHour >= 10) && (pHour < 18))
{
$('.scheduled-target').show();
}
This assumes that you'd make '.scheduled-target' display:none by default.
Also this is for the client's local time. If you want an absolute time, you'll want to start with Date.getUTCHours() and do offsets for your Timezone/Locale.
$(document).ready(function() {
var d = new Date();
if (d.getHours() >= 10 && d.getHours() < 18) {
$(#div1).show();
$(#div2).hide();
}
else {
$(#div1).hide();
$(#div2).show();
}
});
EDIT: Oops, I missed the part about server time. This won't be reliable. Instead you should set them with server-side scripting. Don't know what you're using on the server side, but for example in PHP:
$hour = strftime("%H");
if ($hour >= 10 && $hour < 18)
{
$div1_class = "show";
$div2_class = "hide";
}
In your css, class .hide is display: none;
Theoritically it is as simple as this:
HTML
<div class="h h10-6">10-6</div>
<div class="h h-other">other time of day</div>
JavaScript
current_hour = <? some_server_side_code_to_get_the_hour ?>;
if(current_hour >= 10 && current_hour < 18) $('.h10-6').show();
else $('.h-other').show();
CSS
.h { display: none; }
I used this
<?php
date_default_timezone_set("America/Los_Angeles");
$rightNow = date("m:d:h:i:sa");
//echo $rightNow ;
//$startHide = date("6:11:02:30:00pm")
$startHide = date("06:11:02:30:00pm");
$endHide = date("06:12:05:00:00pm");
?>
<? if ($rightNow > $startHide && $rightNow < $endHide): ?>
<style> .hideCertainTimes {
display:none !important;
}
</style>
<? else: ?>
<? endif; ?>

Categories