How to Pass a PHP Variable to JavaScript – Easy Way

For something seemingly so straight-forward, you would think that the information out there would be a bit better on this subject. Passing a variable from PHP to JavaScript is actually very easy! There are just a couple things you need to keep in mind and some ways to do it to ensure it actually works.

I find that putting the following code into the <head> section of my website is the most foolproof method:

That’s it! You just define the PHP variable first, then echo it into a basic JS variable declaration statement. I know there are lots of ways to define a JavaScript variable, but this is the one I find works in the most circumstances. I’m not an expert here, but most of the others seem to not work a lot of the time.

A few things to keep in mind for this:

1. The PHP variable needs to be defined before the JS one.
2. The JS variable needs to be defined before you actually use it anywhere. This seems obvious, but if you forget this fact and try to put this declaration into the footer of your site and then use it in the content, you’ll find it doesn’t work! That’s why I like to put this in the head section of my website. Or, if you were in WordPress or another CMS, make sure to place it in the header.php file of your active theme.

Additionally, you should be aware that if your variable is not a string and is instead a number, you would want to define it without the quotes around it, i.e.:

Note that as Sherri mentioned in the comments, if you have more complicated strings or any strings with quotes (“) in them, this will break. You’ll want to look into json encoding if needed. But for simple strings and variables, this should do the trick.

Hard to go wrong with any of this. There are of course more complicated ways to use this, but I’m not going to go into any of those here. Let me know if you have any problems!

About Brian Johnson

Brian Johnson is a website developer and designer living in Minneapolis, Minnesota with a passion for code and WordPress. He spends his days building WordPress websites for small businesses, developing new code with the online community, and living life.

