I would like to open a page using index.php?do=settings,
I'm using following code:
$do='';
if (isset($_GET['do'])){
$do = strip_tags($_GET['action']);
}
if ($do == 'settings') {
header("location:settings.php");
}
if ($do == 'posts') {
header("location:posts.php");
}
but the problem is that I have manually add all menu in actions like above to make it work and when it redirects me, the index.php?do=settings disappears and just show me settings.php which I do not want
To avoid having to set it manually you can store the pages in an array with the keys as the page name and the value as the file and then include the file:
$pages = array(
'settings' => 'settings.php',
'otherpage' => 'somePage.php'
);
if (isset($pages[$do])) {
include $pages[$do];
}
You should include the file as the reason the URL changes is because of the redirect.
add the get var back in like so
header("location: http://yoursite.com/settings.php?do=".$do);
NB: that should be the full uri not a relative one
You can use http_build_query($_GET) to generate the query string for links that need to conserve GET data.
If you need to modify a GET key, save GET to a temp array, modify that and pass it to http_build_query.
Related
i want to display 5 php files content randomly but non repeating when clicked a button [NEXT] using php/javascript (that works in php desktop as well).
the code i used did displayed random web page on page load but i did came across repeated web page
this is the code i used for index.php file:
<?php
$RandomList = array();
$RandomList[] = "/review/review-a1.php";
$RandomList[] = "/review/review-a2.php";
$RandomList[] = "/review/review-a3.php";
$RandomList[] = "/review/review-a4.php";
readfile($_SERVER['DOCUMENT_ROOT'].$RandomList[rand(0,count($RandomList)-1)]);
?>
please suggest how to get non repeated files .
Just save paths you already used in the session:
//Read visited paths from session or create a new list.
//?? works only in PHP7+. Use isset()?: instead of ?? for previous versions
$visitedPaths = $_SESSION['visitedPaths'] ?? [];
//Your list, just slightly changed syntax. Same thing
$randomList = [
"/review/review-a1.php",
"/review/review-a2.php",
"/review/review-a3.php",
"/review/review-a4.php"
];
//Remove all paths that were already visited from the randomList
$randomList = array_diff($randomList, $visitedPaths);
//You need to check now if there are paths left
if (!empty($randomList)) {
//The user did not load all files, so we can show him the next one
//Use array_rand() rather than $array[rand(0, count($array) -1)]
$randomPath = $randomList[array_rand($randomList)];
readfile($_SERVER['DOCUMENT_ROOT'] . $randomPath);
//Now we need to save, that the user loaded this file
$visitedPaths[] = $randomPath;
//And we need to save the new list in the session
$_SESSION['visitedPaths'] = $visitedPaths;
} else {
//TODO: Add some logic in case all paths have been visited
}
first time Question asker here. I'm building a web page and want to change the text on page if the user has visited certain pages.
My initial idea was too create an array in the session which records each url as its visited with something like $_SERVER['REQUEST_URI'], which would probably work if it was a site I was building from scratch. however... Because the site is built in Wordpress I'm not 100% how to go about doing that within there system.
Now here's what I'd suggest you do. Navigate to your Theme and open the file functions.php
Then find a suitable spot anywhere on the File (The bottom of the file wouldn't be that odd).
Then, add the following functions:
<?php
// FILE-NAME: functions.php <== LOCATED AT THE ___/wp-content/themes/your-theme-name
add_action("init", "initiatePageLogging");
function initiatePageLogging(){
// START THE SESSION IF IT HAS NOT BEEN STARTED
// THIS WOULD BE USED TO SHARE DATA ACROSS YOUR PAGES...
if (session_status() == PHP_SESSION_NONE || session_id() == '') {
session_start();
}
// CHECK THAT THE SESSION VARIABLE FOR OUR PAGE-LOGGING IS THERE
// IF NOT CREATE IT
if(!isset($_SESSION['visitedPages'])){
// IT DOES NOT EXIST SO WE CREATE IT & INITIALIZE IT AS AN EMPTY ARRAY
$_SESSION['visitedPages'] = array();
}
// NO NEED TO KEEP THE SESSION ARRAY $_SESSION['visitedPages'] TOO LONG
// SO WE TRIM IT OUT CONDITIONALLY TO KEEP IT UNDER CHECK
if(count($_SESSION['visitedPages']) >= 10){
// WE REMOVE ABOUT 7 ELEMENTS FROM THE BEGINNING OF THE ARRAY
// LEAVING JUST THE LAST 3 - NOW THAT'S COOL...
$arrVisitedPages = $_SESSION['visitedPages'];
array_splice($arrVisitedPages, 0, 7);
// RE-DEFINE THE $_SESSION['visitedPages'] ARRAY
$_SESSION['visitedPages'] = $arrVisitedPages;
}
}
function getLastVisitedPage(){
$lastVisitedPage = get_site_url() . $_SERVER['REQUEST_URI']; //<== FALL BACK TO THE CURRENT PAGE IF WE HAVE AN ISSUE.
if( isset($_SESSION['visitedPages']) && is_array($_SESSION['visitedPages']) ){
$arrVP = $_SESSION['visitedPages'];
$intArrVPLength = count($arrVP);
$diff = ($intArrVPLength - 2);
$lastVisitedPage = ( $intArrVPLength > 1) ? $arrVP[$diff] : $lastVisitedPage;
}
return $lastVisitedPage;
}
?>
Now, Part 1 is done! Inside of your Theme, You will still find a File Called header.php
This is where we have to do the logging because by default every page in Word-Press loads this Page (except when configured otherwise).
At the very, very top of that File - I mean on Line 1, do this:
<?php
// FILE-NAME: header.php <== LOCATED AT THE ___/wp-content/themes/your-theme-name
// BUILD THE URL OF THE CURRENT PAGE & PUSH IT TO THE SESSION VARIABLE...
$thisPage = get_site_url() . $_SERVER['REQUEST_URI'];
$_SESSION['visitedPages'][] = $thisPage;
// THAT'S ALL! BELOW HERE, THE ORIGINAL CONTENT OF THE header.php FILE CONTINUES...
?>
One more thing! How do we now use the $_SESSION['visitedPages'] Variable?
Otherwise, how do we know which page was last visited using the $_SESSION['visitedPages'] Variable?
Now on every File like (page.php, index.php, category.php, taxonomy.php, etc); you can now find out the last visited Page by doing something like this:
<?php
// FILE-NAME: ANY FILE IN THE THEME LIKE: page.php, index.php, category.php, taxonomy.php, etc
$lastVisitedPage = getLastVisitedPage();
// THAT'S IT, PAL...
?>
I hope this helps....
I am working on PHP code for automatically redirecting a URL to an affiliate URL based on words in the URL.
This is the code I am using:
if (stripos($mylink, "amazon.in") > 0) {
if (strpos($mylink, "?") > 0) {
$tmp = $mylink."&affiliate_id";
} else {
$tmp = $mylink."?affiliate_id";
}
$loc = "Location:".$tmp;
header($loc);
exit();
}
But the problem is that when the Amazon URL is like: http://www.amazon.in/English-Movies-TV-Shows/b/ref=sa_menu_movies_all_hindi?ie=UTF8&node=4068584031 it adds the affiliate id like this: ie=UTF8&affiliate_id (it automatically removes the node and its value) but I want it to be like: ie=UTF8&node=4068584031&affiliate_id.
This means that I need to add &affiliate_id at the end of the URL every time if it is an Amazon link.
Actually I just want to achieve the following simple thing: if the URL doesn't have any ?s, I need to place ?affiliateid and if the URL has a ?, I just need to append &affiliateid at the end.
Can you suggest the very simple method for implementing what I require?
Let PHP do the string parsing for you. Let's say your affiliate id is XYWZ.
if (strpos($mylink, "amazon.in") !== 0) {
$urlarray=parse_url($mylink);
$urlarray['query']='affiliate_id=XYWZ&'.$urlarray['query'];
$newurl= $urlarray['scheme'].'://'.$urlarray['host'].$urlarray['path'].'?'.$urlarray['query'];
echo $newurl;
}
will output
http://www.amazon.in/English-Movies-TV-Shows/b/ref=sa_menu_movies_all_hindi?affiliate_id=XYWZ&ie=UTF8&node=4068584031
see? I didn't need to worry if there's a question mark. It will be stripped in the output of parse_url;
Edit: using $mylink instead of $theurl
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 :)
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!