Check for URL variable in PHP - php

I have a PHP page that takes a date variable: mypage.php?date=2015-07-14 and displays output.
How do I check if the date= is empty and if it is then insert and refresh the page with the current date?
I've tried to formulate a small script at the top of the page using _GET with the date value but am not sure how to handle the reload of the page?

You can simply check your input is not empty using empty function, and create a date (it will default to current, unless you pass parameter), and passed it as get parameter in header function to the same page.
if(empty($_GET['date']))
header('location:'.$_SERVER['PHP_SELF'].'?date='.date('Y-m-d'));

You can simply use the empty language construct from PHP to check if a date was supplied: http://php.net/empty
Then you could use the header-function to redirect if no date was entered in the url: http://php.net/manual/en/function.header.php
For example:
<?php
if (empty($_GET['date'])) {
header('location: ' . $_SERVER['REQUEST_URI'] . '?date=' . date('Y-m-d'));
}
Also note that any headers should be sent before generating any output in your script.

What you seek is a combination of isset and empty functions with redirect using header. The end result could look something like this
<?php
$rawDate = isset($_GET['date']) && !empty($_GET['date']) ? $_GET['date'] : false;
$requestDateTime = $rawDate ? DateTime::createFromFormat('Y-m-d', $rawDate) : false;
$currentDateTime = new \DateTime();
// If datetime from GET is invalid or is not current date...
if (!$requestDateTime || $currentDateTime->diff($requestDateTime)->days > 0) {
// Redirect to current page with current date
header(sprintf('Location: ?date=%s', $currentDateTime->format('Y-m-d')));
}

Related

expiring php redirect on set date

I.m looking for a way in Php to have a Redirect expire on a said day.
The use for this is that I'm sharing file on a sever using the code below.
What I like is to have that redirect take them to a page that lets them know there time is up and they can see the Redirect anymore or tell I update the date of expire.
if (test){
---do something---
die("<script>location.href = 'http://file.here.com'</script>");
} else {
return false;
}
I have also try
function BeforeProcessList(&$conn, &$pageObject)
{
$target_date = new DateTime("05-01-2014");
$today = new DateTime();
if((int)$target_date->diff($today)->format('%r%a') >= 0)
{
header("Location: testview_list.php");
exit();
}
}
There are several scenarios for this case but i suggest to use session.
Use additional session to be taken once your privilege period is valid and make sure that you've already insert a date when a user get into that file along with value that indicate this user is allowed , for example,1 so you can change a value to ,for example,0 after specific period and that user will be denied automatically or redirected to another page
I got it to work.
<?php
// has this expired?
$expire_date = "2015-08-25"; // good until Aug 8/15
$now = date("Y-m-d");
if ($now>$expire_date) {
header("Location: http://yoursite.com/outoftime.html");
die();
}
// and now the unexpired part of the page ...
header("Location: http://yoursite.com/fileshare/");
die();
Thanks for the help guys

Grab number from URL and use it as variable in PHP

I'm working from a Wordpress website, and I need to be able to create a template for a real quick-and-simple custom order page.
The plan is to create pages so that the URL of said page will be http://www.website.com/order-1234
And then, the template being used for that page will have PHP in it that will try and grab the "1234" portion of the URL, and use it as a variable.
$url = 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF'];
$order_id = intval(substr($url, strrpos($url, '/order-') + 4));
echo $order_id;
But the above code is returning a zero "0"
try by using
www.website.com/order?id=1234
and use
$getid = $_GET['id']
also when you want to use the get to show the page use the request function
if ($_REQUEST['id'] == $getid) {
// do something here
}
something like that :)

PHP Global Variable - Keep assigned value

I have the following declaration at the beginning of my PHP script:
$GLOBALS['monthselect'] = date('m');
$GLOBALS['yearselect'] = date('Y');
during the script I assign the following values:
$GLOBALS['monthselect'] = $_GET['mo'];
$GLOBALS['yearselect'] = $_GET['yr'];
Next, after a form submits, I want to redirect it to the same selection in GET. (This is all in the same PHP script)
header('Location: ?yr='. $GLOBALS['yearselect'] .'&mo=' . $GLOBALS['monthselect']);
Problem is, this always reloads the page with the date of today. Never the newly stored values. So always this output:
website.com/?yr=2013&mo=06
What am I missing here?
Could you please provide the places where do you set $GLOBALS['monthselect'] = $_GET['mo']; and $GLOBALS['yearselect'] = $_GET['yr']; Make sure they get executed..

Remove querystring value on page refresh

