I have an auto site and I am having a feature called SAVE SEARCH, which saves the search a user has made on the site for future use. What I am doing is that I am saving entire url in the database.
But I need to validate it as a valid url. It looks like this.
http://www.anywebsite.com/cars.php?postcode=CV2+5AS&distance=&make=&min_price=&max_price=&category_type=&body_type=&fuel=&colour=&transmission=&year_of_registration=&mileage=&engine=&doors=&seller=&keywords=&sort=PRICE_LOWEST&referer_url=http%253A%252F%252Flocalhost%252Fselling%252Fcars.php&trader_id=0&case=ADVANCE
Can anyone please provide me with any idea as to how I can achieve it?
I have preg_match which is here.
if (!preg_match('/^https?:(\/\/)?(www\.)?([a-zA-Z0-9_%]*)\b\.[a-z]{2,4}(\.[a-z]{2})?/', $fields[$field_name]))
But it only validates urls such as http://www.anywebsite.com, whereas I need to validate the entire above url.
Any help will be highly appreciated.
There shouldn't be a reason why you would need to code up URL validation by hand, this problem has been solved.
Take a look at php's filter_var()
.
Example of URL validation: http://www.w3schools.com/php/filter_validate_url.asp
$url = "http://www.anywebsite.com/cars.php?postcode=CV2+5AS&distance=&make=&min_price=&max_price=&category_type=&body_type=&fuel=&colour=&transmission=&year_of_registration=&mileage=&engine=&doors=&seller=&keywords=&sort=PRICE_LOWEST&referer_url=http%253A%252F%252Flocalhost%252Fselling%252Fcars.php&trader_id=0&case=ADVANCE";
if (!filter_var($url, FILTER_VALIDATE_URL)) {
echo "URL is not valid";
}
else {
echo "URL is valid";
}