Reputation: 431
Can I get data from localstorage using php if yes then tell me how in localstorage data set like this
<script>
var i=0;
function inc()
{
i+=1;
localStorage.setItem("qnum", i);
}
</script>
Upvotes: 2
Views: 15377
Reputation: 91
$Data = "<script>document.write(localStorage.getItem('key'));</script>";
PHP can not handle||add logic with $Data. I think you need to try to use cookie (**trick: if you want to smooth/storage data, try to use localStorage to sync data with cookie)
I try to add some feature with that code (foreach then call item in data), but it not correct. Because we print_r($Data) it will show content of localStorage, but it just show when you open browser. Before browser load, the value of $Data just string (don't have value in localStorage)
so, I still you localStorage in javascript, but I have a function to sync localStorage to cookie for PHP can read value
function sync_cookie() {
let cart = localStorage.getItem("key);
if (!cart) { return; }
cart = JSON.parse(cart); let cart_cookie = [];
cart.forEach(function (item) {
cart_cookie.push(item.id) })
setCookie("key", JSON.stringify(cart_cookie)) }
Upvotes: 0
Reputation: 3718
No, you can't. PHP runs on your server, the localStorage
is only available in the browser of the client.
The only way is to read the localStorage
via JavaScript, and send the result to your server via ajax.
Upvotes: 12
Reputation: 363
I tried with this code and it worked fine.
$Data = "<script>document.write(localStorage.getItem('key'));</script>";
print_r($Data);
Upvotes: 11
Reputation: 2766
Another explanation goes like this: Your browser does not understand php, only javascript (along with html & css). Therefore, you need to read and set LocalStorage with Javascript and send it to a server, like Markus says.
Upvotes: 0
Reputation: 10096
localStorage
is something that is kept on the client side. There is no data transmitted to the server side.
You can only get the data with JavaScript and you could sent it to the server side with Ajax.
Upvotes: 0