Format the website URL as a string using http: // upfront

I have a comment system that automatically links URLs. I use cakephp, but the solution is just PHP. that's what happens.

if the user enters the full url with http:// or https:// , everything is fine. but if they go to www.scoobydoobydoo.com , it turns into http://cool-domain.com/www.scoobydoobydoo.com . basically, cakephp understands that http | https is an external URL, so it works with http | https otherwise.

My idea was to do something like str on the url and force it to insert http if not. unfortunately, no matter what I do, it only makes the situation worse. I noob :) any help / pointer is appreciated.

thanks

EDIT: posting a fragment of the solution. may not be the best, but thanks to the answer, at least I have something.

 <?php $proto_scheme = parse_url($webAddress,PHP_URL_SCHEME); if((!stristr($proto_scheme,'http')) || (!stristr($proto_scheme,'http'))){ $webAddress = 'http://'.$webAddress; } ?> 
+4
source share
4 answers

Try the parse_url function: http://php.net/manual/en/function.parse-url.php

I think this will help you.

+5
source
 $url = "blahblah.com"; // to clarify, this shouldn't be === false, but rather !== 0 if (0 !== strpos($url, 'http://') && 0 !== strpos($url, 'https://')) { $url = "http://{$url}"; } 
+9
source

Here is the regex: fooobar.com/questions/63818 / ...

ps @Vangel, Michael McTiernan answer is correct, so please study your PHP before saying that something may fail :)

0
source

I had a similar problem, so I created the following php function:

  function format_url($url) { if(!$url) return null; $parsed_url = parse_url($url); $schema = isset($parsed_url['scheme']) ? $parsed_url['scheme'] . '://' : 'http://'; $host = isset($parsed_url['host']) ? $parsed_url['host'] : ''; $path = isset($parsed_url['path']) ? $parsed_url['path'] : ''; return "$schema$host$path"; } 

if you format the following: format_url ('abcde.com'), the result will be http://abcde.com .

0
source

Source: https://habr.com/ru/post/1344739/


All Articles