Link visible between certain times - php

I would like someone to help me please.
I need a link to be visible between certain times say 6pm & 1am in the evenings. Clients that are registered on my site can change the times of store opening and closing times within their admin panel and it connects to a table in a database.
The link needs to only be visible during specified times that the client decides via their control panel. Out side of these hours the link is hidden/not visible and not clickable.
So this needs to call/echo times from database table for each customer.
any help would be great.
many thanks
Mark

You could use something like...
// check if the date (current hour) is between two times,
// if it is, assign the link to $link, else assign nothing to $link
$link = date('H') >= 6 && date('H') <= 20 ? 'Link' : ''; // replace hardcoded hours with vars if needed
echo $link;

try this:
// Assuming $userMin and $userMax are the users specified times
$time = date( 'H' );
if( $time > $userMin && $time < $userMax ) {
echo "<a href='linkUrl'>Description</a>";
}

Related

How to validation the starting date and ending date from database so it will not collide with time

Currently, I had some data in my database which was
I had do some action to take out the class_time. Which was later became
$Starttimein=$_POST['startTime'];
$Endtimein=$_POST['endTime'];
$varstart=preg_split('/[\s:\s]+/', $Starttimein);
$totvarstart=$varstart[0]*100+ $varstart[1];
$varend=preg_split('/[\s:\s]+/', $Endtimein);
$totvarend=$varend[0]*100+ $varend[1];
$sql8="select * from class where sup_id='$idselect' ";
$result8=mysqli_query($con,$sql8);
while($row8=mysqli_fetch_assoc($result8))
{
$preclasstime=$row8['class_time'];
$keywords = preg_split('/[\s,\s:\s-\s:\s]+/', $preclasstime);
$day = $keywords[0];
$tottimestart = $keywords[1]*100 + $keywords[2];
$tottimeend = $keywords[3]*100 + $keywords[4];
if($day==$_POST['csday'])
{
if((($totvarstart>= $tottimestart) && ($totvarstart<= $tottimeend)) || (($totvarend>= $tottimestart) && ($totvarend<= $tottimeend)))
{
?>
<script type="text/javascript">
alert("Time crash");
</script>
<?php
}
else
{
echo "correct";
}
}
}
The "day,starting and ending time" was separate using preg_split function. And I wish to validate if user select the same day, it will compare the input starting and ending time whether the input time crash with the time which store in database. For example: if user select Mon, 10.30-11.30, it will display a alert message say that cannot add class time as it is crash with previous time. I had tried using the if((($totvarstart>= $tottimestart) && ($totvarstart<= $tottimeend)) || (($totvarend>= $tottimestart) && ($totvarend<= $tottimeend)))
to validate it, but cannot work.
Don't save these three values "day", "start time" and "end time" in one column, which you have to split later anyway. Keep them separated in three columns "dayofweek", "starttime" and "endtime". Use the TIME type for the latter so you can run comparison operators on them.
There are 6 ways how a time span can be arrange in relation to another time span. You can check this in the database to get only the rows which are in conflict with your input values. The checks should look like this:
[...]
WHERE
dayOfWeek = :dayOfWeek AND
(
(:starttime < starttime AND starttime < :endtime) OR
(:starttime < endtime AND endtime < :endtime) OR
(starttime < :startime AND :endtime < endtime)
)
Note: :starttime and :endtime are the bound variables from your prepared statement. Depending on your API you might need to use ? instead.
This way you don't need to read the whole database just to check if they are overlapping or not.

How can I query mysql table and display result using php conditional statements

