Actually php is server side scripting language (that runs at server) and javascript is basically client side programming language (which runs in the browser) so you can’t set a php variable from javascript. Look at these tutorials php and javascript.
But using ajax (javascript) you can pass javascript variables to php and can use them in the to the php script. Here is ajax tutorial link.
1
solved Set PHP variable value from a Javascript Variable value without refresh [duplicate]