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.
Related
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;
}
?>
I have a servlet which I call the following:
request.getSession().setAttribute("name", nameObj);
Can I access it from the following page using
console.log('IH HERE' + sessionStorage.getItem('name') );
It doesn't seem to work. Either js or jquery solution would be nice.
Thanks,
Scott
This won't work, for two reasons:
sessionStorage is client-side only; it's not sent to the server via HTTP requests and the server can't write it without talking to the client.
request.getSession() is server-side only, with a session ID stored in a cookie but nothing else stored in a client-accessible format.
You'll have to use cookies if you want to achieve this effect (read / write by both) or loop over the session and provide it all in the page somewhere (read only by client).
This is wat needs to happen:
I need to get user information out a MySql database.
But i don't want to insert the password of my database in the php file. Because that file won't be hosted on my own server. Nobody must see that password when they access the server by ftp and edit the php file.
My first solution that didn't work was opening a php file from my own host and reading the output (i made a script that connects to the database and outputs a long string) and converted the output to an array by splitting the values.
This did not work because of security reasons in php.
I can't create a extra account for my database that has read-only access because my host won't allow me. (hostinger.co.uk)
I also thought about using a iFrame and load the file on my host. And read it using javascript to read it. But again, security won't allow me to edit it.
Does someone know a way to fix this?
OPTION 1:
Since you want to make sure your buddies server doesn't have access to the MySQL server info (username, password, etc), your safest bet is to connect to the database from your server, and just communicate between the two servers what needs to be retrieved.
As Darren mentioned in the comments, an API would do this just fine. Since there are a lot of open source libraries out there that can get the job done, I will recommend you one: pheanstalk
pheanstalk is a php client that works on top of the beanstalk library, which is basically a queue.
You could set up a queue on each server, and configure the communication to happen between the 2 servers. Then you would have worker.php scripts running every second (or 10 seconds or however so often you like) looking for commands being sent from 1 server, taking those commands in, processing them, and sending back the information to the main computer.
OPTION 2:
Instead of accessing your database, you can create a copy of yours, and have his server contain a copy.
Key points of option 2:
If his server isn't capable of carrying a full fledged MySQL database, there is MySQLi, which is very similar, but the only difference is that it is basically a file that you keep in your server. That is the benefit since it is LIGHT (hence the "i" from MySQLi). The downside is that the database isn't as "powerful", some operations might be limited, though that is to be expected, but good none the less.
If your friend has a database however, then better yet since it will have all the capabilities.
Now since I am assuming you would need to keep their copy of your database up-to-date, you can create a function that would send a request to your buddies server on what was updated. This is an API since it is intercommunication between processes behind the scenes, but probably wouldn't need any root access as some other API's might require.
Though the hastle here is that you would literally have to call that function every time you do any updates... :(
Edited:
OPTION 3
After talking a bit with the OP in the comments, another possibility came up. In his particular case, he might be willing to have a file in a public directory available for his buddies user to read. For example, lets say his file was located in:
http://www.example.com/hiddenfiles/dfjios4wr238##.txt
To access what is inside that file, you would have to know the name (and the name was specifically designed to work as a password, hence even though the information isn't sensative for the OP's specific situation, it's always best practice to stay consistent and think safe xD).
To access the file, the following could be done:
$path = 'http://www.example.com/hiddenfiles/dfjios4wr238##.txt';
$fileHandle = fopen($path, "r");
while ($line = fgets($fileHandle))
{
echo "--> {$line}";
}
fclose();
i am newbie at developing web Application and like to learn best practices
i want to know what is the best practise to handle the cookie data should one use JavaScript or PHP to handle a cookie data?
1.Do you use javascript to get cookie and than pass it to PHP to do all the filtering ?
2.Do you use PHP to do all of the stuff?
3.Which one of the above will improve performance or is there another way?
should one use JavaScript or PHP to handle a cookie data?
To make this a little more general, let's call this "Client side" (which is almost exclusively JavaScript) and "Server side" (which can be PHP, JavaScript or any other language) code.
The short answer is that: It depends what you are doing with the cookie data.
Most of the time, dealing with cookies server side is simpler.
Sometimes, the information in the cookie needs to be secure, and you don't need to access it from client side code, so you'll set an http only flag on it so that if you suffer an XSS attack the damage is limited.
Sometimes you will want to avoid making a server round trip (to take a trivial example: You allow the user to pick different stylesheets for your website. You don't want to reload the entire page when their change their preference. You use client side code to change the stylesheet currently loaded, and client side code to store that preference in a cookie. In the future, when other pages are loaded, you can use server side code to set a different <link> element.)
Do you use javascript to get cookie and than pass it to PHP to do all the filtering ?
You might use client side code to set a cookie value, and then use server side code to read it. There is no point in using JavaScript to read it and then using some non-cookie based mechanism to send it to server side code. That just makes things complicated and more likely to go wrong.
Do you use PHP to do all of the stuff?
Only if all the stuff is better done with PHP
Which one of the above will improve performance or is there another way?
As is normal with questions of client side code vs server side code: If you aren't loading a new page anyway, then using client side code is usually faster.
It depends on the type of application.
If your application is full request based with PHP as backend, then use can PHP tot extract cookies.
check this link http://www.w3schools.com/php/php_cookies.asp
Or, if you application follows REST architecture or you want send data to the backend using Ajax. Then use javascript/Jquery to get cookie value and send it to the backend server that is PHP or in any other language.
Check this link to know, how to access cookies using jquey.cookie.js plugin:
https://github.com/carhartl/jquery-cookie
In handling cookies, it does not really matter whether you use javascript or PHP, it just depends on when it is more beneficial to access/manipulate them. Server-side stuff always seems more secure, but cookies are always accessible, client or server-side, so it doesn't really matter. You can create a cookie in PHP like this:
setcookie($cookieName, $cookieValue, time() + 3600);
That sets a cookie for an hour, you can then access it through the $_COOKIE superglobal array with array notation, for example
$var = $_COOKIE[$cookieName];
However, keep in mind that this won't work if cookies aren't enabled in the browser, such as when someone uses incognito mode.
In javascript, you can set cookies like this:
document.cookie="cookiename=cookievalue";
However, cookies in javascript are all concatenated as one big string in document.cookie, so the way to break them up into a normal array is with the split function, for example:
var arr = [];
function getCookieArray() {
var value = "; " + document.cookie;
var parts = value.split("; " + name + "=");
if (parts.length == 2) return parts.pop().split(";").shift();
}
You can find more about that here http://www.w3schools.com/js/js_cookies.asp
So, remember, that cookies are not for storing sensitive data. They're often used to store preferences, but never anything that people shouldn't be able to have access to.
Did not have luck with these examples:
Javascript File remove
Javascript FSO DeleteFile Method
Deleting a File
There are no special permissions on the file.
Is there a way to do this in JQuery?
The requirement is - a certain file must be deleted from the web directory when another page is loaded. There is no security issue as this is on a closed network.
Any help is appreciated.
Thanks.
With pure JavaScript, it can't be done. Using an AJAX call to a server side script that deletes the file would work though.
Javascript cannot delete files, it is prevented as it would lead to HUGE security vulnerabilities. THose links are for ActiveX controls that are handled through JS. Use a server side language.
You can't delete files over HTTP (well in theory you can, but it's not implemented.)
The easiest way is to set up a tiny server side script (e.g. in ASP or PHP) and to call that from JavaScript. The server side script needs the proper permissions to do the deletion, but otherwise there is no problem.
In PHP the start would look like this: (Not expanding solution to a fully secure one because you're not saying what platform you are on)
<?
// STILL INSECURE!!!!
// Do not use in any public place without authentication.
// Allows deletion of any file within /my/files
// Usage: filename.php?file=filename
$basedir = "/my/files";
$file_to_delete = $_REQUEST["file"];
$path = realpath($basedir."/".$file_to_delete);
if (substr($path, 0, strlen($basedir)) != $basedir)
die ("Access denied");
unlink($path);
?>
you would call the script like this:
http://yourserver/directory/delete_file.php?file=directory/filename
You cannot delete a file on a remote server using only JavaScript running in a visitor's browser. This must be done with a server-side script.
If you are doing this in a RESTFUL way, you would send an HTTP DELETE request.
jQuery's ajax method states that you can use the method parameter to specify 'DELETE' but notes that some browsers may not support it.
Obviously you will need a webserver which will accept a DELETE request, and apply some sort of authentication/authorization so that joe random visitor can't delete your files. I believe Apache's mod_dav will get you started here.
Javascript is a client side language. So you are not able to delete file on server directly. All examples that you provide may be used only for deleting files on your local machine but not into server.
But you may call some server page function that will delete file.
You can't delete files with JavaScript as it is run locally. So, it doesn't even touch external files.
You need to use a server side language that has access to editing the files such as PHP, RoR, or ASP.
You can however use jQuery to call the server side code via AJAX such as $.get or $.post and then the server side code deletes it and it would seem as though JS is deleting the files.