Add HTTP Protocol if not Exist with URL

Posted By TimesCoding Staff | June 7, 2022 | PHP

 The below function is used to add HTTP protocol to the URL if not available. You can add “http://” or “https://” by using the function.

<?php

function addHttpProtocol($url, $scheme){
	return parse_url($url, PHP_URL_SCHEME) === null ? $scheme . $url : $url;
}
	
	echo addHttpProtocol('timescoding.com', 'http://');
	//result:  
	//  http://timescoding.com
	
	echo addHttpProtocol('timescoding.com', 'https://');
	//result:  
	//  https://timescoding.com

?>



Author: TimesCoding Staff

TimesCoding Staff is a member of the team, and an expert in HTML, CSS, JavaScript, PHP, Ajax, and WordPress theme development.

Read Next