How can directories be protected using htaccess in PHP?

Directories can be protected using htaccess in PHP by creating an htaccess file within the directory you want to protect and specifying the necessary authentication directives. This can be done by setting up basic authentication using a username and password. This will prompt users to enter the specified credentials before being able to access the directory.

```php
// Create an .htaccess file in the directory you want to protect
// Add the following code to the .htaccess file to set up basic authentication

AuthType Basic
AuthName "Restricted Area"
AuthUserFile /path/to/.htpasswd
Require valid-user
```

Note: Replace `/path/to/.htpasswd` with the actual path to the `.htpasswd` file where the usernames and passwords are stored.