Jump to content

Recommended Posts

I'm looking to be able to validate a URL to make sure it has a tld in it (ex. http://example.com, instead of http://example).

 

I know that I can use the following code to validate a URL, but it doesn't make sure that it has a tld, just that it has http/https/etc.

if (filter_var($url, FILTER_VALIDATE_URL) === FALSE) {
    die('Not a valid URL');
}

(By the way, I am not very experienced in PHP, but I do know some basics)

ICANN/IANA also maintains a list of literally the top-level domains. Meaning it lists "uk" but not "co.uk". Doesn't include the IDN versions of the xn-- labels but that's not difficult to deal with in code.

 

Keep in mind that "foo.bar" is a valid domain name - a user could put forward even the slightest bit of effort to circumvent any sort of general-purpose domain name verification you may put in place.

Want to check if is a protocol, contains a decimal point first, Parse the URL , then end explode it, do an in_array() check in your array of top and generic domains.

 

I have my own list I made including decimal points with top,second and generic domains, didn't feel like editing it so are extra in the array.

<?php
$domains = array(".abogado",".ac",".ac.ae",".ac.cn",".academy",".accountants",".active",".actor",".ad",".ads",".adult",".ae",".aero",".af",".africa",".ag",".agency",".agent",".ah.cn",".ai",".airforce",".ak.us",".al",".al.us",".allfinanz",".alsace",".am",".amsterdam",".an",".android",".ao",".apartments",".app",".aq",".aquarelle",".ar",".ar.us",".arab",".archi",".architect",".army",".arpa",".art",".arts",".as",".asia",".associates",".at",".attorney",".au",".au.com",".auction",".audio",".auto",".autos",".aw",".ax",".axa",".az",".az.us",".b2b",".b2c",".b2m",".ba",".baby",".band",".bank",".bar",".barcelona",".bargains",".baseball",".basketball",".bayern",".bb",".bd",".be",".beauty",".beer",".berlin",".best",".bet",".bf",".bg",".bh",".bi",".bible",".bid",".bike",".bingo",".bio",".biz",".bj",".bj.cn",".bl",".black",".blackfriday",".blog",".bloomberg",".blue",".bm",".bmw",".bn",".bnpparibas",".bo",".boats",".boo",".book",".boutique",".box",".bq",".br",".br.com",".broadway",".broker",".brussels",".bs",".bt",".budapest",".build",".builders",".business",".buy",".buzz",".bv",".bw",".by",".bz",".bzh",".ca",".ca.us",".cab",".cafe",".cal",".cam",".camera",".camp",".cancerresearch",".capetown",".capital",".car",".caravan",".cards",".care",".career",".careers",".cars",".cartier",".casa",".cash",".casino",".cat",".catering",".cc",".cd",".center",".ceo",".cern",".cf",".cg",".ch",".channel",".charity",".chat",".cheap",".christmas",".chrome",".church",".ci",".citic",".city",".ck",".cl",".claims",".cleaning",".click",".clinic",".clothing",".cloud",".club",".cm",".cn",".cn.com",".co",".co.uk",".co.us",".coach",".codes",".coffee",".college",".cologne",".com",".com.ac",".com.au",".com.cn",".com.tw",".community",".company",".computer",".condos",".construction",".consulting",".contractors",".cooking",".cool",".coop",".corp",".corsica",".country",".coupon",".coupons",".cpa",".cq.cn",".cr",".credit",".creditcard",".cricket",".crs",".cruises",".ct.us",".cu",".cuisinella",".cv",".cw",".cx",".cy",".cymru",".cz",".dad",".dance",".data",".date",".dating",".day",".dc.us",".dds",".de",".de.com",".de.net",".de.us",".deal",".deals",".degree",".delivery",".democrat",".dental",".dentist",".desi",".design",".dev",".diamonds",".diet",".digital",".dir",".direct",".directory",".discount",".diy",".dj",".dk",".dk.org",".dm",".dnp",".do",".docs",".doctor",".dog",".domains",".doosan",".durban",".dot",".download",".dubai",".durban",".dvag",".dz",".earth",".eat",".ec",".eco",".edu",".edu.ac",".edu.af",".edu.cn",".education",".ee",".eg",".eh",".email",".emerck",".energy",".engineer",".engineering",".enterprises",".equipment",".er",".es",".estate",".esq",".et",".eu",".eu.com",".eu.org",".eurovision",".eus",".events",".everbank",".exchange",".expert",".exposed",".fail",".faith",".family",".fan",".fans",".farm",".fashion",".feedback",".fi",".film",".final",".finance",".financial",".firm",".firmdale",".fish",".fishing",".fit",".fitness",".fj",".fj.cn",".fk",".fl.us",".flights",".florist",".flowers",".flsmidth",".fly",".fm",".fo",".foo",".food",".football",".forsale",".forum",".foundation",".fr",".free",".frl",".frogans",".fun",".fund",".furniture",".futbol",".fyi",".ga",".ga.us",".gal",".gallery",".game",".games",".garden",".gay",".gb",".gb.com",".gb.net",".gbiz",".gd",".gd.cn",".ge",".gent",".gf",".gg",".ggee",".gh",".gi",".gift",".gifts",".gives",".gl",".glass",".gle",".global",".globo",".gm",".gmail",".gmbh",".gmo",".gmx",".gn",".gold",".golf",".google",".gop",".gov",".gov.ac",".gov.ae",".gov.cn",".gp",".gq",".gr",".graphics",".gratis",".green",".gripe",".group",".gs",".gs.cn",".gt",".gu",".guide",".guitars",".guru",".gw",".gx.cn",".gy",".gz.cn",".ha.cn",".hair",".hamburg",".haus",".hb.cn",".he.cn",".health",".healthcare",".help",".helsinki",".here",".hi.cn",".hi.us",".hiphop",".hiv",".hk",".hl.cn",".hm",".hn",".hn.cn",".hockey",".holdings",".holiday",".home",".homes",".horse",".hospital",".host",".hosting",".hot",".hotel",".house",".how",".hr",".ht",".hu",".hu.com",".ia.us",".ibm",".id",".id.us",".ie",".il",".il.us",".im",".immo",".immobilien",".in",".industries",".in.us",".inc",".indians",".industries",".info",".ing",".ink",".institute",".insurance",".insure",".int",".international",".investments",".io",".iq",".ir",".irish",".is",".it",".iwc",".je",".jetzt",".jl.cn",".jm",".jo",".jobs",".joburg",".jp",".js.cn",".juegos",".jx.cn",".kaufen",".kddi",".ke",".kg",".kh",".ki",".kids",".kim",".kitchen",".kiwi",".km",".kn",".koeln",".kp",".kr",".krd",".kred",".ks.us",".ku",".kw",".ky",".ky.us",".kyoto",".kz",".la",".la.us",".lacaixa",".land",".lat",".latino",".latrobe",".law",".lawyer",".lb",".lc",".lds",".lease",".legal",".lgbt",".li",".lidl",".life",".lighting",".limited",".limo",".link",".live",".living",".lk",".llc",".llp",".ln.cn",".loan",".loans",".lol",".london",".lotto",".love",".lr",".ls",".lt",".ltd",".ltda",".ltd.uk",".lu",".luxe",".luxury",".lv",".ly",".m2c",".m2m",".ma",".madrid",".maison",".mail",".management",".mango",".map",".market",".marketing",".ma.us",".mba",".mc",".md",".md.us",".me",".media",".medical",".meet",".melbourne",".meme",".memorial",".men",".menu",".me.uk",".me.us",".med",".mf",".mg",".mh",".miami",".mi.us",".mil",".mil.ac",".mil.ae",".mil.cn",".mini",".mk",".ml",".mm",".mn",".mo",".mo.us",".mobi",".mobile",".moda",".moe",".mom",".monash",".money",".mormon",".mortgage",".moscow",".moto",".motorcycles",".mov",".movie",".mp",".mq",".mr",".ms",".ms.us",".mt",".mt.us",".mu",".museum",".music",".mv",".mw",".mx",".my",".mz",".na",".nagoya",".name",".navy",".nc",".nc.us",".nd.us",".ne",".ne.us",".net",".network",".neustar",".net.ac",".net.ae",".net.cn",".net.tw",".net.uk",".new",".news",".nexus",".nf",".ng",".ngo",".nh.us",".nhk",".ni",".ninja",".nj.us",".nl",".nm.cn",".nm.us",".no",".no.com",".nom.ad",".now",".np",".nr",".nra",".nrw",".nu",".nv.us",".nx.cn",".ny.us",".nyc",".nz",".oh.us",".ok.us",".okinawa",".om",".one",".ong",".onl",".online",".ooo",".or.us",".org",".organic",".org.ac",".org.ae",".org.cn",".org.tw",".org.uk",".osaka",".otsuka",".ovh",".pa",".pa.us",".paris",".partners",".parts",".party",".pay",".pe",".pet",".pets",".pf",".pg",".ph",".phd",".pharmacy",".phone",".photo",".photography",".photos",".physio",".pics",".pictures",".pid",".ping",".pink",".pizza",".pk",".pl",".place",".play",".plc",".plc.uk",".plumbing",".plus",".pm",".pn",".pohl",".poker",".porn",".post",".pr",".praxi",".press",".pro",".pro.ae",".prod",".productions",".prof",".properties",".property",".ps",".pt",".pub",".pw",".py",".qa",".qc.com",".qh.cn",".qpon",".quebec",".racing",".radio",".re",".realestate",".realtor",".realty",".rec",".recipes",".red",".rehab",".reise",".reisen",".reit",".ren",".rent",".rentals",".repair",".report",".republican",".rest",".restaurant",".review",".reviews",".ri.us",".rich",".rio",".rip",".ro",".rocks",".rodeo",".rs",".rsvp",".ru",".ru.com",".rugby",".ruhr",".run",".rw",".ryukyu",".sa",".saarland",".sale",".salon",".samsung",".sarl",".save",".sa.com",".sb",".sc",".sca",".sc.cn",".sc.us",".scb",".sch.ae",".sch.uk",".schmidt",".school",".schule",".schwarz",".science",".scot",".sd",".sd.cn",".sd.us",".se",".se.com",".search",".services",".sew",".sexy",".sg",".sh",".sh.cn",".shiksha",".shoes",".shop",".shopping",".show",".shriram",".si",".singles",".site",".sj",".sk",".ski",".sl",".sm",".sn",".sn.cn",".so",".soc",".soccer",".social",".software",".sohu",".solar",".solutions",".soy",".spa",".space",".spiegel",".sport",".sports",".spot",".sr",".ss",".st",".store",".stream",".studio",".style",".su",".supplies",".supply",".support",".surf",".surgery",".suzuki",".sv",".swiss",".sx.cn",".sy",".sydney",".systems",".sz",".taipei",".tatar",".tattoo",".tax",".taxi",".tc",".td",".team",".tech",".technology",".tel",".tennis",".tf",".tg",".th",".thai",".theater",".tickets",".tienda",".tips",".tires",".tirol",".tj",".tj.cn",".tk",".tl",".tm",".tn",".tn.us",".to",".today",".tokyo",".tools",".top",".tour",".tours",".town",".toys",".tp",".tr",".trade",".trading",".training",".travel",".trust",".tt",".tube",".tui",".tv",".tw",".tw.cn",".tx.us",".tz",".ua",".ug",".uk",".uk.com",".uk.net",".um",".university",".uno",".uol",".us",".us.com",".ut.us",".uy",".uy.com",".uz",".va",".va.us",".vacations",".vc",".ve",".vegas",".ventures",".versicherung",".vet",".vg",".vi",".viajes",".video",".villas",".vision",".vin",".vip",".vision",".vlaanderen",".vn",".vodka",".vote",".voting",".voto",".voyage",".vt.us",".vu",".wa.us",".wales",".wang",".watch",".web",".webcam",".website",".wed",".wedding",".wf",".whoswho",".wi.us",".wien",".wiki",".williamhill",".win",".wine",".wme",".work",".works",".world",".wow",".ws",".wtc",".wtf",".测试",".परीक्षा",".佛山",".集团",".在线",".한국",".ভারত",".八卦",".موقع",".বাংলা",".公益",".公司",".移动",".我爱你",".москва",".испытание",".қаз",".онлайн",".сайт",".срб",".бел",".테스트",".орг",".삼성",".சிங்கப்பூர்",".商标",".商店",".商城",".дети",".мкд",".טעסט",".中文网",".中信",".中国",".中國",".谷歌",".భారత్",".ලංකා",".測試",".ભારત",".भारत",".آزمایشی",".பரிட்சை",".网店",".संगठन",".网络",".укр",".香港",".δοκιμή",".إختبار",".台湾",".台灣",".手机",".мон",".الجزائر",".عمان",".ایران",".امارات",".بازار",".پاکستان",".الاردن",".بھارت",".المغرب",".السعودية",".سودان",".عراق",".مليسيا",".شبكة",".გე",".机构",".组织机构",".ไทย",".سورية",".рус",".рф",".تونس",".みんな",".グーグル",".世界",".ਭਾਰਤ",".网址",".游戏",".vermögensberater",".vermögensberatung",".企业",".مصر",".قطر",".广东",".இலங்கை",".இந்தியா",".հայ",".新加坡",".فلسطين",".テスト",".政务",".wv.us",".wy.us",".xj.cn",".xxx",".xyz",".xz.cn",".yachts",".yandex",".ye",".yoga",".yokohama",".youtube",".yn.cn",".yt",".yu",".za",".za.com",".zip",".zj.cn",".zm",".zone",".zr",".zuerich",".zw");


