阻止目录访问并显示禁止的错误

In PHP and apache web server to prevent from listing and browser showing as i know we can use .htaccess

Deny from all

or using index.html file

<html>
<title>403 Forbidden</title>
<body>
Directory access forbidden!
</body>
</html>

which is better then both approaches? in security and speed access to show the error or there is another approach better then both approaches

You can use http_response_code() to dynamic set response header in PHP script.

For example:

<?php
$acl = [
    ['path' => '/folder/admin',  'allow' => 'admin'],
    ['path' => '/folder/public', 'allow' => 'guest'],
];

$_SESSION['user_type'] = 'guest';

if ( $_SESSION['user_type'] !== $acl[0]['allow'] ) {
    http_response_code(403);
    exit;
}