# Optimize this path location script?

Example Script is located in /home/insp/public_html/deploy/

I want to return the /home/insp/ section

$path = realpath(__DIR__);$parts = explode('/', $path);$newPath = array(
$parts[0],$parts[1],
$parts[2], );$realPath = implode('/', $newPath);  Is there a better/more effeicent way to acheve this? • So you want the home directory of the user? – Bobby Dec 9 '13 at 21:09 • Yes @Bobby i did see that i could use a simple regex .*public_ – Clark T. Dec 9 '13 at 21:11 • What's stopping you from using $_SERVER['HOME'] or getenv('HOME')? – Bobby Dec 9 '13 at 21:12
• That isnt an env variable in cPanel closest i get is [DOCUMENT_ROOT] => /home/insp/public_html – Clark T. Dec 9 '13 at 21:16
• But if I read this documentation and this one correctly, you should be able to use <cpanel print="$homedir"> to get the home directory. – Bobby Dec 9 '13 at 21:24 ## 2 Answers A different way: preg_match(':^/[^/]*/[^/]*/:', realpath(__DIR__),$matches);
$realPath =$matches[0];


This matches the first and second files in path, and stores them in $matches. • I thought about that or doing '.*public_' to get /home/insp/public_ if that's the best way i'll go with it im just farming for opinions. or this (\/[a-zA-Z0-9]*.){3} the issue with the first is it will cause issues if tehre happens to be a folder called public_ anything – Clark T. Dec 9 '13 at 21:19 • Also your regex does not match anything regexr.com?37ir1 – Clark T. Dec 9 '13 at 21:29 • preg_match has a slightly different syntax; removing the colons will work on regexr.com :) – jerous Dec 9 '13 at 21:35 I've ended up going with this approach: preg_match('/(\/[a-zA-Z0-9]*){2}/', realpath(__DIR__),$homeDir);
$homeDir =$homeDir[0];


Reason being this is a much stricter regex and will only match valid cPanel usernames in paths which per their docs can only contain alphanumeric characters. This also prevents the need to expose this path to the public as was recommended by another person here.

• You should add some information on why you chose this alternative. As your answer stands at the moment, it does not indicate why this answer is good or recommended. – rolfl Dec 10 '13 at 14:46
• @rolfl you're right i've updated it now. – Clark T. Dec 10 '13 at 14:48