PHP: Posting tweets at a specific time - php

I'm building an application on WordPress wherein I have a single form with two entries:
1) content of the tweet
2) time at which the tweet should be posted on the user's Twitter timeline
Form:
<form method = "POST">
<input type = "text" name = "tweet1">
<input type = "datetime-local" name = "date1">
<input type = "submit">
</form>
Now, on submitting the form, I want to post the content of the text field to be posted on the user's Twitter timeline at the time specified by the user in the form. $_SESSION['x'] and $_SESSION['y'] stores the user's oauth_token and oauth_token_secret respectively.
<?php
if(isset($_POST['submitted']))
{
function do_this_one()
{
$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, $_SESSION['x'], $_SESSION['y']);
$response = $connection->post("statuses/update", array('status' => $_POST['tweet1']));
}
date_default_timezone_set('Asia/Calcutta');
$myDate = strtotime($_POST['date1']);
$now = time();
$ti_one = $myDate - $now;
echo time() + $ti_one;
add_action( 'my_new_event','do_this_one' );
wp_schedule_single_event(time() + $ti_one, 'my_new_event' );
?>
$ti_one variable basically stores the time in seconds between now and the time specified by the user. For example, if the current time is 2:00 PM, then if the time specified by the user in the form is 2:03 PM, then $ti_one would be equal to 180 seconds. That's the reason why I'm scheduling the event at time() + $ti_one in:
wp_schedule_single_event(time() + $ti_one, 'my_new_event' );
However, on submitting the form, the tweet is not being posted at the specified time. The above code ie code for the form and the PHP code is inside callback.php, which is the page that the users are redirected to after granting permission to the OAuth client.
What seems to be wrong with my code? Am I scheduling the event incorrectly?

Related

How to prevent the user from abusing a button?

i'm quite a beginner with PHP and i tried to make something to get xp when cliking the button. You just need to click and it gives xp, then it refresh the page to refresh the player's stat on screen.
<form method="post">
<p><input type="submit" value="Kill the mob" name="add20xp" /></p>
</form>
<?php
if (isset($_POST['add20xp']))
{
$add20xp =("UPDATE users SET exp = (exp + 20)");
$execadd20xp = mysqli_query($connection, $add20xp);
echo '<meta http-equiv="refresh" content="0.1" />';
}
?>
The problem is that i want to prevent the user from smashing the button to prevent bugs and things like that... I tried to put sleep(1) but i can just keep spamming, wait the seconds and it works so it's not very useful.
Thanks for the help !
Save the last time the update was done in session state. Then, only allow the button to be pressed after (last time + 2 seconds) (Two seconds was chosen since that was the suggested interval in your original question).
if (isset($_POST['add20xp'])) {
if (!isset($_SESSION['last_post'])) {
$_SESSION['last_post'] = 0;
}
$currtime = time();
if ($currtime > ($_SESSION['last_post'] + 2)) {
$_SESSION['last_post'] = $currtime;
// ... process the post.
$add20xp =("UPDATE users SET exp = (exp + 20)"); // fix this line
$execadd20xp = mysqli_query($connection, $add20xp);
echo '<meta http-equiv="refresh" content="0.1" />';
}
}
As #Martin noted above in his comment, you want to do the update only for the user who pressed the button, which is the meaning of the comment "fix this line."
If you want to disable the button for 3 seconds after the form is submitted you can use this:
if(sessionStogare.getItem('submitted') === true){
document.querySelector('input[type="submit"]').disabled = true;
setTimeout(function(){
document.querySelector('input[type="submit"]').disabled = false;
sessionStorage.removeItem("submitted");
}, 3000);
}
document.querySelector("body").onclick = function() {
sessionStorage.setItem("submitted", true);
};
We will note the submission in the sessionStorage and check, if the form has been submitted every time we load the page. Then, we will disable the button and enable it after 3 seconds.
Change your php page to this:
// the beginning of the page:
<?php
// start a SESSION
session_start();
// setup a $_SESSION variable
if (!isset($_SESSION["timestamp"]))
$_SESSION["timestamp"] = 0;
//
// now put the $_POST part
if (isset($_POST['add20xp'])) {
// check the time
$now = time();
if ($now - $_SESSION["timestamp"] > 2) {
// more than 2 seconds have passed since last $_POST
// update the time
$_SESSION["timestamp"] = time();
//
$add20xp =("UPDATE users SET exp = (exp + 20)");
$execadd20xp = mysqli_query($connection, $add20xp);
//
echo '<meta http-equiv="refresh" content="0.1" />';
exit;
} else {
// nothing, just let the page load like it is.
}
}
?>
Notice some important changes:
the use of $_SESSION vars -> these vars are stored and can be
retrieved at every page load -> you can use them to store the last
time an action took place
the $_POST part should be at the beginning
of the page -> otherwise after you send a form, you load the page ->
check the post -> then reload... it's not efficient
if you put the $_POST part at the beginning, you actually don't need the page reload with the meta tag -> because the data are already
updated