I want to show user that he has vaccinated his goat after successfully payment confirmation.
Here is what I tried:
<?php
$treatperiod1=$product_row['treat1'];
$currentDate = date("Y-m-d");
$totalDays = $treatperiod1;
$usedDays = round(abs(strtotime($currentDate)-strtotime($orderdate))/60/60/24);
$remainingDays = $totalDays-$usedDays;
if($remainingDays==0) {
echo "<a target = '_blank' href ='product_addon.php?treatp=$treatperiod1' class='btn btn-success'><i class='fa fa-pencil'></i>Vaccinate Gaoat</a>";
} elseif($remainingDays==$treatperiod1) {
echo 'Vaccinated';
} else {
echo $remainingDays.' Days Left';
}
?>
I have displayed remaining days for vaccination intervals I want to also display 'Vaccinated' if user payment for vaccination is confirmed. $product_row['treat1']; is a column where the number of days for vaccination is specified. order_details is a table for orders with column confirm for confirmed orders.
Goat Vaccination:
Because Goats don't get Autism
Please read how to use PHP DateTime objects because they will make your life a lot easier on this project.
I will rewrite your code and then tell you what the new code does:
//establish DateTime objects.
$currentDate = new DateTime(); //now.
$orderDate = new DateTime($orderdate); //$orderdate format Y-m-d
//Establish how may days since order date and today.
$difference = $orderDate->diff($currentDate);
$usedDays = $difference->days;
/***
Total Period paid for,
in days, integer.
$product_row['treat1'];
***/
$remainingDays = $product_row['treat1'] - $usedDays;
//Returns an integer value of remaining days.
if($remainingDays < 1) {
echo "<a target = '_blank'
href ='product_addon.php?treatp=".$treatperiod1."'>
Vaccinate Goat</a>";
} elseif($remainingDays==$product_row['treat1']) {
//This will only fire if the goat was vaccinated TODAY.
echo 'Vaccinated';
} else {
echo 'Vaccinated:' .$remainingDays.' Days Left';
}
Hopefully with the help of the link above you should be able to see the basics of what I wrote out for you.
Some notes:
Stop making variables that are simply copies of other variables, it's inefficient and confusing.
(Try to) Stop sending data to new PHP pages as GET URL values such as /newpage.php?treatp=".$var.". This is very probably very insecure.
A more specific answer will need a full explanation from you of your MySQL tables, if nessecary please edit your question and add them.
Try and move away from using timestamps and treating timestamp variables as mathematical entities, and use the DateTime object instead.
Really, to determine if a payment is made you should have a payment date value in your database (set when a payment is successful) and simply compare this date to the value of the integer of the number of days payment covers, using the ->diff() method illustrated above.
Further information on Goat Vaccinations

PHP auto-logout after 10 mins of inactivity

