0

I have searched for a solution to this problem and many answers I read said it is not possible.

I found this way and it worked. Let me know if it is a bad way of doing it.

<?php  echo '<script>                                        
 document.getElementById("displayLSValueThroughPHP").innerHTML = 
 JSON.parse(localStorage.getItem(\'localStorageValue\'))</script>';?></div>```
  • 3
    This is accessing it in the client, not the server. – Barmar May 28 '20 at 07:24
  • 1
    That code might do what you're looking to do, but it's not like PHP can actually grab the information and do something with it; it merely causes it to get printed onto the page. The bad thing about it is that the string contains no variables so there's no reason to use `echo` (or PHP code) in the first place. In the end you're just putting a small ` –  May 28 '20 at 07:24
  • The server is just generating the JavaScript that runs on the client, just like it does for any other HTML or JS. You can't access client data directly from server scripts. – Barmar May 28 '20 at 07:25
  • @ChrisG I suspect this is an oversimplification, and in the real code `localStorageValue` is in a PHP variable. – Barmar May 28 '20 at 07:26
  • This is client side access – Adesh Kumar May 28 '20 at 09:40
  • I have made it more clearer. Thank you for your input. – Bernard Sibanda May 28 '20 at 11:38
  • PHP and asp.net don't run on the front end, they run on the server only. JavaScript runs on the front end (i.e. browser) in a web application. JavaScript is the only language the browser knows how to execute. If you want to read the data on the server for some reason, then JavaScript must send that data to the server (normally by using an Ajax request). – ADyson May 28 '20 at 11:52
  • This will be useful background reading: [What is the difference between client-side and server-side programming?](https://stackoverflow.com/questions/13840429/what-is-the-difference-between-client-side-and-server-side-programming) – ADyson May 29 '20 at 08:24
  • "All PHP code is executed on the server before the client even starts executing any of the JavaScript", thanks ADyson – Bernard Sibanda May 30 '20 at 08:21

1 Answers1

1

front end vs back end

what do you mean server side scripting?

  • you can access cookies on server, because they are sent with every single request.
  • you can't access local storage on server, because it is accessible only in exact browser.

the only way it is possible is:

  1. dummy page with javascript
  2. execute javascript in the browser
  3. redirect including the data
  4. render content again using the local storage data server-side
<script>
    const localStorageValue = encodeURIComponent(localStorage.getItem('localStorageValue'))
    window.location = '/local-storage-data-back?localStorageValue=' + localStorageValue;
</script>

NOTE: for higher security use https and POST instead of GET parameters

Community
  • 1
  • 1
Michal Miky Jankovský
  • 3,089
  • 1
  • 35
  • 36