How to resist anonymous user to access module internal files? eg. path starts from \Drupal\module\mymodule\files I have one file placed in my module. I want that only authenticated users or admin can access the content of this file. For anonymous users, it should be shown 'You don't have permission to access...'

Link is like &lt;a href = "' . $base_url . '/' . drupal_get_path('module', 'my_module') . '/files/myfile.xml" target="_blank"&gt;Sample File&lt;/a&gt;'

Right now issue is, even if i logged out, I am able to see the content of this link.

I tried this:

if(isset($user-&gt;roles[1])) {
        global $base_url;
        return $mylink;
      }


but above code is not working for me.

What is the best possible way to achieve this?
If I've understood your requirement correctly, you've some files other than normal Drupal files, like csv, txt which should not be accessible to Anonymous user.

This should be done at .htaccess level or you can give a try to private file system in Drupal Core. Check the ans given to "how to restrict file access to specific user roles" for more details on Private File system. The question is related to Drupal 7 because of which contributed modules will not be available for Drupal 8. But you can check configuration options mentioned for Drupal 8 Core.