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(

        $realPath = implode('/', $newPath);

Is there a better/more effeicent way to acheve this?

  • \$\begingroup\$ So you want the home directory of the user? \$\endgroup\$ – Bobby Dec 9 '13 at 21:09
  • \$\begingroup\$ Yes @Bobby i did see that i could use a simple regex .*public_ \$\endgroup\$ – Clark T. Dec 9 '13 at 21:11
  • \$\begingroup\$ What's stopping you from using $_SERVER['HOME'] or getenv('HOME')? \$\endgroup\$ – Bobby Dec 9 '13 at 21:12
  • \$\begingroup\$ That isnt an env variable in cPanel closest i get is [DOCUMENT_ROOT] => /home/insp/public_html \$\endgroup\$ – Clark T. Dec 9 '13 at 21:16
  • \$\begingroup\$ But if I read this documentation and this one correctly, you should be able to use <cpanel print="$homedir"> to get the home directory. \$\endgroup\$ – Bobby Dec 9 '13 at 21:24

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.

  • \$\begingroup\$ 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 \$\endgroup\$ – Clark T. Dec 9 '13 at 21:19
  • \$\begingroup\$ Also your regex does not match anything regexr.com?37ir1 \$\endgroup\$ – Clark T. Dec 9 '13 at 21:29
  • \$\begingroup\$ preg_match has a slightly different syntax; removing the colons will work on regexr.com :) \$\endgroup\$ – 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.

  • \$\begingroup\$ 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. \$\endgroup\$ – rolfl Dec 10 '13 at 14:46
  • \$\begingroup\$ @rolfl you're right i've updated it now. \$\endgroup\$ – Clark T. Dec 10 '13 at 14:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.