benphelps Posted January 21, 2009 Share Posted January 21, 2009 I have a function that can validate a URL like this: "http://www.example.com" and all the variations. I cant figure out how to validate aFull URL like this: http://www.newegg.com/Product/Product.aspx?Item=N82E16819115044 How can I validate that URL ? Here is what I have now: function is_valid_url($url) { $pattern = "#^(http:\/\/|https:\/\/|www\.)(([A-Z0-9][A-Z0-9_-]*)(\.[A-Z0-9][A-Z0-9_-]*)+)(\d+))?(\/)*$#i"; if (!preg_match($pattern, $url)) { return false; } else { return true; } } Link to comment https://forums.phpfreaks.com/topic/141859-validate-full-url/ Share on other sites More sharing options...
flyhoney Posted January 21, 2009 Share Posted January 21, 2009 You could ping the url Uses more resources however. Here is a class I wrote to check the status of a url: <?php $url = new UrlInfo('http://www.google.com/intl/en_ALL/images/logo.gif'); if ($url->getStatus() == 200) { echo "url is valid"; } else { echo "url returned a status: " . $url->getStatus(); } ?> <?php class UrlInfo { private $url; private $headers; private $status; public function __construct($url = '') { $this->url = $url; // fetch headers for url if ($this->url) { $this->headers = @get_headers($this->url, 1); if (!$this->headers) { $this->headers = array(); } else { $this->getStatus(); } } } public function getUrl() { return $this->url; } public function getHeaders() { return $this->headers; } public function getHeader($key) { if (isset($this->headers[$key])) { return $this->headers[$key]; } else { return ''; } } public function getStatus() { if (!$this->status) { // status looks something like this HTTP/1.0 200 OK $status = trim(end(explode(' ', $this->headers[0], 2))); switch ($status) { // a successful response from the server case '200 OK': $this->status = 200; break; // permanent redirection case '301 Moved permanently': $this->status = 301; break; // common way of performing a redirection case '302 Found': $this->status = 302; break; // redirection case '303 See Other': $this->status = 303; break; // server doesn't grant access to what was requested case '403 Forbidden': $this->status = 403; break; // server could not find what was requested case '404 Not Found': default: $this->status = 404; } } return $this->status; } } ?> Link to comment https://forums.phpfreaks.com/topic/141859-validate-full-url/#findComment-742753 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.