Question

Client-Side vs Server-Side Programming Explained with PHP and JavaScript

phpjavascriptclient-sideserver-side

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:

  • PHP is server-side.
  • JavaScript inside <script> tags is client-side.

When a browser requests a page:

  1. The request goes to the server.
  2. The server runs PHP.
  3. PHP generates output, usually HTML, CSS, or JavaScript.
  4. That output is sent to the browser.
  5. 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 prints 42 into the JavaScript code before the browser sees it.
  • file_put_contents('foo.txt', ' + foo + '); does not use the JavaScript variable foo, because PHP runs earlier and has no idea what foo will 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.

If browser code needs to send data to the server, it must make a new request.

Common ways to do that:

  • submitting a form
  • making an AJAX request
  • using fetch()
  • sending JSON to an API endpoint

This concept matters because almost every web application depends on this separation:

  • browsers handle UI, interaction, and immediate feedback
  • servers handle databases, authentication, file writing, and business logic

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 42 into 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.

Take Quiz

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.

Correct way: send browser data back to the server

Browser code

<script>
  const foo = 'bar';

  fetch('/save.php', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({ foo: foo })
  });
</script>

Server code (save.php)

<?php
$data = json_decode(file_get_contents('php://input'), true);
file_put_contents('foo.txt', $data['foo']);

This works because JavaScript sends foo to the server in a new request, and PHP reads it from that request.

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

Now the browser executes the script:

  • foo becomes 'bar'
  • baz becomes 42
  • alert(baz) shows 42

Now compare that with this PHP line from the original example:

<?php
file_put_contents('foo.txt', ' + foo + ');
?>

What PHP sees there

PHP runs before JavaScript. It does not evaluate JavaScript syntax. It simply treats ' + foo + ' as a PHP string literal.

So PHP writes the literal text:

 + foo + 

not the JavaScript value bar.

That is why the file does not contain the browser variable's value.

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.
Take Quiz

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.

function saveFoo(foo) {
  if (!foo) return;

  return fetch('/save.php', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ foo })
  });
}

Validation on both sides

Client validation improves user experience. Server validation protects correctness and security.

JSON as the data format

Modern apps often send JSON from browser to server and receive JSON back.

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:

  • $name is a PHP variable.
  • name is 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:

<script>
  var foo = 'bar';
  <?php file_put_contents('foo.txt', ' + foo + '); ?>
</script>

This writes the literal text ' + foo + ' because PHP does not evaluate JavaScript expressions.

7. Not sending a request when browser data must reach the server

To save user input, you need a request such as:

  • form POST
  • fetch()
  • AJAX
  • WebSocket message in apps that use sockets

Comparisons

ConceptServer-SideClient-Side
Where it runsWeb serverUser's browser
Example languagesPHP, Python, Ruby, Java, Node.jsJavaScript
When it runsBefore response is sentAfter page is received
Can access server files/database directlyYesNo
Can manipulate the page UI directlyNot after deliveryYes
Can read browser events like clicksNo, not directlyYes
Can be viewed by the userUsually no, only output is visibleYes, browser receives it

PHP output vs JavaScript execution

PatternWorks?Why
var x = <?php echo 42; ?>;YesPHP prints text into the JavaScript source
<?php file_put_contents('a.txt', foo); ?> where foo is JavaScriptNoPHP cannot access browser variables directly
JavaScript fetch() sending data to PHPYesIt creates a new request to the server

Related comparison: rendering vs requesting

  • Rendering: the server prepares the initial page
  • Requesting: the browser later sends data back to the server

That distinction is often the missing piece for beginners.

Take Quiz

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('foo.txt', ' + foo + '); ?>

It writes the literal string.

Safe mental rule

  • Server creates the page
  • Browser runs the page
  • Browser must send a request to talk back to the server

Edge case to remember

Even if both sides use the same language, they are still separate environments if one runs on the server and the other in the client.

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.

Take Quiz

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

  1. Create an HTML page with a text input and a Save button.
  2. Use JavaScript fetch() to send the input value to a PHP file.
  3. In PHP, read the incoming JSON data.
  4. Validate that the message is not empty.
  5. Save the message to a text file and return a response.
Take Quiz

Keep learning

Related questions

View more