Question
Client-Side vs Server-Side Programming Explained with PHP and JavaScript
Question
I have the following code:
<script type="text/javascript">
var foo = 'bar';
<?php
file_put_contents('foo.txt', ' + foo + ');
?>
var baz = <?php echo 42; ?>;
alert(baz);
</script>
Why does this code not write bar into foo.txt, but still alert 42?
More generally, how does client-side code differ from server-side code, and why can the server generate JavaScript values while JavaScript cannot directly change what the server already executed?
Short Answer
By the end of this page, you will understand the difference between client-side and server-side programming, especially in the context of JavaScript running in the browser and PHP running on the server. You will see why PHP runs first, why it can generate JavaScript code, why JavaScript variables are not automatically available to PHP, and how to correctly send data from the browser back to the server using requests such as form submissions or AJAX/fetch.
Concept
Client-side and server-side programming happen in different places and at different times.
- Server-side code runs on the web server before the page is sent to the browser.
- Client-side code runs in the user's browser after the browser receives the page.
In your example:
PHPis server-side.JavaScriptinside<script>tags is client-side.
When a browser requests a page:
- The request goes to the server.
- The server runs PHP.
- PHP generates output, usually HTML, CSS, or JavaScript.
- That output is sent to the browser.
- The browser then reads the result and runs JavaScript.
This explains both parts of the behavior:
<?php echo 42; ?>works because PHP runs on the server and prints42into the JavaScript code before the browser sees it.file_put_contents('foo.txt', ' + foo + ');does not use the JavaScript variablefoo, because PHP runs earlier and has no idea whatfoowill be in the browser.
So the key rule is:
- Server-side code can generate client-side code.
- Client-side code cannot directly access server-side variables or change server-side results that already happened.
Mental Model
Think of the server and browser like a restaurant kitchen and a customer table.
- The server is the kitchen.
- The browser is the table.
The kitchen prepares the dish and sends it out. Once the dish reaches the table, the customer can interact with it, but the customer cannot magically change what the kitchen already cooked without sending a new request.
In that analogy:
- PHP is the kitchen staff preparing the page.
- JavaScript is what happens at the table after the food arrives.
So:
- PHP can place
42into the page before it leaves the kitchen. - JavaScript variable
foo = 'bar'exists only after the page reaches the table. - If you want the kitchen to know about
bar, you must send a new order back.
That new order is a new HTTP request.
Syntax and Examples
A simple way to think about the syntax is:
Server-side output into client-side code
<?php $value = 42; ?>
<script>
const answer = <?php echo $value; ?>;
console.log(answer);
</script>
When the server processes this, the browser receives:
<script>
const answer = 42;
console.log(answer);
</script>
That works because PHP runs first and writes plain text into the response.
Client-side variables are not available to PHP directly
<script>
const foo = 'bar';
</script>
<?php
file_put_contents('foo.txt', foo);
?>
This does not work because foo is a JavaScript variable in the browser, not a PHP variable on the server.
Step by Step Execution
Consider this code:
<script>
var foo = 'bar';
var baz = <?php echo 42; ?>;
alert(baz);
</script>
What happens step by step
1. The browser requests the page
The browser sends an HTTP request to the server.
2. The server runs PHP
The server sees this part:
<?php echo 42; ?>
PHP executes it and outputs 42.
3. The browser receives the final result
The browser does not receive PHP code. It receives this:
<script>
var foo = 'bar';
var baz = 42;
alert(baz);
</script>
4. JavaScript runs in the browser
Real World Use Cases
Understanding this separation is essential in real applications.
Form submission
A user fills out a form in the browser.
- JavaScript may validate the form instantly.
- The server saves the data to a database after submission.
Login systems
- JavaScript can show or hide password errors on the page.
- The server checks credentials and creates sessions.
File uploads
- JavaScript can show upload progress.
- The server stores the file and validates its type.
Shopping carts
- JavaScript updates totals and quantities instantly.
- The server stores the official order and prices.
APIs and dashboards
- JavaScript fetches data and updates charts.
- The server queries the database and returns JSON.
Logging and analytics
- JavaScript captures browser events.
- The server receives them through an API and stores them.
Real Codebase Usage
In real projects, developers deliberately separate responsibilities between client and server.
Common server-side responsibilities
- reading and writing files
- database queries
- authentication and authorization
- secure validation
- generating HTML or JSON responses
Common client-side responsibilities
- handling clicks and form input
- updating the DOM
- showing validation messages
- calling APIs with
fetch() - managing UI state
Common patterns
Guard clauses on the server
Servers should validate incoming data before using it.
<?php
$data = json_decode(file_get_contents('php://input'), true);
if (!isset($data['foo'])) {
http_response_code(400);
echo 'Missing foo';
exit;
}
file_put_contents('foo.txt', $data['foo']);
Early return in client code
Avoid deeply nested logic when a value is missing.
Common Mistakes
1. Assuming PHP and JavaScript share the same variables
They do not.
Broken example:
<script>
let name = 'Alice';
</script>
<?php echo $name; ?>
Why it fails:
$nameis a PHP variable.nameis a JavaScript variable.- They exist in different runtimes.
2. Thinking embedded PHP runs after JavaScript because it appears later in the file
Code order in the source file does not change where it runs. PHP always runs on the server before the browser executes JavaScript.
3. Forgetting that the browser never executes PHP
The browser only receives the output of PHP, not the PHP code itself.
4. Trusting client-side validation alone
JavaScript checks can be bypassed. Always validate on the server too.
5. Trying to write files directly from browser JavaScript using server functions
Functions like file_put_contents() are server-side PHP functions. Browser JavaScript cannot call them directly.
6. Mixing strings from different languages incorrectly
Broken example:
Comparisons
| Concept | Server-Side | Client-Side |
|---|---|---|
| Where it runs | Web server | User's browser |
| Example languages | PHP, Python, Ruby, Java, Node.js | JavaScript |
| When it runs | Before response is sent | After page is received |
| Can access server files/database directly | Yes | No |
| Can manipulate the page UI directly | Not after delivery | Yes |
| Can read browser events like clicks | No, not directly | Yes |
| Can be viewed by the user | Usually no, only output is visible | Yes, browser receives it |
PHP output vs JavaScript execution
| Pattern |
|---|
Cheat Sheet
Quick rules
- PHP runs on the server.
- JavaScript in the page runs in the browser.
- PHP runs before the browser gets the page.
- JavaScript runs after the page is delivered.
- PHP can generate JavaScript code by printing output.
- JavaScript cannot directly use PHP functions unless it sends a new request.
Common pattern
PHP writes data into JavaScript
<script>
const id = <?php echo 123; ?>;
</script>
JavaScript sends data back to PHP
fetch('/save.php', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ value: 'bar' })
});
Important idea
This does not read a JavaScript variable in PHP:
<?php file_put_contents(, );
FAQ
Why does <?php echo 42; ?> work inside JavaScript?
Because PHP runs first and outputs plain text into the response before the browser executes the script.
Why can't PHP read my JavaScript variable?
Because the JavaScript variable exists only in the browser after the page has already been generated by the server.
How do I send a JavaScript value to PHP?
Use a new HTTP request, such as a form submission or fetch() POST request.
Can JavaScript write files on the server directly?
No. Browser JavaScript cannot directly access server files. It must send data to server-side code that performs the file operation.
Is JavaScript always client-side?
No. JavaScript can also run on the server with environments like Node.js. What matters is where the code runs.
If PHP and JavaScript are in the same file, are they sharing memory?
No. They may appear in one file, but they execute in separate runtimes and at different times.
Can the server know about a button click instantly?
Not by itself. The browser must send that information through a request or a persistent connection such as a WebSocket.
Mini Project
Description
Build a small page that lets a user type a message in the browser and save it into a text file on the server. This demonstrates the correct way to move data from client-side JavaScript to server-side PHP using a POST request.
Goal
Create a working browser-to-server flow where JavaScript sends user input and PHP writes it to a file.
Requirements
- Create an HTML page with a text input and a Save button.
- Use JavaScript
fetch()to send the input value to a PHP file. - In PHP, read the incoming JSON data.
- Validate that the message is not empty.
- Save the message to a text file and return a response.
Keep learning
Related questions
Are PDO Prepared Statements Enough to Prevent SQL Injection in PHP?
Learn how PDO prepared statements prevent SQL injection in PHP, what they protect, and the mistakes that still leave MySQL apps vulnerable.
Can You Bind an Array to an IN Clause in PHP PDO?
Learn how PDO handles placeholders in IN() clauses, why arrays cannot be bound directly, and the safe PHP pattern to build dynamic queries.
Choosing the Right MySQL Collation for PHP and UTF-8
Learn how MySQL character sets and collations work with PHP, and how to choose a practical UTF-8 setup for web applications.