1

I'd like to send headers with PHP, inside of a javascript condition. Is that possible?

if ($('body').hasClass('browserChrome')) {
    <?php
       header("Content-Type: application/x-chrome-extension");
       header('Content-Disposition: attachment; filename="http://example.com/file.crx"');
       header("Pragma: no-cache");
       header("Expires: 0");
    ?>
}

4 Answers 4

3

That won't work. First, your web server will execute the PHP script, resulting in an HTML page with JavaScript. That is then sent to the user's web client, which will display the HTML and execute the JavaScript. There is no trace of the PHP code by the time the JavaScript interpreter gets to it.

Sign up to request clarification or add additional context in comments.

Comments

2

No, it is not possible. (Well, more like, it's not meaningful or useful, and will likely cause page errors.)

The php code runs on your server before the page is sent out, like a baby in a stork bill, on its way to the client browser. The stork flies for a long time, through good weather and bad, storms, ice, snow, hunting parties, and pollution. At long last, the stork reaches your customer as they wait patiently for their new baby web page to appear.

Then, suddenly, -~ p00f ~- and the page arrives. At this point, the JavaScript in the page runs.

Comments

2

if you need send some headers from JS(only), you can use method setRequestHeader of object XMLHttpRequest

new XMLHttpRequest(); 
//or 
new ActiveXObject(...) for IE
...
xmlHttp.open(... 
xmlHttp.setRequestHeader("Cache-Control", "no-cache, must-revalidate");  
xmlHttp.setRequestHeader("Pragma", "no-cache"); 

or can use some method JS frameworks (jQuery, Prototype, etc,)

But as has already been answered, is not correct write php code in js

Comments

1

It seems as if you are trying to download a file through javascript, more like, push the file to the client browser. However, as it has been answered, its not possible for the code to work, as it happens on the server, and js runs on the client.

To achieve that, you would need to use javascript itself, ajax in this case, to download the relevant content.

You may find how to download file from javascript here : http://www.codeproject.com/KB/scripting/FileDownloadUsingJScript.aspx

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.