12 Comments on “How to Pass a PHP Variable to JavaScript – Easy Way”

  1. The scenario:

    1. There is a php script which (possibly complemented by a direct written HTML code) consrtucts a HTML page via its echo command, based on whatever algoritmus eventually based on supplementary data from server files or databases.

    2. This php script leads to data being saved into string variable(s), which (possibly) can contain arbitrary characters, including control codes (newline, tab…), HTML special characters (&,<…) and non-ASCII (international) characters.

    3. These non-ASCII characters are UTF-8 encoded, as well as the HTML page (I do highly recommend) *)

    4. The values of these PHP string variables have to be transferred into javascript variables for further processing by javascript (or exposing these values in HTML directly)

    The problem:

    it is not safe to PHP-echo such variables into HTML (javascript) directly, because some of characters possily contained in them cause malfunction of the HTML. These strings need some encoding/escaping in order to become strings of non-conflicting characters

    The solution

    There may be a big lot of ways of this encoding. The following one seems to me the easiest one:
    The PHP variable with unpredictable value can originate from some file, as an example (or from user input as well):

    $variable=file_get_content(…)

    1. Convert all bytes of that string into hex values and prepend all hex-digit-pairs with %

    $variable_e=preg_replace("/(..)/","%$1",bin2hex($variable))

    The new variable is now guarantied to contain only %1234567890abcdefABCDEF chracters (e.g. %61%63%0a…) and can safely be directly echoed into HTML:

    var variable="” //that’s NOT all folks

    But now the value is still encoded. To get the original value of the variable, it has te be decoded: *)

    var variable=decodeURIComponent(“”)

    The value of the variable is now the same as the original value.

    *) I have no idea about non-UTF-8 encoded pages/data, espetially how the decodeURIComponent works in such a case, because i have no reason to use other encodings and handle them as highly deprecatad.

    WARNING: this approach is not (generally) safe against code injection. I highly recommend some further check (parsing) of the value depending on the particular case.

    P.S. For very large amount of data, I would recomment to save them into file on the PHP side (file_put_content) and read them by javascript via HTTP Request.

    I use this approach as it needs one line of code on server as well as client side. I do agree with arguement that not all chaeacters have to be encoded.

    Do not enjoy my possibly stupid solution, if you have a better idea

    murphy

  2. The scenario:

    1. There is a php script which (possibly complemented by a direct written HTML code) consrtucts a HTML page via its echo command, based on whatever algoritmus eventually based on supplementary data from server files or databases.

    2. This php script leads to data being saved into string variable(s), which (possibly) can contain arbitrary characters, including control codes (newline, tab…), HTML special characters (&,<…) and non-ASCII (international) characters.

    3. These non-ASCII characters are UTF-8 encoded, as well as the HTML page (I do highly recommend) *)

    4. The values of these PHP string variables have to be transferred into javascript variables for further processing by javascript (or exposing these values in HTML directly)

    The problem:

    it is not safe to PHP-echo such variables into HTML (javascript) directly, because some of characters possily contained in them cause malfunction of the HTML. These strings need some encoding/escaping in order to become strings of non-conflicting characters

    The solution

    There may be a big lot of ways of this encoding. The following one seems to me the easiest one:
    The PHP variable with unpredictable value can originate from some file, as an example (or from user input as well):

    $variable=file_get_content(…)

    1. Convert all bytes of that string into hex values and prepend all hex-digit-pairs with %

    $variable_e=preg_replace("/(..)/","%$1",bin2hex($variable))

    The new variable is now guarantied to contain only %1234567890abcdefABCDEF chracters (e.g. %61%63%0a…) and can safely be directly echoed into HTML:

    var variable="” //that’s NOT all folks

    But now the value is still encoded. To get the original value of the variable, it has te be decoded: *)

    var variable=decodeURIComponent(“”)

    The value of the variable is now the same as the original value.

    *) I have no idea about non-UTF-8 encoded pages/data, espetially how the decodeURIComponent works in such a case, because i have no reason to use other encodings and handle them as highly deprecatad.

    WARNING: this approach is not (generally) safe against code injection. I highly recommend some further check (parsing) of the value depending on the particular case.

    P.S. For very large amount of data, I would recomment to save them into file on the PHP side (file_put_content) and read them by javascript via HTTP Request.

    I use this approach as it needs one line of code on server as well as client side. I do agree with arguement that not all chaeacters have to be encoded.

    Do not enjoy my possibly stupid solution, if you have a better idea

    murphy

  3. And remember, that whatever variables you add to your javascript, will be visible when anyone uses their browser to view the code in the page.

  4. First, thanks for a great write up. I’m hoping you can offer me a simple solution here. I have to say first that I’m dealing with an ordinary http: page, and I absolutely want to avoid setting up my .htacess file to allow PHP parsing of HTML files (among many reasons, it cases some old browsers to attempt to download rather than display the page!). My page is for my own music, and I use php calls withing HTTP requests to allow visitors to download songs, for example like click here. Things like this work fine (In this case The PHP will find the file and initiate a download ). Now the only thing missing is that I need to be able to retrieve a simple value from the PHP call. For example if I’m checking the authorization of the visitor based on some passed cookie. Since the page itself is .html and not .PHP, the page is not going to be redisplayed, and so an ‘echo’ probably won’t work. Best thing i can think of is having the php write the results I want into a temporary file (on thye server side of course) which I could then read with a javascript XMLHttpRequest(), run within a page wide javascript intervalTimer. This sounds like an awkward rupe goldber approach though. And to make matters worse (maybe) I’m committed to learning to do things in pure PHP and javascript, without loading in jquery, ajax, or other helper libraries.

    1. Why exactly are you using .html pages instead of .php? It seems like it would solve all of your problems just to fix that. And it’s not hard at all to do… Just rename them “.php” and add “” to the beginning of the document and “” to the end and voila! You’re done. PHP and html work perfectly together. At that point you could add whatever PHP you want to the page, just remember to start each php line with ““.

      Easy!

  5. Actually that’s exactly what Sherri was talking about.

    Here is the trick :

    In my php file, I put this

    https://codeshare.io/507Dyn

    (My code is on an external website cause I can’t write code here. It gonna expire in 24h… so please modify my reply with the code in it.

    And now there is a variable called js_variable that I can use in any javascript.

    Thank you all.

    1. PHP is server-side and happens before the page is rendered, so no. But you could pass the JS variable as a URL parameter or something and go to a new page or refresh the current page to get it.

  6. Stumbled on this while looking for a package to convert php vars to js.

    No clue how old this article is…but. Please don’t follow this recommendation. The second your string contains a double quote, it will break. If you want to use other types you have a world of headaches.

    A better method is to json_encode the value before giving it to the js.

    1. That may be true, but for my purposes (and likely the purposes of most of the people here), we don’t need to worry about quotes being in our variables. Generally I’m just doing something quick and easy and don’t want to go through the trouble of encoding and doing other complicated things that really aren’t necessary for what I’m doing.

      1. Hello,

        I try to pass something like $array[‘info1’][‘info2’].

        But it doesn’t work, my var contain a string.

        Here is what I put in my js script :

        var data = “”;

        My php script is called in the top of the page and the javascript on the bottom.

        Maybe it’s linked about what Sherri was talking about. I don’t really know. I’m not good at all at javascript.

        Thanks !

Leave a Reply

Your email address will not be published.