random(non- repeating) file generator on click of button in php - php

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
}

Related

If isnt set open txt name else

Essentially what I'm trying to achieve is, if the user hasn't selected one of the dropdown options, then a default .txt is opened, read and displayed. When the user does decide on a drop down option, it echos the users option. It works by getting the value of the option and setting that to a variable to set the open path.
Instead of opening my default which is 'example' when the user hasnt selected, it seems to pick one of the values at random and select it.
If the user hasnt selected an option, the default file path is p-changelog/example.txt
If the user has chosen and option, the file path becomes p-changelog/$userOp.txt (UserOp being the users option from the drop down).
if(!isset($_POST['userDateOp'])) {
$userOp = "example";
}else{
$userOp = $_POST['userDateOp'];
}
if(!isset($_POST['submit'])) {
$changelog = fopen("p-changelog/$userOp.txt", 'r');
$pageTxt = fread($changelog, 25000);
echo nl2br($pageTxt);
}
Entire Page: Code
I am new to PHP before criticising anything I've done.
userDateOp is always going to be set, as its posted every time.
What you are looking for is its value being empty
That function is
if(empty($_POST['userDateOp'])) {
You don't need to check if submit is set because you've already validated the existence of userDateOp. So this will only lead to an undefined variable notice for $changelog for default.
Your simplified script should be
if(!isset($_POST['userDateOp'])) {
$userOp = "example";
}else{
$userOp = $_POST['userDateOp'];
}
$changelog = fopen("p-changelog/$userOp.txt", 'r');
$pageTxt = fread($changelog, 25000);
echo nl2br($pageTxt);

Personalising Wordpress Sessions Based on the Visited URLs

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....

Issue Passing JS variable to PHP include file

I have a php file where I am using it to setup dynamically generated pages based on the input variables. It starts on and index.html page where the variables are gathered some of which are not simple strings but complex Google Earth objects. On the submit of that page it is posted to another page and you are redirected to the created file. The trouble is coming when I try to use that variable within the php include file that is used to generate the pages.How do i properly get a variable from this form and then pass it through to be able to use it on the new generated page. Here is what I am trying currently.
On the click of this button the variable flyto1view is set.
$("#flyto1").click(function(){
if (!flyto1view){
flyto1view = ge.getView().copyAsLookAt(ge.ALTITUDE_RELATIVE_TO_GROUND);
$("#flyto1view1").val(flyto1view)
}
else {
ge.getView().setAbstractView(flyto1view);
}
});
Then from here I have tried setting the value to an hidden field but Im not sure if that kinda of variable has a value that can be set like that. Whats the best way to get this variable to here after post
<?
if (isset($_POST['submit']) && $_POST['submit']=="Submit" && !empty($_POST['address'])) {//if submit button clicked and name field is not empty
$flyto1view1 = $_POST['flyto1'];
$address = $_POST['address']; //the entered name
$l = $address{0}; // the first letter of the name
// Create the subdirectory:
// this creates the subdirectory, $l, if it does not already exists
// Note: this subdirectory is created in current directory that this php file is in.
if(!file_exists($l))
{
mkdir($l);
}
// End create directory
// Create the file:
$fileName = dirname(__FILE__)."/$address.html"; // names the file $name
$fh = fopen($fileName, 'w') or die("can't open file");
// The html code:
// this will outpout: My name is (address) !
$str = "
<? php include ('template.php') ?>
";
fwrite($fh, $str);
fclose($fh);
// End create file
echo "Congradualations!<br />
The file has been created.
Go to it by clicking here.";
die();
}
// The form:
?>
Firstly. creating files from user input is pretty risky. Maybe this is only an abstract of your code but doing a mkdir from the first letter of the input without checking that the first letter is actually a letter and not a dot, slash, or other character isn't good practice.
Anyway, on to your question. I would probably use $_GET variables to pass to the second file. So in the second file you use <?php $_GET['foo'] ?> and on the first file you do:
echo "Congradualations!<br />
The file has been created.
Go to it by clicking here.";
You could also echo the variable into your template like so:
$str = '
<?php
$var = \'' . $flyto1view1 . '\';
include (\'template.php\')
?>';

php array of webpages - want to be able to cycle through them with NEXT - PREV links

Based on Hunter F's answer, the solution to my problem is almost complete.
Just a couple of tweaks needed.
I modified the code a little and submitted a new question here at: php array help required - if current array item = 'last or first item' then 'do something'
ORIGINAL MESSAGE:
I want to be able to create a simple navigation bar with PREV and NEXT links that I can use to cycle though a list of pages. The navigation bar will be a php include within all of the pages to be cycled.
So I guess the starting point is to create an array of the pages that need to be cycled though with the PREV NEXT links.
Such as....
$projectlist = array(
'http://domain.com/monkey/',
'http://domain.com/tiger/',
'http://domain.com/banana/',
'http://domain.com/parrot/',
'http://domain.com/aeroplane/',
);
I want to option to re-order, add or remove the links. So having one self contained master array such as this seems like a logical choice to me as I'll only need to update this one list for any future additions.
Each directory being linked to has it's own index.php file, so I've left the index.php part off from the end of the links as it's not needed...or is it?
...I'm pretty stumped as of how to continue from here.
I guess I need to work out which page within the array I'm currently on, then generate the PREV and NEXT links based on that. So If I entered from 'http://domain.com/parrot/' I would need links to the relevant PREV and NEXT pages.
Any help or information to guide me on this next stage would be most appreciated.
$currentPath = explode('?', $_SERVER['REQUEST_URI']); //make sure we don't count any GET variables!
$currentPath = $currentPath[0]; //grab just the path
$projectlist = array(
'/monkey/',
'/tiger/',
'/banana/',
'/parrot/',
'/aeroplane/',
);
if(! in_array($currentPath, $projectlist) ) {
die('Not a valid page!'); //they didn't access a page in our master list, handle error here
}
$currentPageIndex = array_search($currentPath, $projectlist);
if($currentPageIndex == 0) { //if it's on the first page, we want them to go to the last page
$prevlink = 'Prev';
} else { //otherwise just go to the n-1th page
$prevlink = 'Prev';
}
if($currentPageIndex == sizeof($projectlist)-1 ) { //if we're on the last page, have them go to the first page for "next"
$nextlink = 'Next';
} else {
$nextlink = 'Next';
}
One thing you may want to consider, is urlencoding the href targets in the link.

html & php question (get command)

Want to include another value in my urls
so far I have
# valid pages
$page = array('splash', 'portraits', 'weddings', 'studio', 'about', 'mobile', 'personal');
# validate GET, default to splash if not provided
$_GET['q'] = (isset($_GET['q'])) ? strtolower(trim($_GET['q'])) : 'splash';
if (!in_array($_GET['q'], $page))
$_GET['q'] = 'splash';
require_once "{$_GET['q']}.html";
but I want to include sections into my site so I need an extra value (ie. ?q=portraits?z=studio )
I assume I could probably just duplicate the $get command and replace q with z... but suppose I don't want the second value to be necessary (so the default pages will display without extra commands) and i want it to target a div or frame within the page? Not sure if I can even target divs.
Just use a default value:
if (isset($_GET['z'])) {
$z = $_GET['z'];
}
else {
$z = NULL; // or 'default' or whatever you want.
}
You can in short write the above in one line:
$z = isset($_GET['z']) ? $_GET['z'] : NULL;
I am not sure what you mean with "target a div", but if you mean an anchor, you can do that via identifiers (id).
Call your PHP script via index.php?q=splash#text and in your splash.html file you somewhere have <div id="splash">. The browser should scroll there.

Categories