Currently I'm tracking time spent by user on website using PHP code mentioned below:
if (!isset($_SESSION[timeset1]))
{
$one_val = time();
$_SESSION[timeset_dummy]= $one_val;
$two_val = time()+1;
$_SESSION[units_all] = array
(
"year" => 29030400,
"month" => 2419200,
"week" => 604800,
"day" => 86400,
"hr" => 3600,
"min" => 60,
"sec" => 1
);
}
else
{
$two_val = time();
}
$diff = abs($two_val - $_SESSION[timeset_dummy]);
foreach($_SESSION[units_all] as $unit => $mult)
if($diff >= $mult)
{
$output .= " ".intval($diff / $mult)." ".$unit.((intval($diff / $mult) == 1) ? ("") : ("s"));
$diff -= intval($diff / $mult) * $mult;
}
I want to give pop-up to users after 8 mins of inactivity that session will expire in next 2 mins. Can you please suggest how can I show pop-up (preferably without using Javascript, nice to have with CSS3 & HTML5) . Pop-Up will have warning message "Do you want to continue" and one button "Yes" , if button is not clicked for 2 mins automatically page logout script (PHP) will be executed.
Any pointers to to get this logic implemented.
I found a jQuery plugin that looks like it will make your life easier. It is called jquery-idleTimeout.
The plugin has a few configuration items so you can customize it for your own needs…
inactivity: 1200000 //20 Minute default (how long before showing the notice)
sessionAlive: 300000, //5 minutes default how often to hit alive_url, we use for our ajax * interfaces where the page doesn’t change very often. This helps to prevent the logout screen of your app appearing in ajax callbacks. If you set this to false it won’t send off.
alive_url: ‘/path/to/your/imHere/url’, //send alive ping to this url
redirect_url: ‘/js_sandbox/’, //Where to go when log out
click_reset: true, //Reset timeout on clicks (for ajax interface) – resets the sessionAlive timer, so we are not hitting up your app with alive_url if we just did an ajax call for another reason.
logout_url: ‘/js_sandbox/timedLogout/index.html’ //logout before redirect (url so you can completely destroy the session before redirecting to login screen)
Here is a link to the github page to download the library.
https://github.com/philpalmieri/jquery-idleTimeout
Edit
Something I also noticed while looking at the source code, they are using jquery-ui as their stylesheet to make it look like it does in the demo.
As far as I know, you cannot achieve what you are looking for without javascript. The browser needs javascript to know when to open the pop-up. You can use whatever means you want to check for timeout, either the basic window.setTimeout or a more advanced library (like the one in tehAon's answer).
Since I cannot post a comment I'm going to ask here: your code seems awfully complicated for checking if a user is still active. Is there any particular reason you could not use something like this:
$_SESSION['last_activity'] = time();
function check_if_logged_in() {
if(time() - $_SESSION['last_activity'] > 600) { // 10 minutes but you could use 480 for 8 minutes
// Do redirect or take other action here
}
}
if(time() - $_SESSION['timestamp'] > 900) { //15 minute subtract new timestamp from the old one
$_SESSION['logged_in'] = false;
session_destroy();
header("Location: " . index.php); //redirect to index.php
exit;
} else {
$_SESSION['timestamp'] = time(); //set new timestamp
}
This is quite easy with php session variable.
set $_SESSION variable with timestamp and check with the action time
<?php
session_start();
if(time()-$_SESSION['time']>600)
unset($_SESSION['time']);
else
$_SESSION['time']=time();//updating with latest timestamp
?>

Wordpress Delay content being published to non-members

I have a wordpress site that uses the WPMU Membership plugin. I want to add code to my template that displays a new post to members 5 days before it is shown to non-members.
Something like this:
if (current_user_on_level(17) && CODE TO DETERMINE IF POST IS LESS THAN 5 DAYS OLD) {
echo POST CONTENT;
}
else {
echo 'Info not available yet';
}
;
What code would I use to determine whether the published post is less than 5 days old??
I figured out the answer. First had to convert the post time to a UNIX code using this code:
(True sets it to UNIX epoch time rather than set to local time zone)
Then I used this code to get the UNIX time 5 days ago
strtotime("-5 day")
Put the two together with an if statement that displays the content or if it's not time it displays a message that the content isn't available yet.
<?php
$post_timestamp = get_post_time('U', true);
if (current_user_on_level(17) && $post_timestamp <= strtotime("-1 day"))
{
get_template_part( 'content', get_post_format() );
}
else {
echo 'No post available yet <br />';
}?>
The only issue with this is that because my posts are ordered in chronological order, the top of my blog is filled with the line "No post available yet". Can anyone think of how I can get these statements to sit at the bottom?

Creating hit Counter

I am trying to create a hit counter for my website and I have developed the following code for it. I have included the following code only in Codeigniter's main controller for my home page.
At first I thought the code was working fine but I just found that if I don't keep on browsing the pages then again go to the home page it doesn't update the data. I mean for example: If I go to my homepage for the first time then it updates the data, but after 10 seconds if I refresh the page it does't update the data. But if I keep refreshing it for 10 seconds then it works.
So could you please tell me how to get it update the data without having to keep on browsing the pages or refreshing the home page?
Thanks :)
function __construct() {
parent::__construct();
// Visitor Counter
if (!$this->session->userdata('timeout')) {
$out = time() + 10; // I will change it to $out = time() + 60*60; later
$this->session->set_userdata('timeout', $out);
mysql_query("UPDATE cane_visitor_counter SET visitor_stat = visitor_stat+1
WHERE id = '1'");
} else {
$timeout_time = $this->session->userdata('timeout');
if (time() > $timeout_time) {
$this->session->set_userdata(array('timeout' => ''));
$this->session->sess_destroy();
}
}
}
edit
What I am trying to achieve is when an user visits the webpage for the first time, I want to update my database. Within 10 seconds (for example purpose), if the visitor again visits the home page, the database will not be updated. But after 10 seconds if he again visits the home page, I want to update my database.
Thanks :)
Your code says "if there is no timeout in the session, update the count". You want it to say "if there is no timeout in the session, or there is but it's old, update the count".
function __construct() {
parent::__construct();
// Visitor Counter
if (!$this->session->userdata('timeout') || $this->session->userdata('timeout') < time()) {
$this->session->set_userdata('timeout', time() + 10);
mysql_query("UPDATE cane_visitor_counter SET visitor_stat = visitor_stat + 1 WHERE id = 1");
}
}
I'm not a CodeIgniter user, so I am assuming that you used its session facilities correctly; I just used them the same way.

Categories