In the generic case, there is no performant solution other than to check every file and folder that is publicly accessible, and then all the parent folders.
Since this is not a feasible or excusable operation to perform on every page load or request, you’re left with two other options:
- Define the location manually, which is not an unreasonable request
- Make assumptions and expectations about where WordPress can be found relative to your file
The latter is what you’ll be relying on if you want to automate things.
Issues I see with your code:
- It assumes that WordPress is either in the same folder or 2 folders up
If you’re okay with those assumptions, then yes, your code is safe to use
However I would recommend you roll your external script into WordPress as a plugin.