Well, my question is simple:
I wish to use my PHP sessions in jQuery, in an if statement, however I do not know how I can do this on an easy way. Am I supposed to somehow import the $_SESSION in jquery?
What I basically want to do, is open a dialog if the User_ID is the same as the $_SESSION User_ID. Also I wish to have it checked to see if someone is an administrator, shop-manager or a user, with the session. This information already exists in PHP and the User_ID only exists in jQuery.
if($admin == true || gebr_id == $_SESSION['id']){
Javascript code here?
}
I think that would be the easiest way to solve it, however that does not seem to work for me. Perhaps I am forgetting tags for the PHP to understand it's javascript?
I've figured out an easy way to come around the solution, thanks you you all!
Solution:
$('.do').click(function(){
<?php
if ($admin == true) {
echo "$('#dialog').dialog('open');\n";
echo "var cid = $(this).attr('id');\n";
echo "var datum = cid.substr(0, 10);\n";
echo "var naampos = cid.indexOf('|');\n";
echo "var gebridpos = cid.indexOf('||');\n";
echo "var naam = cid.substring(naampos+1,gebridpos);\n";
echo "var gebrid = cid.substring(gebridpos+2);\n";
echo "$.ajax({\n";
echo "type: \"POST\",\n";
echo "url: \"agenda.php\",\n";
echo "data: naam,\n";
echo "success: function(){\n";
echo "$('#gebruikerinput').html(\"<input type='text' READONLY='' size='35' value='\" + naam +\"'>\");\n";
echo "$('#gebridinput').html(\"<input type='hidden' name='gebridtextbox' value='\" + gebrid + \"'>\");\n";
echo "$('#datuminput').html(\"<input type='text' READONLY='' size='12' name='datum' value='\" + datum + \"'>\");\n";
echo "}\n";
echo "})\n";
echo "return false;\n";
}
?>
});
It seems to be working so far. The only thing left for me to do is to make so jQuery returns a User_ID variable which needs to be identical to the session ID.
if($admin == true || gebr_id == $_SESSION['id']){
$javascript = "javascript code here";
}
and then in your html
<body>
<?php echo $javascript ?>
</body>
You cannot import the $_SESSION, but you can store some of them (only those that you want) in the cookie and read it in javascript.
For example: store the user-id in the cookie and you can read the value from the cookie in javascript.
read cookie:
function getCookie(c_name)
{
var i,x,y,ARRcookies=document.cookie.split(";");
for (i=0;i<ARRcookies.length;i++)
{
x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
x=x.replace(/^\s+|\s+$/g,"");
if (x==c_name)
{
return unescape(y);
}
}
}
Sadly that you can mix server-side script (PHP) with client-side script (Javascript). However, you can use PHP to echo Javascript, like:
if ($admin == true || gebr_id == $_SESSION['id']){
echo '<script>
alert("Admin!");
$("selector").function(); //
</script>';
}
Php is a server side language. javascript runs on the browser (client side).You can do this:
if($admin == true || gebr_id == $_SESSION['id'])
echo "<script>";
echo "here your jquery function";
echo "</script>";
}
So that you're just rendering HTML
hope it helps
<script type="text/javascript">
<?php if($admin == true || gebr_id == $_SESSION['id']){ ?>
alert('<?php print $admin; ?>');
<?php } ?>
</script>
also works.
Bypassing the apparently obvious security flaws with what you seem to be suggesting, you want to output the PHP session ID to your web page. Of course, JQuery is a client-side language, and it's pretty trivial to circumvent any client-side security of that nature.
<script type='text/javascript'>
<?php
//put in your variables from PHP
echo 'var phpId="' . $_SESSION['id'] .'";' ."\n";
echo 'var admin=' .$admin.";\n";
?>
//Back to Javascript (client side) here
if (gebr_id == phpId || admin){
...
}
</script>
You say you only have the user ID in JQuery. What you should do is code it so you have the user id available in PHP instead... Submit a form with the user id or something like that, then you can store that in the PHP session and do your authentication server-side.
If you like to get access to PHP Sessions from javascript, you can write a simple wrapper.
Somethign like this:
<?php
session_start($_GET['sid']);
echo json_encode($_SESSION);
?>
Keep in mind that this is a possible security flaw, as everyone can get access to your PHP Session variables from outside (with a valid session id).
Now you can simply use jQuery to ask the server for the current session data
Related
Is it possible to hide the table with jQuery if their is session present?
this is my session code
<?php
$username = $this->session->userdata('username');
if($username == TRUE){
echo "WELCOME ".$username;
}else{
echo "<div class='msg'>Please Log In</div>";
}
?>
and in my jQuery I dont know what to put in IF statement so I put it like this
if(".msg:visible"){
$('table').hide();
}
If possible I want to hide the table using jQuery
You can do using jQuery try below code
if ($(".msg").length > 0) {
$('table').hide();
}
if($(".msg").is(":visible"))
$('table').hide();
If you need to hide the table when session exists (when msg is not visible), you can try this with jQuery:
if (!$('.msg').is(':visible')) {
$('table').hide();
}
However, if you page reloads when your users log in, you could do it directly on the table without jQuery:
<table <?php echo $username == TRUE ? 'style="display: none"' : ''; ?>>
<!-- contents -->
</table>
I am using this if statement to redirect a user if the values in a .txt document is 0 but if it is 1 I want nothing to happen however I'm having some issues with my code.
This is my code currently:
$setup = require('setup.txt');
if ($setup === "0") {
echo '<script type="text/javascript"> window.location = "setup.php" </script>';
}
The setup.txt document currently contains the value 0.
I'd look here as to the proper usage of the require function.
if (file_get_contents('setup.txt') == "0") {
header('Location: /setup.php');
}
Use the header function if you have not already sent output to the browser.
$setup = file_get_contents('setup.txt');
if ($setup == "0") {
header('Location: /setup.php');
}
Since all PHP is executed before the output the site. Use this option first.
You can not use include() / require() to transfer as a variable, like you have. Use file_get_contents() to achieve the results.
try this:
<?php
$setup = file_get_contents('setup.txt');
if (trim($setup) == "0") {
echo '<script type="text/javascript"> window.location = "setup.php" </script>';
}
?>
I'm trying to redirect users of a web page to one of two different pages, depending on which of two buttons they click. My approach was to link each onclick event to a javascript function, which would in turn call a php function which uses the header() function to redirect to the appropriate page. Unfortunately, the latter of the two php functions, namely insertIntoTable(), is being called automatically each time the page loads and redirecting, without giving the user a chance to even look at the page with the buttons. I'm wondering if this is an artifact of way PHP is expanded? I don't really understand, becauseit seems like the wrapping javascript function shouldn't be called until the onclick event listener does so, and the php functions shouldn't be called until on the the javascript functions linked to onclick do so. Here is the code...
<?php
session_start();
?>
<html>
<head>
<script>
function createATable()
{
<?php createATable(); ?>
}
function insertIntoTable()
{
<?php insertIntoTable(); ?>
}
</script>
</head>
<body>
<?php
// Define our redirection functions for button click events
function createATable()
{
header("Location: http://codd.edu/Project2/createtable.php?<?php echo htmlspecialchars(SID); ?>");*/
}
function insertIntoTable()
{
header("Location: http://codd.edu/Project2/insertintotable.php?<?php echo htmlspecialchars(SID); ?>");*/
}
// Set session variables so that we don't need to worry about whether
// we're coming from sign in or registration - if $Session['user_name']
// isn't set, we know were coming from the sign in
if (!$_SESSION['user_name'])
{
$_SESSION['user_name'] = $_POST['nametextbox'];
$_SESSION['user_psswd'] = $_POST['psswdtextbox'];
echo "<br />setting session variables";
}
echo "<br />Not setting session variables";
// If we aren't setting the session variables, then we are coming from the
// registration page, and therefore know that this isn't an admin account
$_SESSION['is_admin'] = "false";
// Connect to database
$conn = mysql_connect("localhost", "601", "23");
or die('Could not connect: ' . mysql_error());
// Open database
mysql_select_db("601", $conn)
or die('Could not find database: ' . mysql_error());
// Get USER tuples, if any
$user = mysql_query("SELECT * FROM USERS WHERE name='$_SESSION[user_name]' AND password='$_SESSION[user_psswd]'");
// If there are no entries for this SELECT command, we cannot
// allow the user to log in
$num_user = mysql_num_rows($user);
if ($num_user < 1)
{
$_SESSION['is_user'] = "false";
header("Location: http://codd.edu/Project2/login.php?<?php echo htmlspecialchars(SID); ?>");
exit;
}
else
{
$_SESSION['user_id'] = SID;
$_SESSION['is_user'] = "true";
echo "Welcome ", $_SESSION['user_name'], "!";
echo "<br />User ID: " . $_SESSION['user_id'];
echo "<br /> User Password: " . $_SESSION['user_psswd'];
echo "Is valid user? " . $_SESSION['is_user'];
session_destroy();
echo "<button name='createtable' onclick='createATable()'>Create a Table</button>";
echo "<br /><button name='insert' onclick='insertIntoTable()'>Insert into Table</button>";
}
?>
</body>
</html>
I see no reason why createATable() shouldn't be called anytime the page is loaded. PHP is evaluated before javascript and on a different environment. Moreover, PHP allows you do define/declare a function after you call it, that is exactly what you're doing.
Pretend to be the PHP interpreter: it has no idea of what javascript is. You can even wrap the <?php createATable(); ?> line with yadayadayada ... qweryasdasd before and after it, and it will run.
Please, read this and see if it helps: http://www.developer.com/tech/article.php/923111/Client-side-Versus-Server-side-Coding---Part-1.htm
PS.: this is not related to your question, but please take a look at this: http://en.wikipedia.org/wiki/SQL_injection
Php runs on the server, the htnl output goes to the client.
Instead of trying to use php to redirect, use javascript or a simple a href.
Is it possible to make a pop up window in my existing script?
session_start();
$_SESSION['success'] = ($result) ? TRUE : FALSE;
header('location: inv_fc.php');
session_start();
if ($_SESSION['success'] == TRUE) {
// CREATE POP UP WINDOW SUCCESS
} else {
// CREATE POP UP WINDOW FAILURE
}
You can do it with Javascript. For nicer results, use jQuery UI.
if ($_SESSION['success'] == TRUE) {
echo "<script>alert('Success!');</script>";
} else {
echo "<script>alert('Failure.');</script>";
}
You could open a pop-up using javascript or target a's attribute, but it's impossible from PHP, which is executed at server side.
Edit: ok, as I saw the <script> things: it's not PHP, it's Javascript, from PHP it's not possible.
<?php if ($_SESSION['success'] == TRUE)?>
<script>window.open(...);alert('Your Awesome!');</script>
<?php else ?>
<script>window.open(...);alert('You Fail!!');</script>
<?php endif; ?>
i'm triying to use javascript redirect to main window after log in succeed in an iframe.
this is my code :
if ($_GET['redirect']!='') {
$redirect=$_GET['redirect'];
$smart->assign('redirect',$redirect);
}
$redirect=$_GET['redirect'];
echo $redirect;
if(isset ($_SESSION['user'])&&$_SESSION['user']!='') {
$user->email=$_SESSION['user'];
$user->addCorporate();
$user->signIn();
$user->loadSession();
echo("<script language=\"javascript\" type=\"text/javascript\">");
echo "document.write('redirecting...');";
if ($redirect!='') {
echo 'self.parent.location = "'.$redirect.'"';
} else
echo 'self.parent.location = "index.php"';
//echo $redirect;
// redirect($redirect);
echo "</script>";
}
the echo $redirect displays http://xxxxxxxx/play.php?action=play&id=d59541b89828da34e9a8345a1bdafe2b
but the redirection is made to http://xxxxxxxx/play.php? (without the php option)
This sounds pretty mysterious.
Here's how I'd proceed: Turn off JavaScript in your browser and examine your created JavaScript. Then, at least, you know whether maybe for some bizarre reason the wrong URL is print out after all, or whether the problem's in the redirection part.
If you change the line:
echo 'self.parent.location = "'.$redirect.'"';
to this:
echo 'alert("'.$redirect.'")';
What happens?