Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking if a url has http:// at the beginning & inserting if not [duplicate]

I am currently editing a wordpress theme with custom field outputs. I have successfully made all the edits and everything works as it should. My problem is that if a url is submitted into the custom field, the echo is exactly what was in there, so if someone enters www.somesite.com the echo is just that and adds it to the end of the domain: www.mysite.com www.somesite.com . I want to check to see if the supplied link has the http:// prefix at the beginning, if it has then do bothing, but if not echo out http:// before the url.

I hope i have explained my problem as good as i can.

$custom = get_post_meta($post->ID, 'custom_field', true);

<?php if ( get_post_meta($post->ID, 'custom_field', true) ) : ?>
    <a href="<?php echo $custom ?>"> <img src="<?php echo bloginfo('template_url');?>/lib/images/social/image.png"/></a>
    <?php endif; ?>
like image 734
Rory Web Rothon Avatar asked Dec 21 '11 14:12

Rory Web Rothon


People also ask

How do I check if a string contains http?

To check if string starts with “http”, use PHP built-in function strpos(). strpos() takes the string and substring as arguments and returns 0, if the string starts with “http”, else not. This kind of check is useful when you want to verify if given string is an URL or not.

How do I know if my URL contains https?

How do I know if my URL contains https? If the string to parse is also the page url then you could use $_SERVER["REQUEST_SCHEME"] which returns 'http' or 'https' or $_SERVER["HTTPS"] which returns 1 if the scheme is https.

How do I know if a URL is reachable?

Visit Website Planet. Enter the URL of your website address on the field and press the Check button. Website Planet will show whether your website is online or not.


2 Answers

parse_url() can help...

$parsed = parse_url($urlStr);
if (empty($parsed['scheme'])) {
    $urlStr = 'http://' . ltrim($urlStr, '/');
}
like image 130
DaveRandom Avatar answered Oct 31 '22 05:10

DaveRandom


You can check if http:// is at the beginning of the string using strpos().

$var = 'www.somesite.com';

if(strpos($var, 'http://') !== 0) {
  return 'http://' . $var;
} else {
  return $var;
}

This way, if it does not have http:// at the very beginning of the var, it will return http:// in front of it. Otherwise it will just return the $var itself.

like image 32
Tyil Avatar answered Oct 31 '22 03:10

Tyil