I realized a code for a rate system but when I select a vote, nothing change, when I reselect again a vote, it's ok ! BUT when I see my DB on phpmyadmin, the counter of vote has 1 clic in more than the counter of vote that I "echoed" on my page... why this difference of 1?
my note.js
$(function(){
$('.star').on('mouseover', function(){
var indice = $('.star').index(this);
$('.star').removeClass('full');
for(var i = 0; i<= indice; i++){
$('.star:eq('+i+')').addClass('full');
}
});
$('.star').on('mouseout', function(){
$('.star').removeClass('full');
});
var average = $('.average').attr('data-average');
function avaliacao(average){
average = (Number(average)*20);
$('.barra .bg').css('width', 0);
$('.barra .bg').animate({width: average+'%'}, 500);
}
avaliacao(average);
$('.star').on('click', function(){
var artigoId = $('.artigoDados').attr('data-id');
var ponto = $(this).attr('id');
location.reload();
$.post('sys/votar.php',{votar: 'sim', artigo: artigoId, ponto: ponto}, function(retorno){
avaliacao(retorno.average);
$('p.votos span').html(retorno.votos);
}, 'jSON');
});
});
My html code:
<?php
$bdd = new PDO('mysql:host=localhost;dbname=notation', 'root', 'root');
?>
<html lang="pt-BR">
<head>
<meta charset="utf-8" />
<link href="css/style.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="js/note.js"></script>
</head>
<body>
<?php
$artigoId = (int)$_GET['artigo'];
$artigos = $bdd->prepare('SELECT * FROM sys_note WHERE id_recette = ?');
$artigos->execute(array($artigoId));
while($row = $artigos->fetchObject()){
echo '<h1>'.$row->titre_recette.'</h1>';
$calculo = ($row->pontos == 0) ? 0 : round(($row->pontos/$row->votos), 1);
echo '<span class="average" data-average="'.$calculo.'"></span>';
echo '<span class="artigoDados" data-id="'.$row->id_recette.'"></span>';
?>
<div class="barra">
<span class="bg"></span>
<div class="estrelas">
<?php for($i=1; $i<=5; $i++): ?>
<span class ="star" id="<?php echo $i;?>">
<span class="starAbsolute"></span>
</span>
<?php endfor;?>
</div>
</div>
<p class="votos"><span><?php echo $row->votos;?></span>votes</p>
<?php }?>
</body>
</html>
votar.php
<?php
$bdd = new PDO('mysql:host=localhost;dbname=notation', 'root', 'root');
if($_SERVER['REQUEST_METHOD'] == 'POST'){
$artigo = (int)$_POST['artigo'];
$pontos = $_POST['ponto'];
$pegaArtigo = $bdd->prepare('SELECT * FROM sys_note WHERE id_recette = ?');
$pegaArtigo->execute(array($artigo));
while($row = $pegaArtigo->fetchObject()){
$votosUpd = $row->votos+1;
$pontosUpd = $row->pontos+$pontos;
$average = round(($pontosUpd/$votosUpd), 1);
$update = $bdd->prepare('UPDATE sys_note SET votos = ?, pontos = ? WHERE id_recette = ?');
if($update->execute(array($votosUpd, $pontosUpd, $artigo))){
die(json_encode(array('average' => $average, 'votos' => $votosUpd)));
}
}
}
?>
You need to do location.reload(); after you the post, not before.
$.post('sys/votar.php',{votar: 'sim', artigo: artigoId, ponto: ponto}, function(retorno){
location.reload();
}, 'jSON');
There is no point to do the extra work inside the callback since you are reloading the page anyway.
Although, I would recommend you change the elements on the page via ajax instead of the crude location.reload();
This question already has answers here:
PHP parse/syntax errors; and how to solve them
(20 answers)
Closed 6 years ago.
I have a PHP website and the index page displays fine online, but my local copy running on my wamp server gives me a parser error "Parse error: syntax error, unexpected end of file in..."
My local PHP is the same as my production. 5.6
I looked at previously asked question PHP parse/syntax errors; and how to solve them? and it mentions nothing about end of file.
Here is my code:
<?php
include "Calls.php";
my_session_start();
$sessionid = #$_SESSION["id"];
ini_set ("display_errors", "1");
error_reporting(E_ALL);
ini_set('short_open_tag',true);
include "production.class.php";
include "emailFunctions.php";
$selection="";
$mat = "";
include "currentSeason.php";
//current production
$currProd = new Production($arrSeason[0]['logo'],$arrSeason[0]['odate'],$arrSeason[0]['cldate'],$arrSeason[0]['credits'],$arrSeason[0]['director'],$arrSeason[0]['synopsis'],$arrSeason[0]['characters'],$arrSeason[0]['cast'],$arrSeason[0]['actors'],$arrSeason[0]['photos'],$arrSeason[0]['crewPositions'],$arrSeason[0]['crewNames'],$arrSeason[0]['season'],$arrSeason[0]['shownum'],$arrSeason[0]['showname'],$arrEntireSeason[0]['auddate'],$arrEntireSeason[0]['Special'],$arrEntireSeason[0]['Rights'],$arrSeason[0]['rightsText'],$arrEntireSeason[0]['matinee'],$arrEntireSeason[0]['ticketform'],$arrEntireSeason[0]['Promotion'],$arrEntireSeason[0]['misc'],$arrEntireSeason[0]['Type']);
$curshow=$currProd->getshownumber();
$arrSize = $aS+$aaud+$aevents+$aalerts;
$Events = array();
for($x=0;$x<sizeof($arrSeason);$x++){
$Events[$x][0] = "show";
$Events[$x][1] = $arrSeason[$x]["showname"];
$Events[$x][2] = $arrSeason[$x]["odate"];
$Events[$x][3] = $arrSeason[$x]["cldate"];
$Events[$x][4] = $arrSeason[$x]["director"];
$Events[$x][5] = $arrSeason[$x]["credits"];
$Events[$x][6] = $arrSeason[$x]["season"];
$Events[$x][7] = "";
$Events[$x][8] = "";
$Events[$x][9] = "";
$Events[$x][10] = $arrSeason[$x]["shownum"];
$Events[$x][11] = $arrSeason[$x]["cast"];
$Events[$x][12] = $arrSeason[$x]["Promotion"];
}
if($aaud>1){
for($a1=0;$a1<sizeof($arrAudInfo);$a1++){
$Events[$x][0] = "audition";
$Events[$x][1] = $arrAudInfo[$a1]["showname"];
$Events[$x][2] = $arrAudInfo[$a1]["auddate"];
$Events[$x][3] = "";
$Events[$x][4] = "";
$Events[$x][5] = "";
$Events[$x][6] = $arrAudInfo[$a1]["season"];
$Events[$x][7] = $arrAudInfo[$a1]["when"];
$Events[$x][8] = $arrAudInfo[$a1]["where"];
$Events[$x][9] = $arrAudInfo[$a1]["matOnline"];
$Events[$x][10] = $arrAudInfo[$a1]["shownum"];
$Events[$x][11] = "";
$Events[$x][12] = $arrAudInfo[$a1]["audID"];
$x+=1;
}
}
if($aaud==1){
$Events[$x][0] = "audition";
$Events[$x][1] = $arrAudInfo[0]["showname"];
$Events[$x][2] = $arrAudInfo[0]["auddate"];
$Events[$x][3] = "";
$Events[$x][4] = "";
$Events[$x][5] = "";
$Events[$x][6] = $arrAudInfo[0]["season"];
$Events[$x][7] = $arrAudInfo[0]["when"];
$Events[$x][8] = $arrAudInfo[0]["where"];
$Events[$x][9] = "";
$Events[$x][10] = $arrAudInfo[0]["shownum"];
$Events[$x][11] = "";
$Events[$x][12] = $arrAudInfo[0]["audID"];
$x+=1;
}
if($aevents>1){
for($a2=0;$a2<sizeof($arrEvents);$a2++){
$Events[$x][0] = "event";
$Events[$x][1] = $arrEvents[$a2]["Event"];
$Events[$x][2] = $arrEvents[$a2]["eventDate"];
$Events[$x][3] = "";
$Events[$x][4] = "";
$Events[$x][5] = "";
$Events[$x][6] = "";
$Events[$x][7] = "";
$Events[$x][8] = $arrEvents[$a2]["where"];
$Events[$x][9] = "";
$Events[$x][10] = $arrEvents[$a2]["ID"];
$Events[$x][11] = $arrEvents[$a2]["EventDetails"];
$x+=1;
}
}
if($aevents == 1){
$Events[$x][0] = "event";
$Events[$x][1] = $arrEvents[0]["Event"];
$Events[$x][2] = $arrEvents[0]["eventDate"];
$Events[$x][3] = "";
$Events[$x][4] = "";
$Events[$x][5] = "";
$Events[$x][6] = "";
$Events[$x][7] = "";
$Events[$x][8] = $arrEvents[0]["where"];
$Events[$x][9] = "";
$Events[$x][10] = $arrEvents[0]["ID"];
$Events[$x][11] = $arrEvents[0]["EventDetails"];
}
if($aalerts == 1){
$Events[$x][0] = "alert";
$Events[$x][1] = $arrAlerts[0]["Alert"];
$Events[$x][2] = $arrAlerts[0]["alertDate"];
$Events[$x][3] = "";
$Events[$x][4] = "";
$Events[$x][5] = "";
$Events[$x][6] = "";
$Events[$x][7] = "";
$Events[$x][8] = $arrAlerts[0]["where"];
$Events[$x][9] = "";
$Events[$x][10] = $arrAlerts[0]["ID"];
$Events[$x][11] = $arrAlerts[0]["AlertDetails"];
}
//Sort events by date
array_sort_by_column($Events,2);
//register email
if(isset($_POST['emailSub'])){
joinEmail($_POST['email']);
}
function array_sort_by_column(&$array, $column, $direction = SORT_ASC){
$reference_array = array();
foreach($array as $key => $row){
$reference_array[$key] = $row[$column];
}
array_multisort($reference_array, $direction, $array);
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>The Little Theatre of Jefferson City</title>
<link href="css/style.css" rel="stylesheet" type="text/css" />
<link href="css/menu.css" rel="stylesheet" type="text/css" />
<link rel="shortcut icon" href="images/favicon.ico" />
<script src="scripts/plugins.js"></script>
<script>
function getCast(num,season){
document.getElementById("showDetails").src = "cast.php?season=" + season + "&shownum=" + num;
}
function getAudInfo(num,season,aid){
//alert(aid);
document.getElementById("showDetails").src = "viewAudInfo.php?aid=" + aid + "&season=" + season + "&shownum=" + num;
}
function getEvent(num){
//alert(num)
document.getElementById("showDetails").src = "eventdetail.php?event=" + num;
}
function getAlert(num){
//alert(num)
document.getElementById("showDetails").src = "alertdetail.php?alert=" + num;
}
function getVideo(file,auto){
document.getElementById('player2').src="video.php?video="+file+"&auto="+auto;
}
</script>
<style type="text/css">
#dhtmltooltip{
font-size: 12px;
position: absolute;
width: 200px;
border: 3px inset black;
padding: 2px;
background-color: lightyellow;
visibility: hidden;
z-index: 100;
/*Remove below line to remove shadow. Below line should always appear last within this CSS*/
filter: progid:DXImageTransform.Microsoft.Shadow(color=gray,direction=135);
}
</style>
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-39749769-1', 'tltjc.org');
ga('send', 'pageview');
</script>
</head>
<body>
<div id="dhtmltooltip"></div>
<script type="text/javascript">
/***********************************************
* Cool DHTML tooltip script- � Dynamic Drive DHTML code library (www.dynamicdrive.com)
* This notice MUST stay intact for legal use
* Visit Dynamic Drive at http://www.dynamicdrive.com/ for full source code
***********************************************/
selectArray=new Array("Click on the Prison Brews logo to download a special promotion for Whorehouse ticket holders!")
var offsetxpoint=-60 //Customize x offset of tooltip
var offsetypoint=20 //Customize y offset of tooltip
var ie=document.all
var ns6=document.getElementById && !document.all
var enabletip=false
if (ie||ns6)
var tipobj=document.all? document.all["dhtmltooltip"] : document.getElementById? document.getElementById("dhtmltooltip") : ""
function ietruebody(){
return (document.compatMode && document.compatMode!="BackCompat")? document.documentElement : document.body
}
function ddrivetip(thetext, thecolor, thewidth){
if (ns6||ie){
if (typeof thewidth!="undefined") tipobj.style.width=thewidth+"px"
if (typeof thecolor!="undefined" && thecolor!="") tipobj.style.backgroundColor=thecolor
tipobj.innerHTML=selectArray[thetext]
enabletip=true
return false
}
}
function positiontip(e){
if (enabletip){
var curX=(ns6)?e.pageX : event.clientX+ietruebody().scrollLeft;
var curY=(ns6)?e.pageY : event.clientY+ietruebody().scrollTop;
//Find out how close the mouse is to the corner of the window
var rightedge=ie&&!window.opera? ietruebody().clientWidth-event.clientX-offsetxpoint : window.innerWidth-e.clientX-offsetxpoint-20
var bottomedge=ie&&!window.opera? ietruebody().clientHeight-event.clientY-offsetypoint : window.innerHeight-e.clientY-offsetypoint-20
var leftedge=(offsetxpoint<0)? offsetxpoint*(-1) : -1000
//if the horizontal distance isn't enough to accomodate the width of the context menu
if (rightedge<tipobj.offsetWidth)
//move the horizontal position of the menu to the left by it's width
tipobj.style.left=ie? ietruebody().scrollLeft+event.clientX-tipobj.offsetWidth+"px" : window.pageXOffset+e.clientX-tipobj.offsetWidth+"px"
else if (curX<leftedge)
tipobj.style.left="5px"
else
//position the horizontal position of the menu where the mouse is positioned
tipobj.style.left=curX+offsetxpoint+"px"
//same concept with the vertical position
if (bottomedge<tipobj.offsetHeight)
tipobj.style.top=ie? ietruebody().scrollTop+event.clientY-tipobj.offsetHeight-offsetypoint+"px" : window.pageYOffset+e.clientY-tipobj.offsetHeight-offsetypoint+"px"
else
tipobj.style.top=curY+offsetypoint+"px"
tipobj.style.visibility="visible"
}
}
function hideddrivetip(){
if (ns6||ie){
enabletip=false
tipobj.style.visibility="hidden"
tipobj.style.left="-1000px"
tipobj.style.backgroundColor=''
tipobj.style.width=''
}
}
document.onmousemove=positiontip
</script>
<div id="main">
<div class="container">
<div id="header">
<div id="logo">
</div>
</div>
<?php include "menu.php" ?>
<div id="block_collage" class="block_flash">
<script type="text/javascript">
if (pluginlist.indexOf("Flash")!=-1){
document.write ("<embed src='images\/collage.swf' wmode='transparent' quality='high' pluginspage='http:\/\/www.macromedia.com\/go\/getflashplayer' type='application\/x-shockwave-flash' width='938' height='264'><\/embed>");
}
</script>
</div>
<div id='SpecialAnnouncement' class="block">
<h2>Now Available</h2>
<h3>Purchase your memberships online</h3><br />
You can now purchase 2016-2017 Season Memberships at all levels right here on our website! Follow this link to purchase your membership using your Visa, Mastercard or Discover.
</div>
<div id="leftpane">
<div id="block_featured" class="block">
<h2>Upcoming TLT Events</h2>
<?
for($zzz=0;$zzz<sizeof($Events);$zzz++){
?>
<div class="event">
<? if($Events[$zzz][0]=="show"){?>
<h4>
<a href="seasons.php?shownum=<?=$Events[$zzz][10]?>&curs=<?= $Events[$zzz][6]?>">
<?=switchThe($Events[$zzz][1])?>
</a>
</h4>
<div class="showinfo">
<? if(strpos($Events[$zzz][5],"by")==0){ echo "by"; }?> <?=switchThe($Events[$zzz][5])?><br/>
directed by <?=$Events[$zzz][4]?><? if(strpos($Events[$zzz][1],"Whorehouse")>0){?> <img src="images/prisonbrews_logo.jpg" style="float:right" /><? } ?><br/>
<? if(date("d",strtotime($Events[$zzz][2]))==01){?>
Show dates: <?=date("M",strtotime($Events[$zzz][2])).", ".date("Y",strtotime($Events[$zzz][3]))?><br/>
<? } else{?>
Show dates: <?=date("M",strtotime($Events[$zzz][2]))." ".date("d",strtotime($Events[$zzz][2]))."-".date("d",strtotime($Events[$zzz][3])).", ".date("Y",strtotime($Events[$zzz][3]))?><br/>
<? } ?>
</div>
<? } ?>
<? if($Events[$zzz][0]=="audition"){?>
<h4><? echo "Auditions-".switchThe($Events[$zzz][1])?></h4>
<div class="showinfo">
When: <?=date("M",strtotime($Events[$zzz][2]))." ".date("d",strtotime($Events[$zzz][2])).", ".date("Y",strtotime($Events[$zzz][2]))." at ".$Events[$zzz][7]?><br/>
Where: <?=$Events[$zzz][8]?>
</div>
<? } ?>
<? if($Events[$zzz][0]=="event"){?>
<h4><?=switchThe($Events[$zzz][1])?></h4>
<div class="showinfo">
When: <?=date("M",strtotime($Events[$zzz][2]))." ".date("d",strtotime($Events[$zzz][2])).", ".date("Y",strtotime($Events[$zzz][2]))?><br/>
Where: <?=$Events[$zzz][8]?>
</div>
<? } ?>
<? if($Events[$zzz][0]=="alert"){?>
<h4 class="alertLink"><?=switchThe($Events[$zzz][1])?></h4>
<div class="showinfo">
Where: <?=$Events[$zzz][8]?>
</div>
<? } ?>
</div><br/><br/>
<? } ?>
</div>
<div id="block_multimedia" class="block">
<div id="videoheader" class="sectionheader">
Multimedia
</div><br/><br/>
<!--<video controls style="margin-left:50px;">
<source src="images/Video/Jamie_Waier_WUD.webm" type="video/webm" />
</video>
<h2><em>Cast Interviews</em>('Wait Until Dark')</h2>-->
See video clips here!
</div>
</div>
<div id="rightpane">
<div id="block_currentInfo" class="block"><a name="ci"></a>
<? if(($Events[0][0]=="audition")&&($Events[0][2]!="0000-00-00")){?>
<iframe src="viewAudInfo.php?aid=<?=$Events[0][12]?>&season=<?=$Events[0][6]?>&shownum=<?=$Events[0][10]?>"
scrolling="yes" frameborder="0" id="showDetails" name="showDetails" height="665" width="99%" />
<? } else if($Events[0][0]=="event"){?>
<iframe src="eventdetail.php?event=<?=$Events[0][10]?>"
scrolling="yes" frameborder="0" id="showDetails" name="showDetails" height="665" width="99%" />
<? } else if($Events[0][0]=="show"){?>
<iframe src="cast.php?season=<?=$Events[0][6]?>&shownum=<?=$Events[0][10]?>"
scrolling="yes" frameborder="0" id="showDetails" name="showDetails" height="665" width="98%">
<? } ?>
</iframe>
</div>
<div id="block_signup" class="block">
<div id="signupheader" class="sectionheader">
Stay Informed
</div>
How can you keep yourself informed of everything that TLT does, including audition announcements,
ticket sales, performance reviews and more? There is more than one way! Read more below:
<hr />
Join our email list. When TLT makes a major announcement, we always send out an email about it.
<?php if(isset($_COOKIE['emailadd'])){ ?>
<br /><strong>You are registered on our email list as: <br /><?=$_COOKIE['emailadd']?></strong>
<? } else{?>
Enter your email address to sign up for our email list:<span style="color:red;"><?=$errormsg?></span>
<form action="http://cwebsolutions.net/dada/mail.cgi" method="post" accept-charset="UTF-8" id="subscription_form">
Email: <input type="text" name="email" size="40"/>
<input type="submit" name="emailSub" value="Sign Up" />
</form>
<? }?>
<hr />
Social networking is hot! Join our <a href='http://www.facebook.com/#/group.php?gid=55791655556&ref=ts' target='_blank'><img src='images/fb_icon.jpg' style='border:none;' />Facebook goup</a> and follow us on <a href='http://twitter.com/tltjc' target='_blank'><img src='images/Twitter-icon.png' style='border:none;' />Twitter</a>. We update them often.
<hr />
Subscribe to our <a href='newsfeed.php'>RSS newsfeed</a>. You'll be able to see all of our recent news as soon as it's posted.
</div>
</div>
<? include "footer.php" ?>
</div></div></body>
</html>
Most probably the combined use of normal and short open tag at the end of your document. Specifically this line:
<?php if(isset($_COOKIE['emailadd'])){ ?>
This line is opened with a normal tag. But the end of the if statement is not:
<? }?>
This causes PHP to conclude the document is not complete at the last line because it is still expecting a close tag from that if.
Short open tags are disabled by default on new installations. Presumably one installation has it enabled, and the other has not. Either enable short open tags in php.ini or replace them with normal open tags. At least using the same tag consistently will cause a more regular behavior.
Php codes will show errors because of too many things. Some of them may consider the version of PHP. If your PHP Program is latest PHP 5 or above, You must need to install that latest version of Wamp in your PC. Otherwise, it will show errors like this.
on my website, the user has several options such as language, date and region. when the user clicks anyone of those all is fine, the website adapts to the specific choices, but when they go to another page they loose all their choices, it would be nice if i found a way to keep them for their entire visit or perhaps 24hours.
example: bob goes onto my website, under the region setting, he clicks UK and as a result the website adapts and shows him a UK flag as a result. However, he when he goes to the next page he looses the flag and his region setting and has to choose his region setting all over again.
This is what I want to fix. I will post the whole code up in case this may help:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Loughborough University | Students Union</title>
<script type="text/javascript" src="scripts/changesheets.js"></script>
<?php include("scripts/lang_change.php"); ?>
<?php include("scripts/factoid_randomise.php"); ?>
<?php include("scripts/greeting.php"); ?>
<?php include("scripts/menu_change.php"); ?>
<?php include("scripts/lang_select.php"); ?>
<?php include("scripts/geo_loc_change.php"); ?>
<link href="css/style.css" rel="stylesheet" type="text/css" media="screen" />
<link href="css/grey_white.css" rel="stylesheet" type="text/css" media="screen" />
<link href="css/orange_black.css" rel="stylesheet" type="text/css" media="screen" />
<link href="css/offwhite_blue.css" rel="stylesheet" type="text/css" media="screen" />
<link href="css/style.css" rel="stylesheet" type="text/css" media="screen" />
<script type="text/javascript">
//Specify affected tags. Add or remove from list:
var tgs = new Array( 'div','td','tr','li','p');
//Specify spectrum of different font sizes:
var szs = new Array( 'xx-small','x-small','small','medium','large','x-large','xx-large' );
var startSz = 2;
function ts( trgt,inc ) {
if (!document.getElementById) return
var d = document,cEl = null,sz = startSz,i,j,cTags;
sz += inc;
if ( sz < 0 ) sz = 0;
if ( sz > 6 ) sz = 6;
startSz = sz;
if (!( cEl = d.getElementById( trgt ) ) ) cEl = d.getElementsByTagName( trgt )[ 0 ];
cEl.style.fontSize = szs[ sz ];
for ( i = 0 ; i < tgs.length ; i++ ) {
cTags = cEl.getElementsByTagName( tgs[ i ] );
for ( j = 0 ; j < cTags.length ; j++ ) cTags[ j ].style.fontSize = szs[ sz ];
}
}
</script>
</head>
<body>
<div id="wrapper">
<div id="header">
<?php
if(!isset($_POST['languages']))
{
$_POST['languages'] = array('English');
}
foreach ($_POST['languages'] as $language) {
switch ($language) {
case 'Japanese' :
echo "<div id='logo_japanese'></div>";
break;
case 'Chinese' :
echo "<div id='logo_chinese'></div>";
break;
default:
echo "<div id='logo'></div>";
break;
}
}
?>
<ruby style='float:right; margin-top:-80px;'>
<rb><button style='background-image:url(/misc/FYP/images/textchange.png); width:31px; height:29px; border:none; '></button> </rb>
<rb><a href="javascript:ts('body',-1)" ><button style='background-image:url(/misc/FYP/images/textchangeb.png); width:23px; height:29px; border:none;'></button></a></rb>
<rb><button onclick='JavaScript:changeSheets(1)' style='background-image:url(/misc/FYP/images/theme1.png); width:29px; height:29px; border:none; '></button></rb>
<rb><button onclick='JavaScript:changeSheets(2)' style='background-image:url(/misc/FYP/images/theme2.png);width:29px; height:29px;border:none;' ></button></rb>
<rb><button onclick='JavaScript:changeSheets(3)' style='background-image:url(/misc/FYP/images/theme3.png);width:29px; height:29px;border:none;' ></button></rb>
<rb><button style='background-image:url(/misc/FYP/images/Britishflag.png);width:48px; height:20px;border:none;' ></button></rb>
</ruby>
<div class='greeting'>
<?php
if(!isset($_POST['languages']))
{
$_POST['languages'] = array('English');
}
foreach ($_POST['languages'] as $language) {
switch ($language) {
case 'German' :
echo welcome($tz_ger,$greetings_ger);
break;case 'Korean' :
echo welcome($tz_kor,$greetings_kor);
break;case 'Russian' :
echo welcome($tz_rus,$greetings_rus);
break;
case 'Japanese' :
echo welcome($tz_jap,$greetings_jap);
break;
case 'Chinese' :
echo welcome($tz_chi,$greetings_chi);
break;
default:
echo welcome($tz_eng,$greetings_eng);
break;
}
}
?></div>
</div>
<div id="line"></div>
<?php
if(!isset($_POST['languages']))
{
$_POST['languages'] = array('English');
}
foreach ($_POST['languages'] as $language) {
switch ($language) {
case 'German' :
echo makeMenu($links,$tabs_ger,$title);
break;
case 'Korean' :
echo makeMenu($links,$tabs_kor,$title);
break;
case 'Russian' :
echo makeMenu($links,$tabs_rus,$title);
break;
case 'Japanese' :
echo makeMenu($links,$tabs_jap,$title);
break;
case 'Chinese' :
echo makeMenu($links,$tabs_chi,$title);
break;
default:
echo makeMenu($links,$tabs_eng,$title);
break;
}
}
?>
<div id="line"></div>
<?php
if(!isset($_POST['languages']))
{
$_POST['languages'] = array('English');
}
foreach ($_POST['languages'] as $language) {
switch ($language) {
case 'German' :
echo changeGeoLoc($GeoLoc,$details_ger,$geoplugin);
break;case 'Korean' :
echo changeGeoLoc($GeoLoc,$details_kor,$geoplugin);
break;case 'Russian' :
echo changeGeoLoc($GeoLoc,$details_rus,$geoplugin);
break;case 'Japanese' :
echo changeGeoLoc($GeoLoc,$details_jap,$geoplugin);
break;
case 'Chinese' :
echo changeGeoLoc($GeoLoc,$details_chi,$geoplugin);
break;
default:
echo changeGeoLoc($GeoLoc,$details_eng,$geoplugin);
break;
}
}
?>
<?php
if(!isset($_POST['languages']))
{
$_POST['languages'] = array('English');
}
foreach ($_POST['languages'] as $language) {
switch ($language) {
case 'Russian' :
echo "<div id='welcome_pic_russian'>";
break;
case 'Japanese' :
echo "<div id='welcome_pic_japanese'>";
break;
case 'Chinese' :
echo "<div id='welcome_pic_chinese'>";
break;
default:
echo "<div id='welcome_pic'>
";
break;
}
}
?>
<div id="play_feature">
<?php
if(!isset($_POST['languages']))
{
$_POST['languages'] = array('English');
}
foreach ($_POST['languages'] as $language) {
switch ($language) {
case 'German' :
echo selectLang($h_ger,$lang_ger,$values,$h2_ger,$lang_ger2,$countries,$day,$month,$year);
break;case 'Korean' :
echo selectLang($h_kor,$lang_kor,$values,$h2_kor,$lang_kor2,$countries,$day,$month,$year);
break;
case 'Russian' :
echo selectLang($h_rus,$lang_rus,$values,$h2_rus,$lang_rus2,$countries,$day,$month,$year);
break;
case 'Japanese' :
echo selectLang($h_jap,$lang_jap,$values,$h2_jap,$lang_jap2,$countries,$day,$month,$year);
break;
case 'Chinese' :
echo selectLang($h_chi,$lang_chi,$values,$h2_chi,$lang_chi2,$countries,$day,$month,$year);
break;
default:
echo selectLang($h_eng,$lang_eng1,$values,$h2_eng,$lang_eng2,$countries,$day,$month,$year);
break;
}
}
?>
<?php
/*
#author geoPlugin (gp_support#geoplugin.com)
#copyright Copyright geoPlugin (gp_support#geoplugin.com)
*/
require_once('scripts/geoplugin.class.php');
$geoplugin = new geoPlugin();
$geoplugin->locate();
?>
<div id='menu2' style='width:250px; margin-left:-40px;'>
</div>
<div style="color:#616161; margin-left:-20px;">
<blockquote>‘<?php
if(!isset($_POST['languages']))
{
$_POST['languages'] = array('English');
}
foreach ($_POST['languages'] as $language) {
switch ($language) {
case 'German' :
echo randomFactoid($factoidsg);
break;case 'Korean' :
echo randomFactoid($factoidsk);
break;case 'Russian' :
echo randomFactoid($factoidsr);
break;case 'Japanese' :
echo randomFactoid($factoidsj);
break;
case 'Chinese' :
echo randomFactoid($factoidsc);
break;
default:
echo randomFactoid($factoids);
break;
}
}
?>’</blockquote>
</div>
</font>
</div></div>
<div id="homepage_text">
<?php
if(!isset($_POST['languages']))
{
$_POST['languages'] = array('English');
}
foreach ($_POST['languages'] as $language) {
switch ($language) {
case 'German' :
echo "<p>text</p>";
break;
case 'Korean' :
echo "<p>text.</p> ";
break;
case 'Russian' :
echo "<p>text </p>";
break;
case 'Japanese' :
echo "<p>text</p>";
break;
case 'Chinese' :
echo "<p>text</p>";
break;
default:
echo "<p>text</p>";
break;
}
}
?>
</div></div>
</div>
</body>
</html>
This may be doable in cookies/sessions or something similar but i dnt know how i could incorporate cookies/session into this with the way i have coded it.
Any other suggestions other than cookies or sessions are welcome.
Any help greatly appreciated.
VERY IMPORTANT UPDATE
*After the suggestions below i tried this code:*
<?php
session_start(); //put this at the top of your script on all pages that need to remember
if(isset($_POST['languages']))
{
$_SESSION['languages'] = $_POST['languages'];
}?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Loughborough University | Students Union</title>
<script type="text/javascript" src="scripts/changesheets.js"></script>
<?php include("scripts/lang_change.php"); ?>
<?php include("scripts/factoid_randomise.php"); ?>
<?php include("scripts/greeting.php"); ?>
<?php include("scripts/menu_change.php"); ?>
<?php include("scripts/lang_select.php"); ?>
<?php include("scripts/geo_loc_change.php"); ?>
<link href="css/style.css" rel="stylesheet" type="text/css" media="screen" />
<link href="css/grey_white.css" rel="stylesheet" type="text/css" media="screen" />
<link href="css/orange_black.css" rel="stylesheet" type="text/css" media="screen" />
<link href="css/offwhite_blue.css" rel="stylesheet" type="text/css" media="screen" />
<link href="css/style.css" rel="stylesheet" type="text/css" media="screen" />
<script type="text/javascript">
//Specify affected tags. Add or remove from list:
var tgs = new Array( 'div','td','tr','li','p');
//Specify spectrum of different font sizes:
var szs = new Array( 'xx-small','x-small','small','medium','large','x-large','xx-large' );
var startSz = 2;
function ts( trgt,inc ) {
if (!document.getElementById) return
var d = document,cEl = null,sz = startSz,i,j,cTags;
sz += inc;
if ( sz < 0 ) sz = 0;
if ( sz > 6 ) sz = 6;
startSz = sz;
if (!( cEl = d.getElementById( trgt ) ) ) cEl = d.getElementsByTagName( trgt )[ 0 ];
cEl.style.fontSize = szs[ sz ];
for ( i = 0 ; i < tgs.length ; i++ ) {
cTags = cEl.getElementsByTagName( tgs[ i ] );
for ( j = 0 ; j < cTags.length ; j++ ) cTags[ j ].style.fontSize = szs[ sz ];
}
}
</script>
</head>
<body>
<div id="wrapper">
<div id="header">
<?php
if(!isset($_POST['languages']))
{
$_POST['languages'] = array('English');
}
foreach ($_SESSION['languages'] as $language) {
switch ($language) {
case 'Japanese' :
echo "<div id='logo_japanese'></div>";
break;
case 'Chinese' :
echo "<div id='logo_chinese'></div>";
break;
default:
echo "<div id='logo'></div>";
break;
}
}
?>
<ruby style='float:right; margin-top:-80px;'>
<rb><button style='background-image:url(/misc/FYP/images/textchange.png); width:31px; height:29px; border:none; '></button> </rb>
<rb><a href="javascript:ts('body',-1)" ><button style='background-image:url(/misc/FYP/images/textchangeb.png); width:23px; height:29px; border:none;'></button></a></rb>
<rb><button onclick='JavaScript:changeSheets(1)' style='background-image:url(/misc/FYP/images/theme1.png); width:29px; height:29px; border:none; '></button></rb>
<rb><button onclick='JavaScript:changeSheets(2)' style='background-image:url(/misc/FYP/images/theme2.png);width:29px; height:29px;border:none;' ></button></rb>
<rb><button onclick='JavaScript:changeSheets(3)' style='background-image:url(/misc/FYP/images/theme3.png);width:29px; height:29px;border:none;' ></button></rb>
<rb><button style='background-image:url(/misc/FYP/images/Britishflag.png);width:48px; height:20px;border:none;' ></button></rb>
</ruby>
<div class='greeting'>
<?php
if(!isset($_POST['languages']))
{
$_POST['languages'] = array('English');
}
foreach ($_SESSION['languages'] as $language) {
switch ($language) {
case 'German' :
echo welcome($tz_ger,$greetings_ger);
break;case 'Korean' :
echo welcome($tz_kor,$greetings_kor);
break;case 'Russian' :
echo welcome($tz_rus,$greetings_rus);
break;
case 'Japanese' :
echo welcome($tz_jap,$greetings_jap);
break;
case 'Chinese' :
echo welcome($tz_chi,$greetings_chi);
break;
default:
echo welcome($tz_eng,$greetings_eng);
break;
}
}
?></div>
</div>
<div id="line"></div>
<?php
if(!isset($_POST['languages']))
{
$_POST['languages'] = array('English');
}
foreach ($_SESSION['languages'] as $language) {
switch ($language) {
case 'German' :
echo makeMenu($links,$tabs_ger,$title);
break;
case 'Korean' :
echo makeMenu($links,$tabs_kor,$title);
break;
case 'Russian' :
echo makeMenu($links,$tabs_rus,$title);
break;
case 'Japanese' :
echo makeMenu($links,$tabs_jap,$title);
break;
case 'Chinese' :
echo makeMenu($links,$tabs_chi,$title);
break;
default:
echo makeMenu($links,$tabs_eng,$title);
break;
}
}
?>
<div id="line"></div>
<?php
if(!isset($_POST['languages']))
{
$_POST['languages'] = array('English');
}
foreach ($_SESSION['languages'] as $language) {
switch ($language) {
case 'German' :
echo changeGeoLoc($GeoLoc,$details_ger,$geoplugin);
break;case 'Korean' :
echo changeGeoLoc($GeoLoc,$details_kor,$geoplugin);
break;case 'Russian' :
echo changeGeoLoc($GeoLoc,$details_rus,$geoplugin);
break;case 'Japanese' :
echo changeGeoLoc($GeoLoc,$details_jap,$geoplugin);
break;
case 'Chinese' :
echo changeGeoLoc($GeoLoc,$details_chi,$geoplugin);
break;
default:
echo changeGeoLoc($GeoLoc,$details_eng,$geoplugin);
break;
}
}
?>
<?php
if(!isset($_POST['languages']))
{
$_POST['languages'] = array('English');
}
foreach ($_SESSION['languages'] as $language) {
switch ($language) {
case 'Russian' :
echo "<div id='welcome_pic_russian'>";
break;
case 'Japanese' :
echo "<div id='welcome_pic_japanese'>";
break;
case 'Chinese' :
echo "<div id='welcome_pic_chinese'>";
break;
default:
echo "<div id='welcome_pic'>
";
break;
}
}
?>
<div id="play_feature">
<?php
if(!isset($_POST['languages']))
{
$_POST['languages'] = array('English');
}
foreach ($_SESSION['languages'] as $language) {
switch ($language) {
case 'German' :
echo selectLang($h_ger,$lang_ger,$values,$h2_ger,$lang_ger2,$countries,$day,$month,$year);
break;case 'Korean' :
echo selectLang($h_kor,$lang_kor,$values,$h2_kor,$lang_kor2,$countries,$day,$month,$year);
break;
case 'Russian' :
echo selectLang($h_rus,$lang_rus,$values,$h2_rus,$lang_rus2,$countries,$day,$month,$year);
break;
case 'Japanese' :
echo selectLang($h_jap,$lang_jap,$values,$h2_jap,$lang_jap2,$countries,$day,$month,$year);
break;
case 'Chinese' :
echo selectLang($h_chi,$lang_chi,$values,$h2_chi,$lang_chi2,$countries,$day,$month,$year);
break;
default:
echo selectLang($h_eng,$lang_eng1,$values,$h2_eng,$lang_eng2,$countries,$day,$month,$year);
break;
}
}
?>
<?php
/*
#author geoPlugin (gp_support#geoplugin.com)
#copyright Copyright geoPlugin (gp_support#geoplugin.com)
*/
require_once('scripts/geoplugin.class.php');
$geoplugin = new geoPlugin();
$geoplugin->locate();
?>
<div id='menu2' style='width:250px; margin-left:-40px;'>
</div>
<div style="color:#616161; margin-left:-20px;">
<blockquote>‘<?php
if(!isset($_POST['languages']))
{
$_POST['languages'] = array('English');
}
foreach ($_SESSION['languages'] as $language) {
switch ($language) {
case 'German' :
echo randomFactoid($factoidsg);
break;case 'Korean' :
echo randomFactoid($factoidsk);
break;case 'Russian' :
echo randomFactoid($factoidsr);
break;case 'Japanese' :
echo randomFactoid($factoidsj);
break;
case 'Chinese' :
echo randomFactoid($factoidsc);
break;
default:
echo randomFactoid($factoids);
break;
}
}
?>’</blockquote>
</div>
</font>
<a href="http://s06.flagcounter.com/more/7ydE" ><img src="http://s06.flagcounter.com/count/7ydE/bg=FFFFFF/txt=000000/border=CCCCCC/columns=3/maxflags=25/viewers=Visitors/labels=0/pageviews=1/" alt="free counters" style="border:none; margin-left:15px;"/></a></div></div>
<div id="homepage_text">
<?php
if(!isset($_POST['languages']))
{
$_POST['languages'] = array('English');
}
foreach ($_SESSION['languages'] as $language) {
switch ($language) {
case 'German' :
echo "<p> </p>";
break;
case 'Korean' :
echo "<p></p> ";
break;
case 'Russian' :
echo "<p> </p>";
break;
case 'Japanese' :
echo "<p>。</p>";
break;
case 'Chinese' :
echo "<p></p>";
break;
default:
echo "<p></p>";
break;
}
}
?>
</div></div>
</div>
</body>
</html>
WHICH DIDNT WORK. ANY reasons why, seem to have done everything people have told me?**
The session can be used at this situation. You can assign these values in the session variable and can access on all the pages of application.
$_SESSION['somevar']='someval';
You should take a serious look at using gettext for manageable localization support. Instead of doing conditionals for every piece of your page, you'll simply call a function like <?php _('Welcome!') ?> and it will be automatically translated according to your language setting.
Download the library
Follow these instructions
Sessions or Cookies are definitely the best way to do it:
The thing is that you have to have a way to connect it with the user.
Technically you could store it in a database and either store a cookie on the user's computer that says which database entry to read or even store the user's ip and relate it to the user that way (although that's a pretty unreliable method). But that's all probably an overkill for what you want to do.
Here is how to incorporate sessions into your code:
Posting only one language
For a start lets reformat what you already have.
You have $_POST['languages'] which is actually an array that contains one result.
In that case you may as well make it a string and call it $_POST['language']
You also must remember to post it correctly (in the singular) when the user originally chooses his language.
First off you have to start the session at the top of the page:
session_start();
Next you have to save the user's selection to a session variable.
We are going to check if the user has selected a language (from the $_POST variable) and, if yes, assign it to a $_SESSION variable.
if ($_POST['language']) {
$_SESSION['language'] = $_POST['language'];
}
The session variable functions identical to any other variable, but it will carry on from page to page until the session ends.
Now we are going to check what the language is
This is pretty simple. In your example you checked what the language was by finding what the user had 'posted':
isset($_POST['languages'])
In our new code, we are going to check the session variable, which we have just saved:
$_SESSION['language']
Choosing the right language
No need to make $_POST['languages'] an array and then use a foreach to loop through it.
A simpler way of doing it would be like this:
switch($_SESSION['language']) {
case "german": //do german suff
case "english": //do english suff
etc...
}
Additionally, you first checked if the session tag was empty and then put a value if it wasn't.
You can skip that step and instead put inside the switch() { } at the end, after all the cases:
default: //do default language stuff
As a session:
session_start(); //put this at the top of your script on all pages that need to remember
if(isset($_POST['languages']))
{
$_SESSION['languages'] = $_POST['languages'];
}
Then change:
foreach ($_POST['languages'] as $language) {
to
foreach ($_SESSION['languages'] as $language) {
As a cookie:
if(isset($_POST['languages']))
{
setcookie('language', $_POST['languages'], 7776000) //sets cookie for 90 days, or 7776000 seconds
}
and change
foreach ($_POST['languages'] as $language) {
to
foreach ($_COOKIE['languages'] as $language) {
I believe this answer is complete... do you intend to support multiple languages?
DEMO + SOURCE: https://so.lucafilosofi.com/remembering-users-selection-from-one-page-to-the-next/
<?php
session_start();
if (isset($_GET['lang'])) {
$_SESSION['lang'] = $_GET['lang'];
}
if (isset($_SESSION['lang'])) {
define(LANGUAGE, $_SESSION['lang']);
}
else {
define(LANGUAGE, 'en_GB');
}
include 'languages/'.LANGUAGE.'.php';
?>
Add the top of the code, write "session_start();"
After that, whenever an update is submitted, update the matching $_SESSION array's index (you may choose names such as "region", "language", "lng" - the choice is up to you as long as you are consistent). Then, whenever you are loading a page, load it depending on the value in the $_SESSION array.
See also: http://il2.php.net/manual/en/book.session.php
After all related session updates - one main thing is that how you set your $_SESSION variables. It shows that you get it from $_POST, but there is no place in code that actually posts the value. You mention that someone clicks to change the language - is it done via the form submit, or via a URL?
Add a dump of $_SESSION variable right after you set the language value, and see if it actually gets set... I have a feeling that you never reach that line of code as you don't have a $_POST variable defined anywhere...
The only problem with the session variable is that the user can't change his setting anymore, if that is what you want! But it should be possible using hidden input variable on each page, too. In fact I'm using hidden input variable all the time and also I compress this variable so it is quite fast and secure and also I'm using ajax.
It is very difficult to read the lengthy example code. Please reduce the size of a non working example.
The PHP session code relies on a SESSION ID. There are two ways to transport these ID from web page to web page: POST and GET. But what I can see is, that you support only one, the POST method. In case of GET you must add the SESSION ID variable SID to the URL used for navigation.
The details of SESSION ID handling are described in the PHP documentation:
Passing the Session ID
My website welcome page has got a link to login and one to logout. I want to know how to only show the logout link when the user is logged in and the other way around?
index.php code:
<?php require_once('Connections/PAPCon.php'); ?>
<?php
//initialize the session
if (!isset($_SESSION)) {
session_start();
}
// ** Logout the current user. **
$logoutAction = $_SERVER['PHP_SELF']."?doLogout=true";
if ((isset($_SERVER['QUERY_STRING'])) && ($_SERVER['QUERY_STRING'] != "")){
$logoutAction .="&". htmlentities($_SERVER['QUERY_STRING']);
}
if ((isset($_GET['doLogout'])) &&($_GET['doLogout']=="true")){
//to fully log out a visitor we need to clear the session varialbles
$_SESSION['MM_Username'] = NULL;
$_SESSION['MM_UserGroup'] = NULL;
$_SESSION['PrevUrl'] = NULL;
unset($_SESSION['MM_Username']);
unset($_SESSION['MM_UserGroup']);
unset($_SESSION['PrevUrl']);
$logoutGoTo = "login.php";
if ($logoutGoTo) {
header("Location: $logoutGoTo");
exit;
}
}
?>
<?php
if (!function_exists("GetSQLValueString")) {
function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "")
{
if (PHP_VERSION < 6) {
$theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;
}
$theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue);
switch ($theType) {
case "text":
$theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
break;
case "long":
case "int":
$theValue = ($theValue != "") ? intval($theValue) : "NULL";
break;
case "double":
$theValue = ($theValue != "") ? doubleval($theValue) : "NULL";
break;
case "date":
$theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
break;
case "defined":
$theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;
break;
}
return $theValue;
}
}
mysql_select_db($database_PAPCon, $PAPCon);
$query_Users = "SELECT * FROM tbl_utilizadores";
$Users = mysql_query($query_Users, $PAPCon) or die(mysql_error());
$row_Users = mysql_fetch_assoc($Users);
$totalRows_Users = mysql_num_rows($Users);
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" >
<head>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />
<title>RelPro</title>
<link rel="stylesheet" type="text/css" media="screen" href="style.css" />
<style type="text/css">
#container #intro #pageHeader h1 {
font-size: 4em;
}
</style>
</head>
<body>
<div id="container">
<div id="intro">
<div id="pageHeader" style="padding: 20px 0 0 50px;">
<h1>RelPro</h1><h2> </h2>
<h2><span>by: Mário Honório 12ºPI Nº6</span></h2>
<h2><div style="position: absolute; left: 944px; top: 152px; height: 100px;"><img src="Logo PAP 2.png" alt="" width="230" height="187" /></div></h2>
</div>
<div id="preamble">
<h3><span>Acerca da RelPro</span></h3>
<p class="p1">Este website foi criado no âmbito do Curso Profissional de Técnico de Gestão de Equipamentos Informáticos de forma a avaliar toda a aprendizagem realizada. Foi concebido de forma a facilitar o acesso a relatórios de projectos de final de curso de várias áreas a todos os interessados. É um website de fácil acesso, simples design e produzido em linguagem PHP, MySQL e HTML.</p>
</div>
</div>
<div id="supportingText"></div>
<div id="footer"></div>
<div id="linkList">
<div id="linkList2">
<div id="lselect">
<h3 class="select"><span>Secções:</span></h3>
<ul>
<li>RelPro</li>
<li>Relatórios</li>
<li>Admin</li>
<li>Contactos</li>
<li>Login</li>
<li>Log out</li>
</ul>
</div></div>
</div>
</div>
</body>
</html>
<?php
mysql_free_result($Users);
?>
Here is a picture of the section menu where the links are:
Either hidden or disabled will do.
display it based on session
if($_SESSION['MM_Username'])
{
?>
<li>Log out</li>
<?php
}else
{
?>
<li>Login</li>
<?php
}
The use of a ternary operator can be used effectively here.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
session_start();
session_destroy(); // comment this out if it gives you trouble
// Comment this out to test and using your own method of user check.
$_SESSION['MM_Username'] = "John";
$login = "<li>Login</li>";
$logout = "<li>Log out</li>";
$check_login = isset($_SESSION['MM_Username']) ? $logout : $login;
$logout : $login - Only one will echo depending on if the session is set or not.
Then replace this entire block:
<ul>
<li>RelPro</li>
<li>Relatórios</li>
<li>Admin</li>
<li>Contactos</li>
<li>Login</li>
<li>Log out</li>
</ul>
with:
<ul>
<li>RelPro</li>
<li>Relatórios</li>
<li>Admin</li>
<li>Contactos</li>
<?php echo $check_login; ?>
</ul>
<?php echo $check_login; ?> takes care of both actions.
You will need to make a few adjustments of course, as far as placement goes.
Reference(s):
http://php.net/manual/en/language.operators.comparison.php
You can display it with checking if the session variable(s) is set. Example for only one session variable:
if(isset($_SESSION['MM_Username']))
echo '<li>Log out</li>';
else
echo '<li>Login</li>';
Do not use MySQL driver as it is deprecated. Use MySQLi(mproved) instead.
After some research and some try and fail attempts here is the final code i used to do this thingy (with some addons):
<?php
$loginlink = "index.php";
if (isset($_SESSION['MM_Username'])){
echo "Hello " . $_SESSION['MM_Username'];
echo "<br/><a href='".$logoutAction."'>Logout</a>";
}else{
echo "<a href='".$loginlink."'>Login</a>";}
?>
It worked for me and maybe it can help someone else. Thanks to #Richard Reiber whose code was my jump start.
Peace, Slaxer13