Your code is split into two entirely separate parts, the server side and the client side.
The example code executes like this:
Step 1, PHP executes all code between
<?php ?> tags. The result is this:
file_put_contents call did not result in anything, it just wrote " + foo + " into a file. The
<?php echo 42; ?> call resulted in the output "42", which is now in the spot where that code used to be.
alert call works, while the
foo variable is not used anywhere.
To call some PHP code, the client will have to send a new HTTP request to the server. This can happen using one of three possible methods:
- A link, which causes the browser to load a new page.
- A form submission, which submits data to the server and loads a new page.
Here's a question outlining these method in greater detail
window.location or submit a form, emulating possibilities 1. and 2.