Make Link expire after X minutes

Okay I am sending an activation email link to user's email. My Activation link is working perfect I wants to make that link expire after X minutes.
Here is my code:
$base_url='http://172.16.0.60/WebServices/';
$activation=md5($email.time());
email format to HTML
$mail->Subject = 'Activate Your Account';
$mail->Body = 'Hi, <br/> <br/> We need to make sure you are human. Please verify your email and get started using your Website account. <br/> <br/> '.$base_url.'activation/'.$activation.'';
Now my
.htaccess file
RewriteEngine On
RewriteRule ^activation/([a-zA-Z0-9_-]+)$ activation.php?code=$1
RewriteRule ^activation/([a-zA-Z0-9_-]+)/$ activation.php?code=$1
Now how can I make my link expire? I dont have timestamp field in my database.
I dont have timestamp field in my database.
Then add one.
Add a field to record when the link was generated and you can then instantly check against that time when they visit. There is no need to waste time trying to think of hacks when you can simply adjust your setup accordingly.
I got my answer using this simply,
Send a timestamp in link and on other end while accepting the link I have to check the time with current time stamp.
$base_url='http://172.16.0.60/WebServices/';
$activation=md5($email.time());
$time = time();
email format to HTML
$mail->Subject = 'Activate Your Account';
$mail->Body = 'Hi, <br/> <br/> We need to make sure you are human. Please verify your email and get started using your Website account. <br/> <br/> '.$base_url.'activation/'.$activation.$time.'';
While when user clicks on link, following code will check the expiration of link.
$u_time = $this->input->get('time'); // fetching time variable from URL
$u_time = md5($u_time);
$cur_time = time(); //fetching current time to check with GET variable's time
if ($cur_time - $u_time < 10800)
{
// link is not expired
}
else
{
// link has been expired
}
date_default_timezone_set("Asia/Kolkata"); // set time_zone according to your location
$expire_date = "2019-03-26 14:45:00"; // time that you want the link to expire
echo $now = date("Y-m-d H:i:s"); // your current time.
if ($now>$expire_date) {
echo " Your link is expired";
}
else
{
echo " link is still alive";
}
you can find your time_zone here
Hope this helps:)

how to end php session and begin a new one when user chooses action

This relates to my question here, which had to do with making variables usable in multiple php files. Both Ian Hildebrand and Transcendental offered useful advice.
I want to let a user select, say, 6 a.m. from a form and view data pertaining to that hour, in either or both of two views, View_A and View_B. If the user then wants to look at data from 7 a.m. then he/she just reloads the form and selects that hour and submits.
What happens now is that the variable $hour stays stuck at 6 a.m. So the user can select whatever hour he/she wishes but still gets 6 a.m. data.
So what I want is, when the user selects the new hour, that action ends the first session and starts a new one.
here's the applicable code from the form file:
<form action='view_A.php' method='post'>
<label for 'date'><strong>Select an hour for <?php echo $date; ?></strong>
</label>
<input type="text" name='hour' data-role="datebox" data-options='{"mode":"timeflipbox","minuteStep":60, "overrideTimeFormat": "%H", "overrideTimeOutput": "%H"}' placeholder='click icon to select hour'>
<input type='submit' name='submit' value='submit'>
</form>
</div>
<?php
if(isset($_POST[ 'submit'])) {
$_SESSION[ 'hour']=$ _POST[ 'hour'];
$hour=$ _SESSION[ 'hour']; }
?>
... and applicable code in the file view_A.php
session_start();
error_reporting(E_ALL);
include ("db_connect.php");
date_default_timezone_set('America/Toronto');
$date = date('Y-m-d');
$hour = $_SESSION['hour'];
$blink = $_SESSION['hour'];
$date_hour = $date.' '.$hour;
Both these files lead off with session_start(); right after the opening php tag.
How could I modify the form file so that when the user selects a new hour the current session ends and a new one starts?
You never get to to the if(isset()) part of the code.
As action the form will direct the user directly to Vieuw_A.php
You have to put it in View_A.php
session_start();
error_reporting(E_ALL);
include ("db_connect.php");
date_default_timezone_set('America/Toronto');
$_SESSION['hour'] = $_POST['hour'];
$date = date('Y-m-d');
$hour = $_SESSION['hour'];
$blink = $_SESSION['hour'];
$date_hour = $date.' '.$hour;
although you could skip the session all together
session_start();
error_reporting(E_ALL);
include ("db_connect.php");
date_default_timezone_set('America/Toronto');
$date = date('Y-m-d');
$hour = $_POST['hour'];
$blink = $_POST['hour'];
$date_hour = $date.' '.$hour;
I hope this fixed your problem

