storing value in session variable, and checking it - php

i have made a login form on a light box using a javascript function. Now i want to store a value on session variable, so to check if the user has logined , and not to show him login lightbox again and again on his navigations on the page.. My javascript function is:
<script language="javascript" type="text/javascript">
function createlightbox()
{
document.getElementById('light').style.display='block';
document.getElementById('fade').style.display='block'
}
function closelightbox()
{
document.getElementById('light').style.display='none';
document.getElementById('fade').style.display='none'
}
function checksession()
{ if (admin=="admin")
{closelightbox();}
else
{createlightbox();}
}
function check(form)/*function to check userid & password*/
{
/*the following code checkes whether the entered userid and password are matching*/
if(form.name.value == "admin" && form.password.value == "admin")
{
closelightbox();
var admin = <?php $_SESSION['Admin']= 1; ?>
}
else
{
document.getElementById("error").style.display='block';/*displays error message*/
}
}
</script>
And i m calling the checksession function in my forms onsubmit event as
<form id="Admin" onreset="checksession()">
The problem is, on every reset or submit of form, even on the page changes, the login form is shown. Why it is not checking the check session function.
Please tell me any fault i m making

i'm not sure where your conditions are.
but the following code should present in php script that generates your lightbox:
<?php echo '<script> var admin ='.$_SESSION['Admin'].'</script>'; ?>
(to check above is working correctly, you could View source code of your page and see if there is a line like: <script> var admin =1</script>)
the following should be before you access admin variable setted above:
<script language="javascript" type="text/javascript">
.... //other code
function checksession()
{ if(admin =="admin")
{closelightbox();}
else
{createlightbox();}
}
....
also note that if statement should compare == not assign =

Related

Run a Jquery Login Form if php Login Check Fails

I do not want to redirect to a new page if the login check fails, rather I want to stay on the page and simulate a click on the login button which would bring up a login form popup. Any ideas?
Lame attempt using php redirect which doesnt do anything desired:
function logincheck($redirect='')
{
if(!isset($_SESSION['duser']['id']))
{
if($redirect)
{
header("Location: ".$config['site_url']."index.php? redirect=".urlencode($redirect));
}
else
{
header("Location: ".$config['site_url']."index.php#login-box");
}
exit;
}
}
HTML button:
<li><a class="log" href="#login-box"></a></li>
In your <head></head> define a javascript variable if the user is logged in or not such as
<script type="text/javascript" />
var logged_in = <? if(!isset($_SESSION['duser']['id'])){
echo "FALSE";
}else{
echo "TRUE";
}
?>
</script>
Now when you load the page check using javascript that if logged_in is TRUE or FALSE and base on that run the javascript to pop up for login panel
Hope it helps :)

Triggering or preventing a javascript function if $_SESSION['SESS_USER_ID'] isn't set

