thara Posted January 17, 2015 Share Posted January 17, 2015 HI, I am triying to check a domain is valid or not using PHP. If the domian is not a valid one the name shoud be empty string. So I tried using preg_match() and preg_replace(). But I couldn't get it to work. This is my code sofar - if (preg_match ('/^((?!-)[A-Za-z0-9-]{1,63}(?<!-)\\.)+[A-Za-z]{2,6}$/', $domain)) { $mydomain = $domain; } else { $mydomain = preg_replace("/^((?!-)[A-Za-z0-9-]{1,63}(?<!-)\\.)+[A-Za-z]{2,6}$/", "", $domain); } When I am tring using valid and invalid domain name its always going to else part. Eg: example.com example.t.t.c Hope somebody may help me out. Thank you. Quote Link to comment https://forums.phpfreaks.com/topic/294011-check-domain-name-is-valid-or-not/ Share on other sites More sharing options...
ginerjm Posted January 17, 2015 Share Posted January 17, 2015 What defines a 'valid' domain name? It's simply a string with periods in it. Quote Link to comment https://forums.phpfreaks.com/topic/294011-check-domain-name-is-valid-or-not/#findComment-1503257 Share on other sites More sharing options...
Jacques1 Posted January 17, 2015 Share Posted January 17, 2015 None of this makes sense. If there's no match for your regex, you try to do a replacement with the exact same regex. What? You already know that the regex doesn't match, so the replacement obviously won't do anything. Maybe what you actually meant is simply $mydomain = ''. Your examples are processed like you want: The first one triggers the if branch, the second one triggers the else branch. I have no idea how you came to the conclusion that both trigger the else branch. That homegrown regex stuff generally doesn't do much. It will happily accept any garbage as long as it contains a bunch of dots (e. g.“i.do.not.exist” is perfectly valid according to you). If you want a more serious check, use the Public Suffix List. Quote Link to comment https://forums.phpfreaks.com/topic/294011-check-domain-name-is-valid-or-not/#findComment-1503261 Share on other sites More sharing options...
QuickOldCar Posted January 17, 2015 Share Posted January 17, 2015 I don't believe is a reliable way to do this unless you visit the said domain and confirm it can connect. Use curl to get the response code and make all 200 and 300 range responses as valid Quote Link to comment https://forums.phpfreaks.com/topic/294011-check-domain-name-is-valid-or-not/#findComment-1503276 Share on other sites More sharing options...
Jacques1 Posted January 18, 2015 Share Posted January 18, 2015 Um, what? We're talking about domains here, not HTTP resources. A domain doesn't send response codes. There could be a webserver on the machine, and that webserver may or may not send certain response codes for certain resources, but that's an entirely different topic. Quote Link to comment https://forums.phpfreaks.com/topic/294011-check-domain-name-is-valid-or-not/#findComment-1503284 Share on other sites More sharing options...
thara Posted January 18, 2015 Author Share Posted January 18, 2015 Valid Domain Names - www.google.com google.com mkyong123.com Invalid Domain Names - mkyong.t.t.c – Tld must between 2 and 6 long mkyong,com – Comma is not allow mkyong So, my $domain variable should have above valid or not valid domain. First I need to check, the value of $domain is valid or not. So I have used this regx pattern in my if condition - But its not match '/^((?!-)[A-Za-z0-9-]{1,63}(?<!-)\\.)+[A-Za-z]{2,6}$/' In else part I want to set $mydomain to empty if $domain have invalid value. And also I want to prevent from XSS attacks as I might print this value, thats way I used this line - preg_replace("/^((?!-)[A-Za-z0-9-]{1,63}(?<!-)\\.)+[A-Za-z]{2,6}$/", "", $domain); But this is not working for me. Quote Link to comment https://forums.phpfreaks.com/topic/294011-check-domain-name-is-valid-or-not/#findComment-1503287 Share on other sites More sharing options...
Jacques1 Posted January 18, 2015 Share Posted January 18, 2015 Did you read any of the replies? Repeating the same wrong statements and nonsensical code snippets isn't gonna help us. You need to read the replies, understand them and have a discussion with us. Again: The regex does match your valid examples. It really does. If you get different results, there's something wrong with the way you're testing your code. Try this: <?php $domain = 'mkyong123.com'; if (preg_match ('/^((?!-)[A-Za-z0-9-]{1,63}(?<!-)\\.)+[A-Za-z]{2,6}$/', $domain)) { $mydomain = $domain; echo 'Match'; } else { $mydomain = preg_replace("/^((?!-)[A-Za-z0-9-]{1,63}(?<!-)\\.)+[A-Za-z]{2,6}$/", "", $domain); echo 'No match'; } You see “Match” on the screen, right? That means the regexes matches the domain. And again: The else part is nonsensical. You cannot replace something which isn't there. If you want to set $mydomain to an empty string, you do it like this: $mydomain = ''; OK? Quote Link to comment https://forums.phpfreaks.com/topic/294011-check-domain-name-is-valid-or-not/#findComment-1503289 Share on other sites More sharing options...
QuickOldCar Posted January 18, 2015 Share Posted January 18, 2015 We're talking about domains here, not HTTP resources. A domain doesn't send response codes. There could be a webserver on the machine, and that webserver may or may not send certain response codes for certain resources, but that's an entirely different topic. I'll stick to what I said. Trying in any other way unless actually checking for top and second level domains in an array is only way have a chance determining if could possibly be a valid domain. aaaaa.aaa would be valid in the above code or any other regex unless also did the tld and sld matches Quote Link to comment https://forums.phpfreaks.com/topic/294011-check-domain-name-is-valid-or-not/#findComment-1503293 Share on other sites More sharing options...
Jacques1 Posted January 18, 2015 Share Posted January 18, 2015 (edited) There's a difference between a domain and an HTTP URL. A domain is simply an identifier in the DNS system. It doesn't have anything to do with web pages, response codes or whatever you may have in mind. A domain doesn't even have to map to an IP address. For example, it's perfectly valid to set up a domain exclusively for e-mail addresses. In that case, cURL wouldn't even manage to resolve the domain. But even if the domain happens to point to an IP address (which is not a requirement in any way), that still doesn't mean there's a webserver on it. For example, I have a machine exclusively for VPN. There's no Apache anywhere, any attempt of connecting to port 80 or 443 will fail. Does that mean the domain is invalid? No, it simply means it's not meant for the WWW. But even if there happens to be an IP address with an active webserver, that still doesn't mean you'll get a 200 response code for the specific path “/” (I guess that's what you meant). Maybe the only valid path is “/index.html”. Does that mean there's something wrong with the domain? No. I understand that browsers make us think the entire Internet consists of websites: You type some domain into the address bar, and automatically a website pops up – and if it doesn't, then “the domain is invalid”. This is very wrong. The Internet is much broader than the WWW, and the original poster didn't say anything about checking websites. The question was about domains. Edited January 18, 2015 by Jacques1 1 Quote Link to comment https://forums.phpfreaks.com/topic/294011-check-domain-name-is-valid-or-not/#findComment-1503294 Share on other sites More sharing options...
Jacques1 Posted January 18, 2015 Share Posted January 18, 2015 Of course you do have a point that formal validation alone doesn't really prove anything. So, yes, it might make sense to also check the DNS records. Depends on the problem. Quote Link to comment https://forums.phpfreaks.com/topic/294011-check-domain-name-is-valid-or-not/#findComment-1503316 Share on other sites More sharing options...
QuickOldCar Posted January 18, 2015 Share Posted January 18, 2015 I agree with you, a lot depends on the specific applications intention. It's just a hard thing to do. you can try to eliminate most of the invalid but to ensure is always valid is harder. Takes a few steps and huge array to match against. ICANN releases new generic top level domains all the time, is over 1,300 projected ones http://newgtlds.icann.org/en/program-status/delegated-strings This is the list of the current root zones http://www.iana.org/domains/root/db Here is a list of top and second levels including the generic to check against This was made over a long period and was a pain to find them all. .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 Quote Link to comment https://forums.phpfreaks.com/topic/294011-check-domain-name-is-valid-or-not/#findComment-1503330 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.