r/PHPhelp • • Sep 26 '26

Assets from protected dir

Hey everyone,

I have made a website that has a members area. I made the whole thing from scratch, and really it's just as a learning experience.

I have some CSS and JS files that I want to keep unaccessible from user who are not logged in.

Is there a way I can put them in a protect directory using .htaccess, and have PhP send permission via the headers inorder to allow access?

4 Upvotes

19 comments sorted by

5

u/VRStocks31 Sep 26 '26

You can block them via htaccess and then you can create a php script that checks if the member is logged in and in that case reads the css or js and outputs css/js headers and the content of those files. Something like that. It’s something convoluted though, usually websites are not structured this way and nothing sensible should be added inside a js or css

4

u/thejester1324 Sep 26 '26

roughly what abrahamguo said, in code. put the css/js in a folder outside the web root and point the member pages at this:

<?php
session_start();
if (empty($_SESSION['user_id'])) {
    http_response_code(403);
    exit;
}

$name = basename($_GET['f'] ?? '');
$path = __DIR__ . '/../private-assets/' . $name;
$types = ['css' => 'text/css', 'js' => 'text/javascript'];
$ext = pathinfo($name, PATHINFO_EXTENSION);
if (!isset($types[$ext]) || !is_file($path)) {
    http_response_code(404);
    exit;
}

header('Content-Type: ' . $types[$ext]);
header('Cache-Control: private, max-age=3600');
readfile($path);

then <link rel="stylesheet" href="/asset.php?f=members.css"> on the page. basename() is the line that matters, without it ?f=../../something walks straight out of that folder. swap user_id for whatever your login actually sets

1

u/Ducking_eh Sep 28 '26

I did something like this, but it drastically slowed down the website.

I am hoping to find a better way tomdo it.

2

u/colshrapnel Sep 28 '26

The better way is obviously to drop that whim completely and move on. Or at least to provide some explanation, since your case looks exactly like an XY problem. Which basically means you will always get wrong answers for the wrong question, wasting everyone's time, your confident self included

1

u/Ducking_eh Sep 28 '26

As I mentioned in the OP, I am doing this to learn and challenge myself. Not trying to waste anyone's time; just get better at coding.

@thejester1324 made a suggestion that I would have never thought of. And it gave me better insight into how PHP works.

1

u/colshrapnel Sep 28 '26

Even challenges have to be sensible. For a such a groundless whilm you will always get questionable suggestions, just like one you just got, that cripples the sessions' functionality. And the moment you will have to write something onto a session, this suggestion will backfire. At least it should have been suggested in the form of calling session_write_close() after session_start() - in some specific files, as opposed to having different calls to session_start() for different files.

I know different people learn differently. But still, there are better ways, and it does no harm to learn how to challenge yourself better.

1

u/Ducking_eh Sep 28 '26

Great input.

If you look at the original question, I was actually trying to learn how php and .htaccess can work together. Mainly, I was wondering if I can get the benefits of locking entire directory with basic auth via .htaccess, and still have a nice html/php login.

There are some trivial reasons I want to block css and JS. But mainly, I wanted to figure out that whole relationship.

In hindsight,.I could have been more clear about that in my op

1

u/colshrapnel Sep 28 '26

Well it's possible with just basic JS. Like just a few lines in the body of your PHP script which will load all assets from the basic auth-protected dir. The problem is, this "protection" is as silly as one I suggested below - your php will have to send login and password to JS, so they will be discovered by any curious person.

Your main outcome should be that PHP has very little control over what a browser will send with request. So "have PhP send permission via the headers" won't work, because PHP sends to the browser, while any protection happens on the server side. At the same time, JS can send any headers with its async requests so it's a better candidate. But there is a caveat: apache is static. it can protect your files using a hardcoded login and password pair, but cannot serve temporary tokens which all modern protection is based on. For that, PHP is inevitable. A more plausible case similar to yours is protected user file access. But such files are usually being donwloaded one by one, so there is no problem with simultaneous blocked requests

1

u/thejester1324 Sep 28 '26

that's probably the session lock, not the file serving. php's default file sessions lock for the whole request, so every asset.php hit waits for the page and the other assets to finish, one at a time. swap the first line of the asset script for

session_start(['read_and_close' => true]);

it reads the session and drops the lock right away. and in your page scripts call session_write_close() as soon as you're done writing to $_SESSION. tested it here with two concurrent asset requests: the second one waited 1.3s with a plain session_start and 0.04s with read_and_close.

1

u/Ducking_eh Sep 28 '26

very cool! I didn't know this. I did it in my code, and it cut my loading time in half.

It was taking about 30 seconds to load before. Now that I added your suggestion, it loads in about 11-15 seconds. I know that is still kind of long. But that is mostly because I have other things slowing it down.

If I load the CSS and JS directly using their URL and no loader, the whole thing loads in about 6 seconds.

1

u/thejester1324 Sep 28 '26

nice. the gap between 11-15s and 6s is still the loader, so two things to check. first, make sure asset.php doesn't include your app bootstrap (db connection, config, autoloader), it should only need the session and the file. second, let the browser reuse what it already has instead of re-downloading every time. send an etag and answer 304 when it matches:

$mtime = filemtime($path);
$etag  = '"' . md5($mtime . filesize($path)) . '"';
header('Cache-Control: private, max-age=86400');
header('ETag: ' . $etag);
if (($_SERVER['HTTP_IF_NONE_MATCH'] ?? '') === $etag) {
    http_response_code(304);
    exit;
}

put that before the readfile(). tested it here: first request 200, the repeat comes back 304 with an empty body.

4

u/danabrey Sep 27 '26

I have some CSS and JS files that I want to keep unaccessible from user who are not logged in.

Why?

2

u/PetahNZ Sep 26 '26

Search for X-SendFile, it's a header you can use to instruct Apache to send the file. 

1

u/r-spriebsch Oct 03 '26

Look for x-sendfile or x-accel-redirect header depending on which web server you use.

-1

u/abrahamguo Sep 26 '26

Using both htaccess and PHP sounds more difficult than necessary, because you're mixing two tools to do one job.

I'd recommend simply storing the CSS and JS files in a directory that's already not automatically served by your web server, and then building a PHP endpoint that reads and serves the file after performing the necessary permissions checks.

-1

u/colshrapnel Sep 27 '26

There is an Apache-only solution, although as silly as the request itself. Since we don't really care, we can just pretend that files are protected with such a simple rule

RewriteCond %{HTTP:Cookie} !(^|;\s*)auth=true(;|$)
RewriteRule ^assets/ - [R=403,L]

and then in php,

setcookie('auth', 'true');

on login, and

setcookie('auth', '', time() - 3600);

on logout

This answers directly to your request: we are instructing the browser to send a specific HTTP header (well to add a specific part to a specific header to be strict) named Cookie, which said browser will happily send back with every request. The rest is just a simple rewrite rule. You don't even have to make /assets/ protected.

Obviously, I won't recommend this approach for any file that requires more protection than a css stylesheet.

0

u/TheTreasuryPetra Sep 27 '26

Amazing that we still get these kind of confident suggestions.

Please don't use cookies for security like this, any user can set this cookie themselves.

1

u/colshrapnel Sep 28 '26 edited Sep 28 '26

Amazing that we still get these kind of confident comments. Did you even read the comment above? The question? WTF is that "security" you are talking about here?