This php function currently redirects the user to another page if they aren't logged in
if(!isset($_SESSION['SESS_USER_ID']) || (trim($_SESSION['SESS_USER_ID']) == '')){
header("location: login_failed.html");
exit();
}
How can I change the function so that instead of redirecting the user it does the following:
Triggers the javascript function: loginFailed();
Prevents specific iframes which are preloaded from launching (these require a user to be logged in, and are currently opening as empty iframes if they're not logged in). I've included the script for this below. Alternatively, preventing iframes from launching which have a specific class or data-fancybox-type, or those which require !isset($_SESSION['SESS_USER_ID']).
The functions which I want to trigger/prevent
function loginFailed() {
$().toastmessage('showToast', {
text: 'Log In Failed<br/><br/>Please check your username and password',
sticky: false,
position: 'top-center',
type: 'message',
closeText: '',
close: function () { console.log("toast is closed ...") }
});
}
$(function () {
$(".fancybox").fancybox({
preload: true,
});
$(".fancybox").eq(0).trigger('click');
});
I've tried:
echo "<script>loginFailed();</script>";
echo "<script type="text/javascript">loginFailed();</script>";
echo "<script type="text/javascript">loginFailed;</script>";
Adding on to techfoobar's answer...
It is generally a good practice to put your variables from PHP into Javascript (if needed) and letting Javascript handle it, as opposed to echoing different javascript depending on a PHP variable.
Keep in mind that all javascript variables CAN be manipulated by the client.
Try something like this:
if(!isset($_SESSION['SESS_USER_ID']) || (trim($_SESSION['SESS_USER_ID']) == '')){
$t="no_session";
}
else{
$t="yes_session";
}
....
<script>
var session="<?php echo $t; ?>";
if(session == "no_session")
loginFailed();
</script>
PHP runs on the server side. JavaScript runs on the client side inside the browser. PHP cannot directly invoke JavaScript functions.
PHP can however render JavaScript along with the HTML to the browser so that the browser can in turn run it.
In your particular case, one thing you can do is check for logged-in status via an AJAX call and call the required JS methods on its success callback.
Example:
For checking the login status:
/* JS */
function checkLoginState() {
$.post('/yourserver.com/isloggedin.php', function(data) {
if(data != "OK") { // not logged in
// call your JS method thats disables stuff etc.
loginFailed();
}
});
}
// Periodically check login state
setInterval(checkLoginState, 10000); // check every 10 seconds, change as needed.
/* PHP - isloggedin.php */
if(!isset($_SESSION['SESS_USER_ID']) || (trim($_SESSION['SESS_USER_ID']) == '')){
echo "NOT OK";
}
else {
echo "OK";
}
I combined #hellohellosharp's suggestion with a solution which was given to me by #willoller for another problem and figured it out :-)
Add this to the php:
$logged_in = (isset($_SESSION['SESS_USER_ID']));
Add this to the javascript:
<?php if ($logged_in) : ?>
<a class="fancybox" data-fancybox-type="iframe" href="iframe1.html"></a>
<?php else : ?>
loginFailed();
<?php endif; ?>
I'm also using this to change the menu options based on whether or not a user's logged in.
Just a reminder - this uses ISSET to determine what javascript should show, but it only changes the user's experience and doesn't provide any security.

testing a php session variable on page load with Jquery

I have a session variable that is set when the user submits a form with a certain option selected. When the page refreshes I need to test this session variable and if it exists then make some of the form read only. This is my code so far, php:
<?php
require("header.php");
if(isset($_REQUEST['searching'])){ //check if form has been submitted
echo"<h2>Submitted</H2><p>";
connect('final');//connect to DB
$fName = $_POST['addFname'];
$lName = $_POST['addLname'];
$address = $_POST['address']
$dropdown = $_POST['field']; // yes or no option
$fName = htmlspecialchars($fName);
$fName = mysql_real_escape_string($fName);
$lName = htmlspecialchars($lName);
$lName = mysql_real_escape_string($lName);
$address = htmlspecialchars($line2); // stop HTML characters
$address = mysql_real_escape_string($line2); //stop SQL injection
if($dropdown== "no"){
$_SESSION['name'] = "$fName";
}
?>
'field' is the name of my dropdown with 2 options yes and no.
MY JS for getting the variable:
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<script type = "text/javascript">
var session;
function multi(){
$.ajaxSetup({cache: false})
$.get('getSession.php', {requested: 'foo'}, function (data) {
session = data;
});
}
</script>
I use that to get the variable from the session, getSession.php has the following:
<?php
session_start();
if (isset($_GET['name'])) {
// return requested value
print $_SESSION[$_GET['name']];
} else {
print json_encode($_SESSION);
}
?>
finally I have this function to disable the text fields
<script language="JavaScript">
<!--
function enable_text2()
{
if (session !=""){
status = "true";
document.add.addFname.readonly=readonly;
document.add.addLname.readonly=readonly;
}
}
//-->
</script>
the rest of my html is just a form, this is all in one document with the php code at the top, and the javascript functions in the head tag.
I call a wrapper function in the body onload tag, which then calls both of those functions, I thought the first function would get the session variable if it existed from the php document and then the second function would test if it was not empty, if it wasn't then it would make the fields read only.
However when I select no in the drop down and submit the form, the page refreshes and nothing happens, the fields are not read only.
Why You are using javascript for it??
session_start();
if (isset($_GET['name'])) {
$disable=true;
} else {
$disable=false;
}
<input type="text" name="addFname" <?php if($disable) { ?> readonly="readonly" <?php } ?>
Here i have taken "addFname" .you can disable any element inside that php if condition
Assuming PHP is generating the page you've got this "must be disabled" form on, there's no need for an ajax call - PHP can output a JS variable when it builds the page, e.g.
<script type="text/javascsript">
var disableForm = <?php echo (($_SESSION['somevar'] == 'whatever' ? 'true' : 'false') ?>;
if (disableForm) {
...
}
</script>

display a javascript message before proceeding

I have this code that is to fetch a particular item in the database after the user presses a button. If the item is found I would like to display a confirm message via javascript and I don't know how to show it.
After obtaining the item from the database
if(null!=mysqli_fetch_array($res)))
{
echo ""; // how can I call the javascript code here ?
}
and the following confirm box
<script type="text/javascript">
function onConfirm()
{
return confirm("Display this item ?");
}
</script>
Use jquery and ajax to get the value from the database:
<script src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
$.get("ajax.php", function(data){
if(data != "0"){
if(confirm("Display this item ?"))
{
//do something
}
}
});
ajax.php:
//other db code here
if(null!=mysqli_fetch_array($res)))
{
echo "1";
}
else{
echo "0";
}
There are number of ways you can solve this. A good way is to:
Send an ajax request to a page
The page does the mysql stuff and returns(echo in case of PHP) the message
On the callback function use simple way such as alert() to show the message.

Trigger PHP function by clicking HTML link

Is it possible to trigger a PHP function by just clicking a link? Or should I stick with the form submit method? If clicking the link will work, where should the link refer to?
Here is a sample code:
<?php
session_start();
function listMe($username){
$username = mysql_real_escape_string($username);
$query = mysql_query("INSERT INTO List (Usernames) VALUES ('$username')") or die(mysql_error());
}
?>
<html>
<head>
<title>SAMPLE</title>
</head>
<body>
Add my username to the list
<?php
listMe($_SESSION['Username']);
?>
</body>
</html>
Maybe someone can point me in the right direction. Thanks!
You can do this by means of loading the entire page over again by the use of form submission, or by loading specific page contents directly into the page without needing to go from page to page. The second method is called "AJAX" (Asynchoronous Javascript and XML). Here are two examples, one of each specified.
Form submission approach
form.php
<?php
function get_users(){
}
if(isset($_GET['get_users']))
{
get_users();
}
?>
...
<form method="get">
<input type="hidden" name="get_users">
<input type="submit">
</form>
AJAX approach
ajax_file.php
<?php
function call_me(){
// your php code
}
call_me();
?>
form.html
<html>
<head>
<script type="text/javascript">
function loadXMLDoc()
{
var xmlhttp;
if (window.XMLHttpRequest)
{
xmlhttp = new XMLHttpRequest();
}
else
{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function()
{
if(xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
// do something if the page loaded successfully
}
}
xmlhttp.open("GET","ajax_file.php",true);
xmlhttp.send();
}
</script>
</head>
<body>
click to call function
</body>
</html>
HTML
list me
PHP
<?php
if (isset($_GET['list_me'])) listMe();
(EDIT although this works, it's a bad idea as it is. One should never read from $_GET without sanitising it first)
You can pass it as a query parameter of the link.
http://example.com/?command=listMe&username=tom
However that way everybody will be able to run the function by loading that URL
List me
and in the PHP
<?php
if( isset($_GET['list_me']) && isset($_SESSION['Username'] ) ){
listMe( $_SESSION['Username'] );
}
?>
To trigger a function on link click with php the only way I know would be to append a param in the url of the link and then listen for that
Add my username to the list
Then check for link
if (isset($_GET['function'])){
runFunction();
}
This is because php is a server side technology if you want to fire something without refreshing the page you would need to look at something like javascript
I found this code in a plugin, they have user a foreach look to trigger the action:
$actions = unset($meta[$key]);
foreach ( $actions as $action => $value ) {
echo '<li>' . '<i class="fa fa-times"></i></li>';
}

Categories