Making the variable unset after two minutes

Hey guys am writing a small validation script which uses a simple token to login from the input..When the token is right the user must succesfully login and after two minutes the token must expire and give user a message token expired..But here when i use the token it also came with the message token destroyed ..i want to use the token for 2 minutes and i want the token to be expired in 2 minutes.
I have the html file
<form action="gethints.php" method="post">
First name: <input type="text" name="fname"><br>
<input type="submit" value="Submit">
</form>
Php file
<?php
$name = $_POST['fname'];
$currenttime = time();
$token = 'sample';
$timetounset = strtotime("2 minutes");
if($name != $token) {
echo 'you cant login';
} else {
echo 'you have succesfully logged in <br>';
}
if($currenttime > time() - $timetounset) {
unset($token);
echo "you cant use this token anymore";
} else {
echo 'token is not destroyed';
}
When i run this code and type sample in the input box i get the message like
you have succesfully logged in
you cant use this token anymore
What i need is when i type the id as sample i want to get the message you have succesfully logged in and after two minute when i use the same id i need to get the message like you cant use this token anymore
Thanks for your help..
Could use a session here:
first, store the last time the user made a request
<?php
$_SESSION['timeout'] = time();
?>
in subsequent request, check how long ago they made their previous request
<?php
if ($_SESSION['timeout'] + 2 * 60 < time()) {
// session timed out
} else {
// session ok
}
?>
EDIT:
Don't forget to have session_start(); on top of your code && check if $_SESSION['timeout'] exists, above code is just an example.
The most simple way to approach this imo is to set a cookie with an expiration of 2 minutes.
Store a variable or flag in the cookie and check the contents each time you want to do a validation.
setcookie("TestCookie", $value, time()+120);
Read out the value:
if (isset($_COOKIE['TestCookie'])) {
// Good cookie
} else {
// expired or invalid
}
For information on how to set a cookie and expiration:
http://php.net/manual/en/function.setcookie.php
People can play around with cookies. I suggest you create a database table tokens with token and expires columns. When you insert the token add this to your sql. ...... Insert ....... Timestampadd(now(), interval minute 2); To validate just check if now() is less than expires.

Create multipart form & redirect user

I am fairly new to web design and need some help coding a form. What I am looking to do is take an HTML form that contains a birthday drop down section (mm/dd/yyyy - So 3 different select tabs) and redirect a user based on their age.
If the user is under 30 send them to a new page that says we can't help them. If the user is 30 or over, send them to a second form where they will be able to answer follow up questions... so another form. When processed, I would need to display all the data the user has entered from the beginning of the process.
It's basically 2 form pages, and the 2nd only appears if the user is 30 or over. I am trying to code this using PHP and can't seem to get started. Any help would be appreciated.
Thanks!!
$interval = date_diff(new DateTime(), new DateTime($_POST['year'] .'-'. $_POST['month'] .'-'. $_POST['day']));
if ($interval->y >= 30)
{
session_start();
$_SESSION = $_POST;
header('Location: over30.php');
}
else
{
header('Location: under30.php');
}
in the next form...
<?php session_start(); ?>
<html>
<head><head>
<body>
<form method="post" action="xxx.php">
<input type="text" value="<?=$_SESSION['name'];?>" />
</form>
</body>
</html>

Categories