I"m loading a file in start of PHP. I have declared some activity and assign them to buttons which are aligned left and right side of HTML document. On click of each button will included some Other PHP file but I want to remove the previous loaded on startup file before including any other file.
Here is my code
<?php
// php file on startup of file
include("dashboard.php");
$activity = $_REQUEST['activity'];
if($activity) {
if($activity == 'addMember'){
include("addMember.php");
remove("dashboard.php");
}
if($activity == 'dashboard'){
}
if($activity == 'issueBooks'){
include("issueBooks.php");
}
if($activity == 'returnBooks'){
include("returnBooks.php");
}
<?php
I tried with
if($activity == 'addMember'){
include("addMember.php");
remove("dashboard.php");
}
But since I"m very new to PHP, it didn't work as expected.
Any Help anyone.
That isn't how include works. When you include a file, the contents of that file are executed at that point in the code. There's no straightforward way to undo that.
It looks like you want the dashboard activity to be the default view if no activity has been selected yet. To do that, you can just include it only when there is no activity value in request, or when the dashboard activity has been specifically requested.
if (empty($_REQUEST['activity']) || $_REQUEST['activity'] == 'dashboard') {
include 'dashboard.php';
}
The core of this question is to ascertain why the same code, when enclosed by {php} tags in a smarty template - doesn't work fully, compared to when the 'same code' is contained in tags (in a non-smarty template). Specifically, the smarty code version (though partly functioning) isn't returning users to their original landing page.
More info: Am utilising a script which provides a smarty template framework for customisation. On other 'pure php' template sites I've been utilising the following code for the gateway page and all other pages respectively. Part of the functionality of the code is that after being first directed to the gateway page (if they don't have relevant cookie set), users (after getting a cookie) are then redirected back to the page they originally landed on.
[Because so similar, will just include the smarty version. Only difference are the opening and closing tags.]
Code on all pages except gateway page:
{php}
session_start();
function check_if_spider()
{
$spiders = array('Googlebot','google','Yammybot','Openbot','Yahoo','Slurp','msnbot', 'ia_archiver','Lycos',
'Scooter','AltaVista','Teoma','Gigabot','Googlebot-Mobile','Baiduspider','R6_FeedFetcher','NetcraftSurveyAgent',
'Sogou web spider','bingbot','facebookexternalhit','PrintfulBot','msnbot','Twitterbot','UnwindFetchor','urlresolver','Butterfly', 'TweetmemeBot', 'ia_archiver');
// Loop through each spider and check if it appears in
// the User Agent
foreach ($spiders as $spider)
{
if (stristr($_SERVER['HTTP_USER_AGENT'],$spider) == true)
return TRUE;
}
return FALSE;
}
if (check_if_spider() == false) {
if (empty($_COOKIE["accepted"])) {
$_SESSION["page_address"] = $_SERVER["PHP_SELF"];
header("Location: http://www.domain.name/gateway.shtml");
exit;
}
}
{/php}
This is code on gateway page (actually, this is a non-smarty generated php page, so normal php tags used)
<?php
$inoneday = $_SESSION['inoneday'];
if (empty($inoneday)) $inoneday = '';
$baseaddress = $_SESSION['baseaddress'];
if (empty($baseaddress)) $baseaddress = '';
$page_address = $_SESSION['page_address'];
if (empty($page_address)) $page_address = '';
session_start();
//Expire 25 days in the future
//seconds * minutes * hours * days + current time
$inoneday = 60 * 60 * 24 * 25 + time();
setcookie('accepted', date("G:i - m/d/y"), $inoneday);
if ($_SESSION["page_address"] != NULL) {
$baseaddress = "http://www.domain.name";
header('Location: '.$baseaddress . $_SESSION['page_address']);
exit; }
else {
header("Location: http://www.domain.name/index.php");
exit; }
?>
When a user lands on one of the site pages, they are correctly redirected back to the gateway page - just that after the gateway page, they are always directed back to: http://www.domain.name/index.php and not their original landing position. Thus it seems that these lines in the smarty template are not working, or transferring info:
$_SESSION["page_address"] = $_SERVER["PHP_SELF"];
and that
if ($_SESSION["page_address"]
is always equalling null.
Why is this and what can I do to fix it.
Background
I am developing a web application which has users classified by security levels 1-5. This should act as the systems primary access level to allow users to view (or not) sensitive information.
On the system administration page I have a pretty basic page layout... i.e.
<?php if ($seclvl > 4) { ?>
// basic user code
<? } elseif ($seclvl > 1 && $seclvlv <= 4){ ?>
/// elevated privileges code
<? } elseif ($seclvl == 1) { ?>
// super administrator code
<? } else { ?>
//fallback if no security flag - error msg
<? } ?>
What i'm running into is figuring out the best methodology to have the system display a couple buttons in sec lvl 2-4, but yet only be able to be clicked by #1, without having to specify individually through php display gray for sec lvl 2-4, activate lvl 1... Can anyone suggest a better methodology than the following:
<? } elseif ($seclvl > 1 && $seclvlv <= 4){ ?>
<? if (!$seclvl == 1) { ?>
Add a User
<? } else { ?>
Add a User
<? } ?>
//basics for seclvl 2-4... i.e:
View User Info
<? } else { ?>
Furthermore, now that i'm writing this block of code (still untested, yet theory is there)... i'm thinking that my short tag nested if statements wont actually work... Any comment welcome.
I really really dont want to have to specify the conditions of security access for each friggin link/button.
You can write a function to make it easier or use in_array() like this:
<?php
if (in_array($seclvl, [2,3,4])) { // seclvl is between 1 and 5
// do something
}
... or as a function like this:
<?php
is_between($seclvl, $min = 1, $max = 5)) {
if ($seclvl >= $min && $seclvl <= $max)
return true;
return false;
}
I'm working with a page that, once a link is called this script checks and if the POST contains the keyword it and then finds that page. However no matter how I organize this if it doesn't work.
<?PHP
if($_POST['page']) {
$page = (int)$_POST['page'];
$exists = file_exists('pages/page_'.$page.'html');
if($exists) {
echo file_get_contexnts('pages/page_'.$page.'html');
} else {
echo 'There is no such page!';
}
} else if ($_POST['course']) die("0"); {
$course = (int)$_POST['course'];
$exists = file_exists('courses/course_'.$course.'html');
if($exists) {
echo file_get_contexnts('courses/course_'.$course.'html');
die("1");
} else {
echo 'There is no such page!';
}
}
?>
The error I'm currently receiving with this setup is:
Notice: Undefined index: course in C:\wamp\www\Home Page\load_page.php on line 12
Call Stack
# Time Memory Function Location
1 0.0003 253944 {main}( ) ..\load_page.php:0
Is it because there is no 'course' in the page? I might be confused of the code I'm modifying a tutorial of a simple ajax website. It is possible what I am trying to do does not work.
In that case how could I possible go about doing what I want to do.
Right now I have a home page and it loads in another page without switching pages. I like the floridness of it. I would like to have a sort of sub call. So if you are on the home page and you go to courses page then you can click on a specific course and that will load from a different directory within the courses directory.
Homepage (when you click on courses you go to...)
pages/courses_home.html (when you click on a course you go to...)
courses/course_1.html (you can view course and then click back to directory above or go to home)
That is the structure I'm looking to try to achieve.
If more information is needed please let me know what and I'll do my best to include it. Thank you.
The syntax should be:
if(isset($_POST["page"])) {
} elseif(isset($_POST["course"])) {
}
I am not sure why you have a die statement there, but I don't think it belongs. Also, keep in mind the logic for what happens if neither of these conditions is met.
Edit: also keep in mind that isset doesn't prevent empty strings, so you may want to check for that as well. A function you could use is
function checkPost($value) {
return isset($_POST[$value]) && $_POST[$value] !== "";
}
To use:
if(checkPost('page')) {
//some logic
}
Wrong syntax.
elseif ($_POST['course']) {
without die statement.If 'course' undefined else statement works and does not get error. Sorry for bad English.
Try this:
if isset(($_POST['page'])) {
...
} else if isset(($_POST['course'])) die("0"); {
instead of this:
if($_POST['page']) {
...
} else if ($_POST['course']) die("0"); {
Update, Solved:
After all this I found out that I was calling an old version of my code in the update ajax.
'boardControl.php' instead of 'boardUpdate.php' These are the kinds of mistakes that make programing fun.
I'm writing a browser gomoku game. I have the ajax statement that allows the player to play a piece.
$(document).ready(function() {
$("td").live('click',function(){
var value = $(this).attr('id');
$.get('includes/boardControl.php',{play: value, bid: bid});
});
});
value = board square location
bid = board ID
Before creating a user login for player identification, the server side php had a temporary solution. It would rotate the piece state for the squares when clicked instead of knowing what player to create them for.
After creating login stuff I set a session variable for the player's ID. I was hoping to read the session ID from the php during the ajax request and figure out what player they are from there.
session_start();
...
$playerId = $_SESSION['char'];
$Query=("SELECT p1, p2 FROM board WHERE bid=$bid");
$Result=mysql_query($Query);
$p1 = mysql_result($Result,0,"p1");
$p2 = mysql_result($Result,0,"p2");
$newPiece = 0; //*default no player
if($playerId == $p1)
$newPiece = 1;
if($playerId == $p2)
$newPiece = 2;
For some reason when I run the full web app, the pieces still cycle though, even after I deleted the code to make them cycle.
Furthermore, after logging in If i manually load the php page in the browser, it modifies the database correctly (where it only plays pieces belonging to that player) and outputs the correct results.
It seems to me that the session is not being carried over when used with Ajax. Yet Google searches tell me that, sessions do work with Ajax.
Update: I'm trying to provide more information.
Logging in works correctly. My
ID is recognized and I printed it
out next to the board to ensure that
I was retrieving it correctly.
The ajax request does update the
board. The values passed are
correct and confirmed with firebug's
console. However instead of placing
pieces only for the player they
belong to it cycles though the piece
states (0,1,2).
When manually browsing to
boardUpdate.php and putting in the
same values sent from the Ajax the
results seen in the echo'ed response
indicates that the corresponding
piece is played each time as
intended.
Same results on my laptop after
fresh load of firefox.
Manually browsing to
boardUpdate.php without logging in
before hand leave the board
unchanged (as intended when no user
is found in the session).
I've double checked the that
session_start() is on the php files
and double checked the session ID
variables.
Hope this extra information helps, i'm running out of ideas what to tell you. Should I load up the full code?
Update 2:
After checking the Ajax responce in fire-bug I realized that the 'play' request does not get a result, and the board is not updated till the next 'update'. I'm still looking into this but I'll post it here for you guys too.
boardUpdate.php
Notable places are:
Refresh Board(line6)
Place Piece(line20)
function boardUpdate($turnCount) (line63)
<?php
session_start();
require '../../omok/dbConnect.php';
//*** Refresh Board ***
if(isset($_GET['update']))
{
$bid = $_GET['bid'];
$Query=("SELECT turn FROM board WHERE bid=$bid");
$Result=mysql_query($Query);
$turnCount=mysql_result($Result,0,"turn");
if($_GET['turnCount'] < $turnCount) //** Turn increased
{
boardUpdate($turnCount);
}
}
//*** Place Piece ***
if(isset($_GET['play'])) // turn order? player detect?
{
$squareID = $_GET['play'];
$bid = $_GET['bid'];
$Query=("SELECT turn, boardstate FROM board WHERE bid=$bid");
$Result=mysql_query($Query);
$turnCount=mysql_result($Result,0,"turn");
$boardState=mysql_result($Result,0,"boardstate");
$turnCount++;
$playerId = $_SESSION['char'];
$Query=("SELECT p1, p2 FROM board WHERE bid=$bid");
$Result=mysql_query($Query);
$p1 = mysql_result($Result,0,"p1");
$p2 = mysql_result($Result,0,"p2");
$newPiece = 0; //*default no player
if($playerId == $p1)
$newPiece = 1;
if($playerId == $p2)
$newPiece = 2;
// if($newPiece != 0)
// {
$oldPiece = getBoardSpot($squareID, $bid);
$oldLetter = $boardState{floor($squareID/3)};
$slot = $squareID%3;
//***function updateCode($old, $new, $current, $slot)***
$newLetter = updateCode($oldPiece, $newPiece, $oldLetter, $slot);
$newLetter = value2Letter($newLetter);
$newBoard = substr_replace($boardState, $newLetter, floor($squareID/3), 1);
//** Update Query for boardstate & turn
$Query=("UPDATE board SET boardState = '$newBoard', turn = '$turnCount' WHERE bid = '$bid'");
mysql_query($Query);
// }
boardUpdate($turnCount);
}
function boardUpdate($turnCount)
{
$json = '{"turnCount":"'.$turnCount.'",'; //** turnCount **
$bid = $_GET['bid'];
$Query=("SELECT boardstate FROM board WHERE bid='$bid'");
$Result=mysql_query($Query);
$Board=mysql_result($Result,0,"boardstate");
$json.= '"boardState":"'.$Board.'"'; //** boardState **
$json.= '}';
echo $json;
}
function letter2Value($input)
{
if(ord($input) >= 48 && ord($input) <= 57)
return ord($input) - 48;
else
return ord($input) - 87;
}
function value2Letter($input)
{
if($input >= 10)
return chr($input += 87);
else
return chr($input += 48);
}
//*** UPDATE CODE *** updates an letter with a new peice change and returns result letter.
//***** $old : peice value before update
//***** $new : peice value after update
//***** $current : letterValue of code before update.
//***** $slot : which of the 3 sqaures the change needs to take place in.
function updateCode($old, $new, $current, $slot)
{
if($slot == 0)
{// echo $current,"+((",$new,"-",$old,")*9)";
return letter2Value($current)+(($new-$old)*9);
}
else if($slot == 1)
{// echo $current,"+((",$new,"-",$old,")*3)";
return letter2Value($current)+(($new-$old)*3);
}
else //slot == 2
{// echo $current,"+((",$new,"-",$old,")";
return letter2Value($current)+($new-$old);
}
}//updateCode()
//**** GETBOARDSPOT *** Returns the peice value at defined location on the board.
//****** 0 is first sqaure increment +1 in reading order (0-254).
function getBoardSpot($squareID, $bid)
{
$Query=("SELECT boardstate FROM board WHERE bid='$bid'");
$Result=mysql_query($Query);
$Board=mysql_result($Result,0,"boardstate");
if($squareID %3 == 2) //**3rd spot**
{
if( letter2Value($Board{floor($squareID/3)} ) % 3 == 0)
return 0;
else if( letter2Value($Board{floor($squareID/3)} ) % 3 == 1)
return 1;
else
return 2;
}
else if($squareID %3 == 0) //**1st spot**
{
if(letter2Value($Board{floor($squareID/3)} ) <= 8)
return 0;
else if(letter2Value($Board{floor($squareID/3)} ) >= 18)
return 2;
else
return 1;
}
else //**2nd spot**
{
return floor(letter2Value($Board{floor($squareID/3)}))/3%3;
}
}//end getBoardSpot()
?>
Please help, I'd be glad to provide more information if needed.
Thanks in advance =)
From the small snippet of code we have, it's difficult to tell what your problem might be. What I can say is that session_start should be one of the first things you do on each page where you're expecting to use the session. After that, I would just immediately do a var_dump of $_SESSION to see that the data is in there (put a die right after that). It is quite possible that your true problem lies somewhere else, and that the session is in fact working. Is there a problem with your login code, for example, that is causing it to wipe out the session?
You can use Firebug to look at the raw results of your AJAX calls, which should be helpful, since your script appears to work if you directly visit the page.
Cases where I've seen sessions not work as expected have generally been that session_start is being called too often or too late. The other possibility is that you have an insanely short timeout, but that sounds unlikely.
Finally, you can make sure that your PHP install is set to use cookie sessions. It's very unlikely at this point that it wouldn't be, but you could look.
One potential problem in this code is the use of $.get - it is cached by IE, so your server code doesn't run every time. Try using $.ajax with cache set to false:
$.ajax({
type: 'GET',
url: 'includes/boardControl.php',
cache: false,
data: {play: value, bid: bid}
});
Just happened to me, in my case was that i was importing a config file with the session_start and since i had deactivated errors i couldn't see that the import was never happening. Just triple check this, I know it's the basic.