I am redirecting to a different page with Querystring, say
header('location:abc.php?var=1');
I am able to display a message on the redirected page with the help of querystring value by using the following code, say
if (isset ($_GET['var']))
{
if ($_GET['var']==1)
{
echo 'Done';
}
}
But my problem is that the message keeps on displaying even on refreshing the page. Thus I want that the message should get removed on page refresh i.e. the value or the querystring should not exist in the url on refresh.
Thanks in advance.
You cannot "remove a query parameter on refresh". "Refresh" means the browser requests the same URL again, there's no specific event that is triggered on a refresh that would let you distinguish it from a regular page request.
Therefore, the only option to get rid of the query parameter is to redirect to a different URL after the message has been displayed. Say, using Javascript you redirect to a different page after 10 seconds or so. This significantly changes the user experience though and doesn't really solve the problem.
Option two is to save the message in a server-side session and display it once. E.g., something like:
if (isset($_SESSION['message'])) {
echo $_SESSION['message'];
unset($_SESSION['message']);
}
This can cause confusion with parallel requests though, but is mostly negligible.
Option three would be a combination of both: you save the message in the session with some unique token, then pass that token in the URL, then display the message once. E.g.:
if (isset($_GET['message'], $_SESSION['messages'][$_GET['message']])) {
echo $_SESSION['messages'][$_GET['message']];
unset($_SESSION['messages'][$_GET['message']]);
}
Better use a session instead
Assign the value to a session var
$_SESSION['whatever'] = 1;
On the next page, use it and later unset it
if(isset($_SESSION['whatever']) && $_SESSION['whatever'] == 1) {
//Do whatever you want to do here
unset($_SESSION['whatever']); //And at the end you can unset the var
}
This will be a safer alternative as it will save you from sanitizing the get value and also the value will be hidden from the users
There's an elegant JavaScript solution. If the browser supports history.replaceState (http://caniuse.com/#feat=history) you can simply call window.history.replaceState(Object, Title, URL) and replace the current entry in the browser history with a clean URL. The querystring will no longer be used on either refresh or back/previous buttons.
When the message prompt ask for a non exsisting session. If false, show the message, if true, do nothing. session_start(); is only needed, if there is no one startet before.
session_start();
if ($_GET['var']==1 && !isset($_SESSION['message_shown']))
{
$_SESSION['message_shown'] = 1;
echo 'Done';
}
Try this way [Using Sessions]
<?php
//abc.php
session_start();
if (isset ($_GET['var']))
{
if ($_GET['var']==1)
{
if(isset($_SESSION['views']))
{
//$_SESSION['views']=1;
}
else
{
echo 'Done';
$_SESSION['views']=1;
}
}
}
?>
Think the question mean something like this?
$uri_req = trim($_SERVER['REQUEST_URI']);
if(!empty($_SERVER['REQUEST_URI'])){
$new_uri_req = str_replace('?avar=1', '?', $uri_req);
$new_uri_req = str_replace('&avar=1', '', $new_uri_req);
$pos = strpos($new_uri_req, '?&');
if ($pos !== false) {
$new_uri_req = str_replace('?&', '?', $new_uri_req);
}
}
if( strrchr($new_uri_req, "?") == '?' ){
$new_uri_req = substr($new_uri_req, 0, -1);
}
echo $new_uri_req; exit;
You can use then the url to redirect without vars. You can also do the same in js.
str_replace() can pass array of values to be replaced. First two calls to str_replace() can be unified, and filled with as many vars you like that needs to be removed. Also note that with preg_replace() you can use regexp that can so manage any passed var which value may change. Cheers!

Using jquery and javascript to display variable from PHP

I'm trying to display a PHP variable using javascript/jquery but it's displaying 'null'.
if(mysql_num_rows($checkBan) > 0){
$bannedDate = $checkBan['banLength'];
if(preg_match('/[0-9]/',$bannedDate)){
list($yyyy,$mm,$dd) = explode('-',$bannedDate);
$date = $mm."-".$dd."-".$yyyy;
}
//$date = "test"; when this is uncommented it appears in the alert so I know the json_encode is working fine
?>
<script type ="text/javascript">
var bannedUntil= <?php echo json_encode($date); ?>;
alert('Your account has been banned until ' + bannedUntil +'. Please contant an administrator if you believe this is an error');
</script>
<?
}
The alert appears just fine, but the bannedUntil variable is null. However, when the second date variable is uncommented it appears in the alert. It's not a separate function so I don't see why the scope would be an issue.
I am seeing you use $checkBan as a result resource in mysql_num_rows(), then attempt to access an array key from it without fetching. You appear to be missing a call to mysql_fetch_assoc():
if(mysql_num_rows($checkBan) > 0){
// Fetch a row from the result resource $checkBan
$row = mysql_fetch_assoc($checkBan);
$bannedDate = $row['banLength'];
// etc...
}
Another tip: It looks like you are getting a standard MySQL date format back as YYYY-MM-DD and converting it with string operations in PHP to MM-DD-YYYY. Just retrieve it in that format in your query to begin with and avoid the explode() and list() calls in your PHP application code.
SELECT DATE_FORMAT(banLength, '%m-%d-%Y') FROM yourtable

Categories