John Magnolia
John Magnolia

Reputation: 16823

regular expression which validates a relative URL

How would I validate a string to check that it is safe for a URL. No spaces or special characters in the filename which may break the URL in gmail.

E.g: data/Logo - free.png would be invalid

I would only like: "a-z", "0-9", ".", "-", "_"

There are hundreds of questions for validating URLs on here but they all seem to check if it contains "http" which I dont need.

UPDATE with working code (from @minitech):

// validate filename
if (preg_match('/[^\w.-]/', basename($logo))){
    $error = true
}

Upvotes: 0

Views: 3310

Answers (3)

Amir Mirmoeini
Amir Mirmoeini

Reputation: 123

I am not a big fan of regex so I fixed PHP's internal filter_var, it seems to have a problem with relative URL's. I use this workaround:

function isValid($url)
{
    if (parse_url($url, PHP_URL_SCHEME) != '') {
        // URL has http/https/...
        return !(filter_var($url, FILTER_VALIDATE_URL) === false);
    }else{
        // PHP filter_var does not support relative urls, so we simulate a full URL
        // Feel free to replace example.com with any other URL, it won't matter!
        return !(filter_var('http://www.example.com/'.ltrim($url,'/'), FILTER_VALIDATE_URL) === false);
    }
}

PS: Beware of the security problems in filter_var: https://d-mueller.de/blog/why-url-validation-with-filter_var-might-not-be-a-good-idea/

Upvotes: 4

Anirudha
Anirudha

Reputation: 32827

Use this regex to check for valid filename

 ^.*/[\w.-]+$

Upvotes: 0

Ry-
Ry-

Reputation: 225291

Just taking it right from what you listed:

$valid = !preg_match('/[^\w.-]/', $name);

You might consider just escaping it using urlencode, depending on the situation.

Upvotes: 1

Related Questions