5

In D7, how do I check whether a page exists by page alias? I've found some guy asking the same very question but I have problems with using menu_valid_path() (or drupal_valid_path() in D7) function. It always returns TRUE, no matter how weird a path I pass to it. Here is a sample code:

if(drupal_valid_path($GLOBALS['base_url'] . '/contacts')) //this exists
{
    print_r('Exists!');
}
if(drupal_valid_path($GLOBALS['base_url'] . '/weird_alias')) //this doesn't exist
{
    print_r('Exists!');
}

I get two "exists" despite the fact that /weird_alias page doesn't exist and returns a "page not found" error. I'm extremely reluctant to use drupal_http_request() because there are a lot of unnecessary things like headers, timeouts etc. Shouldn't there be an easier way to check internal paths?

2 Answers 2

7

If you look at the code for drupal_valid_path() it passes the alias through url_is_external(), which considers paths with a http:// prefix to be external. The function defaults to allow access to these sorts of paths and simply returns that fact; it does not check whether the 'external' url exists.

Since you're adding $GLOBALS['base_url'] to the alias it will appear to be external; you just need to pass the alias into the function without the base URL attached:

if(drupal_valid_path('weird_alias')) {
  // This code is never run
  print_r('Exists!');

}
2
  • Oh. :-) I've been stupid. Didn't even think of the fact it should be without 'http'. Thanks.
    – Ari Linn
    Commented Apr 16, 2012 at 21:49
  • There is also an issue with whether the path is an alias or not. If the path is an alias, drupal_lookup_path('source','$path) might be needed to get a valid result. See this post: [eureka.ykyuen.info/2013/03/05/drupal-7-check-if-a-path-exists/] Commented Aug 29, 2013 at 22:45
2

Just try this

if(drupal_valid_path('contacts') == 1) //this exists
{
    print_r('Exists!');
}
if(drupal_valid_path('weird_alias') == 1) //this doesn't exist
{
    print_r('Exists!');
}
1
  • Tnx. Most unfortunately I can't tag 2 answers as 'Answered' so I had to choose the one above because it came earlier. But your answer is valuable too. :-)
    – Ari Linn
    Commented Apr 16, 2012 at 21:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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