Set SESSION on php and remove it via JAVASCIPT [duplicate] - javascript

Is it possible to set PHP session variables using Javascript?

In JavaScript:
jQuery('#div_session_write').load('session_write.php?session_name=new_value');
In session_write.php file:
<?
session_start();
if (isset($_GET['session_name'])) {$_SESSION['session_name'] = $_GET['session_name'];}
?>
In HTML:
<div id='div_session_write'> </div>

The session is stored server-side so you cannot add values to it from JavaScript. All that you get client-side is the session cookie which contains an id. One possibility would be to send an AJAX request to a server-side script which would set the session variable. Example with jQuery's .post() method:
$.post('/setsessionvariable.php', { name: 'value' });
You should, of course, be cautious about exposing such script.

If you want to allow client-side manipulation of persistent data, then it's best to just use cookies. That's what cookies were designed for.

or by pure js, see also on StackOverflow :
JavaScript post request like a form submit
BUT WHY try to set $_session with js? any JS variable can be modified by a player with
some 3rd party tools (firebug), thus any player can mod the $_session[]! And PHP cant give js any secret codes (or even [rolling] encrypted) to return, it is all visible. Jquery or AJAX can't help, it's all js in the end.
This happens in online game design a lot. (Maybe a bit of Game Theory? forgive me, I have a masters and love to put theory to use :) ) Like in crimegameonline.com, I
initialize a minigame puzzle with PHP, saving the initial board in $_SESSION['foo'].
Then, I use php to [make html that] shows the initial puzzle start. Then, js takes over, watching buttons and modding element xy's as players make moves. I DONT want to play client-server (like WOW) and ask the server 'hey, my player want's to move to xy, what should I do?'. It's a lot of bandwidth, I don't want the server that involved.
And I can just send POSTs each time the player makes an error (or dies). The player can block outgoing POSTs (and alter local JS vars to make it forget the out count) or simply modify outgoing POST data. YES, people will do this, especially if real money is involved.
If the game is small, you could send post updates EACH move (button click), 1-way, with post vars of the last TWO moves. Then, the server sanity checks last and cats new in a $_SESSION['allMoves']. If the game is massive, you could just send a 'halfway' update of all preceeding moves, and see if it matches in the final update's list.
Then, after a js thinks we have a win, add or mod a button to change pages:
document.getElementById('but1').onclick=Function("leave()");
...
function leave() {
var line='crimegameonline-p9b.php';
top.location.href=line;
}
Then the new page's PHP looks at $_SESSION['init'] and plays thru each of the
$_SESSION['allMoves'] to see if it is really a winner. The server (PHP) must decide if it is really a winner, not the client (js).

You can't directly manipulate a session value from Javascript - they only exist on the server.
You could let your Javascript get and set values in the session by using AJAX calls though.
See also
Javascript and session variables
jQuery click event to change php session variable

One simple way to set session variable is by sending request to another PHP file. Here no need to use Jquery or any other library.
Consider I have index.php file where I am creating SESSION variable (say $_SESSION['v']=0) if SESSION is not created otherwise I will load other file.
Code is like this:
session_start();
if(!isset($_SESSION['v']))
{
$_SESSION['v']=0;
}
else
{
header("Location:connect.php");
}
Now in count.html I want to set this session variable to 1.
Content in count.html
function doneHandler(result) {
window.location="setSession.php";
}
In count.html javascript part, send a request to another PHP file (say setSession.php) where i can have access to session variable.
So in setSession.php will write
session_start();
$_SESSION['v']=1;
header('Location:index.php');

Not possible. Because JavaScript is client-side and session is server-side. To do anything related to a PHP session, you have to go to the server.

be careful when doing this, as it is a security risk. attackers could just repeatedly inject data into session variables, which is data stored on the server. this opens you to someone overloading your server with junk session data.
here's an example of code that you wouldn't want to do..
<input type="hidden" value="..." name="putIntoSession">
..
<?php
$_SESSION["somekey"] = $_POST["putIntoSession"]
?>
Now an attacker can just change the value of putIntoSession and submit the form a billion times. Boom!
If you take the approach of creating an AJAX service to do this, you'll want to make sure you enforce security to make sure repeated requests can't be made, that you're truncating the received value, and doing some basic data validation.

