I’ve looking for this on the web and haven’t found a clear explanation for my question.
I have 2 pages, user select a story on the first page. Second page (using post method) receives the story value(there are only 3 options) and does something.
If a user opens the second page without choosing a story, I want to pop an alert box saying user needs to choose a story first and redirect user to the first page.
here is my php code
$story = $_POST["stories"];
if (($story!= "story1.txt") && ($story!="story2.txt") && ( $story!="story3.txt")){
echo'<script>alert("You need to choose a story first, please go to Story Selection");window.location.href= "StorySelection.php";</script>';
}
this is what i figured out from other posts
This code does not work, I just see bunch of question marks.
But when I open the page, a box pops up asking to open the same page and when i do that (just to see what happens) it says this is a script file, are you sure you want to open it?
my alert box doesn’t pop up, and why it wants to open itself again?
I think most people would simply tend to redirect the user back to page one, as they should not be able to navigate directly to this page, from your description.
$story = $_POST["stories"];
$permitted_stories = array(
'story1.txt'
, 'story2.txt'
, 'story3.txt'
);
// check if the story submitted is permitted
if( !in_array($story, $permitted_stories) ){
// send to the start page
header('Location: page_one.php');
exit();
}
// All ok - get on with the page
If you wanted to be nice and explain on page one why they had been redirected you could replace “page_one.php” with “page_one.php?reason=badchoice” on the redirect line.
Then on page_one you could detect that by checking for
$_GET[‘reason’]
Edit:
Ah, bit slow there you could do what Kalon suggests too, and detect the absence of POST[‘stories’] and do a similar redirect with a different $reason