function checkUrl($url, $domains)
{
    $url = trim($url);
    if (parse_url($url, PHP_URL_SCHEME) && strpos($url, ".") !== false) {
        $suffix = end(explode(".", $url));
        if (in_array(".$suffix", $domains)) {
            return true;
        } else {
            return false;
        }
        
    } else {
        return false;
    }
}


//usage
$sample_urls = array(
    "http://phpfreaks.com",
    "phpfreaks.com",
    "http://phpfreaks.blah",
    "http://phpfreaks.com.blah"
);

foreach ($sample_urls as $url) {
    if (checkUrl($url, $domains)) {
        echo "<p style='color:green;'> $url </p>";
    } else {
        echo "<p style='color:red;'> $url </p>";
    }
}
?>

 

Want to check if is a protocol, contains a decimal point first, Parse the URL , then end explode it, do an in_array() check in your array of top and generic domains.

 

I have my own list I made including decimal points with top,second and generic domains, didn't feel like editing it so are extra in the array.

<?php
$domains = array(".abogado",".ac",".ac.ae",".ac.cn",".academy",".accountants",".active",".actor",".ad",".ads",".adult",".ae",".aero",".af",".africa",".ag",".agency",".agent",".ah.cn",".ai",".airforce",".ak.us",".al",".al.us",".allfinanz",".alsace",".am",".amsterdam",".an",".android",".ao",".apartments",".app",".aq",".aquarelle",".ar",".ar.us",".arab",".archi",".architect",".army",".arpa",".art",".arts",".as",".asia",".associates",".at",".attorney",".au",".au.com",".auction",".audio",".auto",".autos",".aw",".ax",".axa",".az",".az.us",".b2b",".b2c",".b2m",".ba",".baby",".band",".bank",".bar",".barcelona",".bargains",".baseball",".basketball",".bayern",".bb",".bd",".be",".beauty",".beer",".berlin",".best",".bet",".bf",".bg",".bh",".bi",".bible",".bid",".bike",".bingo",".bio",".biz",".bj",".bj.cn",".bl",".black",".blackfriday",".blog",".bloomberg",".blue",".bm",".bmw",".bn",".bnpparibas",".bo",".boats",".boo",".book",".boutique",".box",".bq",".br",".br.com",".broadway",".broker",".brussels",".bs",".bt",".budapest",".build",".builders",".business",".buy",".buzz",".bv",".bw",".by",".bz",".bzh",".ca",".ca.us",".cab",".cafe",".cal",".cam",".camera",".camp",".cancerresearch",".capetown",".capital",".car",".caravan",".cards",".care",".career",".careers",".cars",".cartier",".casa",".cash",".casino",".cat",".catering",".cc",".cd",".center",".ceo",".cern",".cf",".cg",".ch",".channel",".charity",".chat",".cheap",".christmas",".chrome",".church",".ci",".citic",".city",".ck",".cl",".claims",".cleaning",".click",".clinic",".clothing",".cloud",".club",".cm",".cn",".cn.com",".co",".co.uk",".co.us",".coach",".codes",".coffee",".college",".cologne",".com",".com.ac",".com.au",".com.cn",".com.tw",".community",".company",".computer",".condos",".construction",".consulting",".contractors",".cooking",".cool",".coop",".corp",".corsica",".country",".coupon",".coupons",".cpa",".cq.cn",".cr",".credit",".creditcard",".cricket",".crs",".cruises",".ct.us",".cu",".cuisinella",".cv",".cw",".cx",".cy",".cymru",".cz",".dad",".dance",".data",".date",".dating",".day",".dc.us",".dds",".de",".de.com",".de.net",".de.us",".deal",".deals",".degree",".delivery",".democrat",".dental",".dentist",".desi",".design",".dev",".diamonds",".diet",".digital",".dir",".direct",".directory",".discount",".diy",".dj",".dk",".dk.org",".dm",".dnp",".do",".docs",".doctor",".dog",".domains",".doosan",".durban",".dot",".download",".dubai",".durban",".dvag",".dz",".earth",".eat",".ec",".eco",".edu",".edu.ac",".edu.af",".edu.cn",".education",".ee",".eg",".eh",".email",".emerck",".energy",".engineer",".engineering",".enterprises",".equipment",".er",".es",".estate",".esq",".et",".eu",".eu.com",".eu.org",".eurovision",".eus",".events",".everbank",".exchange",".expert",".exposed",".fail",".faith",".family",".fan",".fans",".farm",".fashion",".feedback",".fi",".film",".final",".finance",".financial",".firm",".firmdale",".fish",".fishing",".fit",".fitness",".fj",".fj.cn",".fk",".fl.us",".flights",".florist",".flowers",".flsmidth",".fly",".fm",".fo",".foo",".food",".football",".forsale",".forum",".foundation",".fr",".free",".frl",".frogans",".fun",".fund",".furniture",".futbol",".fyi",".ga",".ga.us",".gal",".gallery",".game",".games",".garden",".gay",".gb",".gb.com",".gb.net",".gbiz",".gd",".gd.cn",".ge",".gent",".gf",".gg",".ggee",".gh",".gi",".gift",".gifts",".gives",".gl",".glass",".gle",".global",".globo",".gm",".gmail",".gmbh",".gmo",".gmx",".gn",".gold",".golf",".google",".gop",".gov",".gov.ac",".gov.ae",".gov.cn",".gp",".gq",".gr",".graphics",".gratis",".green",".gripe",".group",".gs",".gs.cn",".gt",".gu",".guide",".guitars",".guru",".gw",".gx.cn",".gy",".gz.cn",".ha.cn",".hair",".hamburg",".haus",".hb.cn",".he.cn",".health",".healthcare",".help",".helsinki",".here",".hi.cn",".hi.us",".hiphop",".hiv",".hk",".hl.cn",".hm",".hn",".hn.cn",".hockey",".holdings",".holiday",".home",".homes",".horse",".hospital",".host",".hosting",".hot",".hotel",".house",".how",".hr",".ht",".hu",".hu.com",".ia.us",".ibm",".id",".id.us",".ie",".il",".il.us",".im",".immo",".immobilien",".in",".industries",".in.us",".inc",".indians",".industries",".info",".ing",".ink",".institute",".insurance",".insure",".int",".international",".investments",".io",".iq",".ir",".irish",".is",".it",".iwc",".je",".jetzt",".jl.cn",".jm",".jo",".jobs",".joburg",".jp",".js.cn",".juegos",".jx.cn",".kaufen",".kddi",".ke",".kg",".kh",".ki",".kids",".kim",".kitchen",".kiwi",".km",".kn",".koeln",".kp",".kr",".krd",".kred",".ks.us",".ku",".kw",".ky",".ky.us",".kyoto",".kz",".la",".la.us",".lacaixa",".land",".lat",".latino",".latrobe",".law",".lawyer",".lb",".lc",".lds",".lease",".legal",".lgbt",".li",".lidl",".life",".lighting",".limited",".limo",".link",".live",".living",".lk",".llc",".llp",".ln.cn",".loan",".loans",".lol",".london",".lotto",".love",".lr",".ls",".lt",".ltd",".ltda",".ltd.uk",".lu",".luxe",".luxury",".lv",".ly",".m2c",".m2m",".ma",".madrid",".maison",".mail",".management",".mango",".map",".market",".marketing",".ma.us",".mba",".mc",".md",".md.us",".me",".media",".medical",".meet",".melbourne",".meme",".memorial",".men",".menu",".me.uk",".me.us",".med",".mf",".mg",".mh",".miami",".mi.us",".mil",".mil.ac",".mil.ae",".mil.cn",".mini",".mk",".ml",".mm",".mn",".mo",".mo.us",".mobi",".mobile",".moda",".moe",".mom",".monash",".money",".mormon",".mortgage",".moscow",".moto",".motorcycles",".mov",".movie",".mp",".mq",".mr",".ms",".ms.us",".mt",".mt.us",".mu",".museum",".music",".mv",".mw",".mx",".my",".mz",".na",".nagoya",".name",".navy",".nc",".nc.us",".nd.us",".ne",".ne.us",".net",".network",".neustar",".net.ac",".net.ae",".net.cn",".net.tw",".net.uk",".new",".news",".nexus",".nf",".ng",".ngo",".nh.us",".nhk",".ni",".ninja",".nj.us",".nl",".nm.cn",".nm.us",".no",".no.com",".nom.ad",".now",".np",".nr",".nra",".nrw",".nu",".nv.us",".nx.cn",".ny.us",".nyc",".nz",".oh.us",".ok.us",".okinawa",".om",".one",".ong",".onl",".online",".ooo",".or.us",".org",".organic",".org.ac",".org.ae",".org.cn",".org.tw",".org.uk",".osaka",".otsuka",".ovh",".pa",".pa.us",".paris",".partners",".parts",".party",".pay",".pe",".pet",".pets",".pf",".pg",".ph",".phd",".pharmacy",".phone",".photo",".photography",".photos",".physio",".pics",".pictures",".pid",".ping",".pink",".pizza",".pk",".pl",".place",".play",".plc",".plc.uk",".plumbing",".plus",".pm",".pn",".pohl",".poker",".porn",".post",".pr",".praxi",".press",".pro",".pro.ae",".prod",".productions",".prof",".properties",".property",".ps",".pt",".pub",".pw",".py",".qa",".qc.com",".qh.cn",".qpon",".quebec",".racing",".radio",".re",".realestate",".realtor",".realty",".rec",".recipes",".red",".rehab",".reise",".reisen",".reit",".ren",".rent",".rentals",".repair",".report",".republican",".rest",".restaurant",".review",".reviews",".ri.us",".rich",".rio",".rip",".ro",".rocks",".rodeo",".rs",".rsvp",".ru",".ru.com",".rugby",".ruhr",".run",".rw",".ryukyu",".sa",".saarland",".sale",".salon",".samsung",".sarl",".save",".sa.com",".sb",".sc",".sca",".sc.cn",".sc.us",".scb",".sch.ae",".sch.uk",".schmidt",".school",".schule",".schwarz",".science",".scot",".sd",".sd.cn",".sd.us",".se",".se.com",".search",".services",".sew",".sexy",".sg",".sh",".sh.cn",".shiksha",".shoes",".shop",".shopping",".show",".shriram",".si",".singles",".site",".sj",".sk",".ski",".sl",".sm",".sn",".sn.cn",".so",".soc",".soccer",".social",".software",".sohu",".solar",".solutions",".soy",".spa",".space",".spiegel",".sport",".sports",".spot",".sr",".ss",".st",".store",".stream",".studio",".style",".su",".supplies",".supply",".support",".surf",".surgery",".suzuki",".sv",".swiss",".sx.cn",".sy",".sydney",".systems",".sz",".taipei",".tatar",".tattoo",".tax",".taxi",".tc",".td",".team",".tech",".technology",".tel",".tennis",".tf",".tg",".th",".thai",".theater",".tickets",".tienda",".tips",".tires",".tirol",".tj",".tj.cn",".tk",".tl",".tm",".tn",".tn.us",".to",".today",".tokyo",".tools",".top",".tour",".tours",".town",".toys",".tp",".tr",".trade",".trading",".training",".travel",".trust",".tt",".tube",".tui",".tv",".tw",".tw.cn",".tx.us",".tz",".ua",".ug",".uk",".uk.com",".uk.net",".um",".university",".uno",".uol",".us",".us.com",".ut.us",".uy",".uy.com",".uz",".va",".va.us",".vacations",".vc",".ve",".vegas",".ventures",".versicherung",".vet",".vg",".vi",".viajes",".video",".villas",".vision",".vin",".vip",".vision",".vlaanderen",".vn",".vodka",".vote",".voting",".voto",".voyage",".vt.us",".vu",".wa.us",".wales",".wang",".watch",".web",".webcam",".website",".wed",".wedding",".wf",".whoswho",".wi.us",".wien",".wiki",".williamhill",".win",".wine",".wme",".work",".works",".world",".wow",".ws",".wtc",".wtf",".测试",".परीक्षा",".佛山",".集团",".在线",".한국",".ভারত",".八卦",".موقع",".বাংলা",".公益",".公司",".移动",".我爱你",".москва",".испытание",".қаз",".онлайн",".сайт",".срб",".бел",".테스트",".орг",".삼성",".சிங்கப்பூர்",".商标",".商店",".商城",".дети",".мкд",".טעסט",".中文网",".中信",".中国",".中國",".谷歌",".భారత్",".ලංකා",".測試",".ભારત",".भारत",".آزمایشی",".பரிட்சை",".网店",".संगठन",".网络",".укр",".香港",".δοκιμή",".إختبار",".台湾",".台灣",".手机",".мон",".الجزائر",".عمان",".ایران",".امارات",".بازار",".پاکستان",".الاردن",".بھارت",".المغرب",".السعودية",".سودان",".عراق",".مليسيا",".شبكة",".გე",".机构",".组织机构",".ไทย",".سورية",".рус",".рф",".تونس",".みんな",".グーグル",".世界",".ਭਾਰਤ",".网址",".游戏",".vermögensberater",".vermögensberatung",".企业",".مصر",".قطر",".广东",".இலங்கை",".இந்தியா",".հայ",".新加坡",".فلسطين",".テスト",".政务",".wv.us",".wy.us",".xj.cn",".xxx",".xyz",".xz.cn",".yachts",".yandex",".ye",".yoga",".yokohama",".youtube",".yn.cn",".yt",".yu",".za",".za.com",".zip",".zj.cn",".zm",".zone",".zr",".zuerich",".zw");


function checkUrl($url, $domains)
{
    $url = trim($url);
    if (parse_url($url, PHP_URL_SCHEME) && strpos($url, ".") !== false) {
        $suffix = end(explode(".", $url));
        if (in_array(".$suffix", $domains)) {
            return true;
        } else {
            return false;
        }
        
    } else {
        return false;
    }
}


//usage
$sample_urls = array(
    "http://phpfreaks.com",
    "phpfreaks.com",
    "http://phpfreaks.blah",
    "http://phpfreaks.com.blah"
);

foreach ($sample_urls as $url) {
    if (checkUrl($url, $domains)) {
        echo "<p style='color:green;'> $url </p>";
    } else {
        echo "<p style='color:red;'> $url </p>";
    }
}
?>

 

I really love the idea. However it looks like this code will produce an error. I am thinking it's because you might have to use end and explode on seperate lines. Like

$suffix = explode(".", $url);
$suffix = end($suffix);

I have no idea why this happens, but it just does.

Edited by lush_rainforest

I have no idea why this happens, but it just does.

It's because end() wants to modify internal information about an array, so it needs to be passed a variable and by reference. If the function returned an array by reference, that would work too.

A combination of strrpos and substr will work for a one-liner too.

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.