I solved this question using Ajax. What I do is make an ajax call to a PHP page where the value that passes will be saved in session.
The example that I am going to show you, what I do is that when you change the value of the number of items to show in a datatable, that value is saved in session.
$('#table-campus').on( 'length.dt', function ( e, settings, len ) {
$.ajax ({
data: {"numElems": len},
url: '../../Utiles/GuardarNumElems.php',
type: 'post'
});
});
And the GuardarNumElems.php is as following:
<?php
session_start();
if(isset ($_POST['numElems'] )){
$numElems = $_POST['numElems'];
$_SESSION['elems_table'] = $numElems;
}else{
$_SESSION['elems_table'] = 25;
}
?>

Related

How i can use PHP Session in React?

I have a question of session PHP in React. I have to create an online shop in React and PHP. I currently programming a shopping cart. To do this, I have to use PHP Session. I can't use JWT, so my questions are:
How to start a Session if I can't include PHP code in index.html (react-create-app, MVC, I can't include start_session() at the beginning of the page)
How to retrieve data from Session (is it possible by ajax?)
I have never used PHP and React. So far I have only used restful API.
Please help.
Yes i think you can. Check this question and the most voted answer:
The answer is yes:
Sessions are maintained server-side. As far as the server is concerned, there is no difference between an AJAX request and a regular page request. They are both HTTP requests, and they both contain cookie information in the header in the same way.
From the client side, the same cookies will always be sent to the server whether it's a regular request or an AJAX request. The Javascript code does not need to do anything special or even to be aware of this happening, it just works the same as it does with regular requests.
Do AJAX requests retain PHP Session info?
What you can do is initialize a Javascript variable with your PHP variable. This is possible because PHP, a server-side language executes on the page before Javascript, so it's almost like entering plain text where the right-hand side of the JS line is.
An example would be something like this in your index.html file:
index.php (you must rename your index.html file to index.php so the computer knows there's some PHP in there). Also, must ensure PHP is installed in your local environment hosting this. Something like npm install PHP, brew install PHP, or yum install PHP will do.
<script>
// Note here: we must ensure name is set,
// otherwise it would look something like
// let name = ;
// this would cause an error
// that is why I check the value is present with isset()
let name = <? echo isset($name) ? $name : "Air"; ?>;
</script>
Therefore, I think you would just need to ensure your environment supports PHP. You can also use a subroutine/webservice/ajax call to do the same; however, this is a little bit more complex in regards to its setup.

Passing javascript variables to php

I am now on a php page that has presented the user with some choices and I have saved the users input in 5 javascript variables:
product_format
product_print
product_paper_weight
product_paper_type
product_quantity
I want to send them to a a calculate.php page that will do the calculation of the price and then include calculate.php on my page and present the user with the price dynamically. I have read send javaScript variable to php variable
that I can use:
window.location.href = "calculate.php?name=" + javascriptVariable (and the rest);
And then I could use php get to calculate by querying the database. I also need this to be done continously as soon as the user changes an option I need to recalculate the price and present a new price.
Is this possible? Is there a better approach? Am I thinking right? Should I instead calculate the price by loading the php-sql data into javascript and calculate in javascript instead? Which is quicker and more secure?
The page http://www.reclam.se/trycksaker.php?product_id=1
This is a perfect application for AJAX. Much easier if you use jQuery, though you can do it in pure Javascript. Essentially, create a Javascript function that takes place when a field is changed (e.g., $('.product').change(function() { }); if you set class="product" on all the relevant input fields) and in that function use $.ajax to post the data to your PHP form.
You can do all the calculations in Javascript. If the data is dependent on database lookups or relatively complex math then AJAX makes more sense. If the calculations are very simple then you can embed the calculations directly in the .change function.
Using window.location.href= will cause a full page load, which does not sound like what you want.
As we all know this very well that php code runs on server side and javascript on client side. To transfer data between client and server, we need some kind of data transfer protocol and thats where Http comes in. You can send data to php server from client side either by Form or Ajax call with http get or post method.And once data are sent to php server, you can catch those data using php super globals $_GET or $_POST.

Pass javascript value into PHP variable [duplicate]

This question already has answers here:
How do I pass variables and data from PHP to JavaScript?
(19 answers)
Closed 7 years ago.
I'm trying to include JavaScript variables into PHP code as PHP variables, but I'm having problems doing so. When a button is clicked, the following function is called:
<script type="text/javascript">
function addTraining(leve, name, date)
{
var level_var = document.getElementById(leve);
var training_name_var = document.getElementById(name);
var training_date_var = document.getElementById(date);
<?php
$result = "INSERT INTO training(level, school_name, training_date) VALUES('level_var', 'training_name_var', 'training_date_var')" or die("Query not possible.");
?>
</script>
Is it possible?
PHP is run server-side. JavaScript is run client-side in the browser of the user requesting the page. By the time the JavaScript is executed, there is no access to PHP on the server whatsoever. Please read this article with details about client-side vs server-side coding.
What happens in a nutshell is this:
You click a link in your browser on your computer under your desk
The browser creates an HTTP request and sends it to a server on the Internet
The server checks if he can handle the request
If the request is for a PHP page, the PHP interpreter is started
The PHP interpreter will run all PHP code in the page you requested
The PHP interpreter will NOT run any JS code, because it has no clue about it
The server will send the page assembled by the interpreter back to your browser
Your browser will render the page and show it to you
JavaScript is executed on your computer
In your case, PHP will write the JS code into the page, so it can be executed when the page is rendered in your browser. By that time, the PHP part in your JS snippet does no longer exist. It was executed on the server already. It created a variable $result that contained a SQL query string. You didn't use it, so when the page is send back to your browser, it's gone. Have a look at the sourcecode when the page is rendered in your browser. You will see that there is nothing at the position you put the PHP code.
The only way to do what you are looking to do is either:
do a redirect to a PHP script or
do an AJAX call to a PHP script
with the values you want to be insert into the database.
<script type="text/javascript">
var jvalue = 'this is javascript value';
<?php $abc = "<script>document.write(jvalue)</script>"?>
</script>
<?php echo 'php_'.$abc;?>
You seem to be confusing client-side and server side code. When the button is clicked you need to send (post, get) the variables to the server where the php can be executed. You can either submit the page or use an ajax call to submit just the data.
-don
PHP runs on the server. It outputs some text (usually). This is then parsed by the client.
During and after the parsing on the client, JavaScript runs. At this stage it is too late for the PHP script to do anything.
If you want to get anything back to PHP you need to make a new HTTP request and include the data in it (either in the query string (GET data) or message body (POST data).
You can do this by:
Setting location (GET only)
Submitting a form (with the FormElement.submit() method)
Using the XMLHttpRequest object (the technique commonly known as Ajax). Various libraries do some of the heavy lifting for you here, e.g. YUI or jQuery.
Which ever option you choose, the PHP is essentially the same. Read from $_GET or $_POST, run your database code, then return some data to the client.
I had the same problem a few weeks ago like yours; but I invented a brilliant solution for exchanging variables between PHP and JavaScript. It worked for me well:
Create a hidden form on a HTML page
Create a Textbox or Textarea in that hidden form
After all of your code written in the script, store the final value of your variable in that textbox
Use $_REQUEST['textbox name'] line in your PHP to gain access to value of your JavaScript variable.
I hope this trick works for you.
You can take all values like this:
$abc = "<script>document.getElementByID('yourid').value</script>";
You can do what you want, but not like that. What you need to do is make an AJAX request from JavaScript back to the server where a separate PHP script can do the database operation.

Passing a variable from one page to the next page

I am developing a Question & Answer website where a user is presented five puzzles on a page and the score is calculated using JavaScript as he attempts the questions on the page. The score is saved in a Javascript variable score. I have a paging system like this:
Now when the user clicks on 3 I want to send the variable score to the next page, where I have require scoreUpdateInDatabase.php on each such page such that the score of previous page is made permanent to the databse and the following PHP script presents him the next 5 questions.
How can I pass that score variable in secure way? I can't use GET because the user will modify it. I am satisfied with POST if this can be used, even though POST data can be modified but I just want minimal security.
P.S. Please do not suggest making AJAX call where in one side I will send score and while returning carries next 5 questions. I don't want to use AJAX to refresh content because it is not SEO friendly.
The simplest solution would be cookie based. Writing the value to a session cookie and the reading it.
You could use jquery cookie. It also gives you the option to require https if desired.
Save it in a session. POST would work equally well in this particular case but my preference would be storing it in the session.
The only secure way to do this is to pass the actual answers to the server using a POST or AJAX, do the calculation of the score also on server side and keep it in a SESSION variable.
More information on sessions in PHP
Try looking into Jquery - You should be able to return the value to the server scripting language (as you listed PHP as a tag, I assume you're using PHP). By using Jquery, you can get the javascript variable to the form BEFORE submitting the form to the next page.
Assuming you have used PHP to generate the form to submit initially rather than create the form in javascript. I would use Jquery - to get this file ( http://jquery.com/ ) and to include("jquery.js"); etc... in your PHP script for it to be used.
I would then convert the javascript variable(s) to a php variable and assign this to a hidden field in the form to be submitted to the next page using a $_POST[] variable.
However It will not be SEO friendly (POST and SESSION is not SEO friendly, but you should use them, continue reading)
We are talking of a game. No-one want that the Search engine index the last page of a game... because everyone can search on google (for example) for the last page of your game without playing.
You have to use ajax or post, but don't let google index every page of your game. It's nonsense.
Only the first page of your game should be indexed.

Passing variables from one page to another via url bar and risks involved

When passing a variable to another page via PHP I found that trying to find a solution to be above and beyond a pain as it is all over the place to find the relevant information regarding it such as how to send both single and multiple variables and how to select specific variables inside of a url and the security risks involved with url injections.
So far this is what I've managed to piece together.
Simple question:
Passing Variables from one page to another via URL-Bar
// PHP (Server side)
// To send it
header(Location: www.example.com?VariableId=$Var)
// To get it
$_GET["VariableId"]
// Sending multiple variables
header(Location: www.example.com?VariableId1=$Var1&VariableId2=$Var2)
// To get a variable in a multiple variable url it's the same method
// just specify a different variable
$_GET["VariableId1"]
$_GET["VariableId2"]
However I have had difficulty understanding how to do something similar to the PHP in javascript (Client side), how to get a specific variable from the URL to use on the page.
To redirect in javascript like in PHP see link as it's the best one I've found.
How to redirect to another webpage in JavaScript/jQuery?
I assume you can put ?VariableId=Blarg at the end of the links referenced in the link to make it work the same.
For security reasons I understand that it's unwise to use the url to send across variables as they can be used in ways unintended. I've done research on how do urlencode however came to no understanding and an explanation of how to use it (both encoding it and decoding it would be greatly appreciated) and is urlencode protection enough?
i think you have to study the POST and GET methods:
use the following tutorial:
http://www.tutorialspoint.com/php/php_get_post.htm
You may want to store variables in a cookie, you can do that easily in javascript with this plugin (for jQuery): http://plugins.jquery.com/cookie/
//To set a cookie
$.cookie('the_cookie', 'the_value');
//Create expiring cookie, 7 days from then:
$.cookie('the_cookie', 'the_value', { expires: 7 });
//Create expiring cookie, valid across entire page:
$.cookie('the_cookie', 'the_value', { expires: 7, path: '/' });
See examples here: http://www.jquerybyexample.net/2012/06/jquery-cookies-get-set-and-delete.html
If you want to redirect page with javascript just used simple code as:
<script>
function redirecturl(){
var url = "www.domain.com/yoururlstring";
window.location = url;
}
</script>
If you want to store data on the server without exposing it to the client (because they could tamper with it), then you can store it in a user's session on the server. Think about a session as a pool of data that stays on the server between requests from the user.
So a user makes request 1. Then makes request 2. If you set something into the session on request 1, then you can fetch it from the session on request 2. The server automatically manages the storage and retrival of the
http://www.php.net/manual/en/book.session.php
<?php
session_start();
if (!isset($_SESSION['count'])) {
$_SESSION['count'] = 0;
} else {
$_SESSION['count']++;
}
?>

Categories