Check if URL is valid – PHP
In order to check if a URL is valid in PHP, we are going to use the cURL. You can get the complete reference on cURL from php.net. First, we are going to create a variable that will hold the value of URL that needs to be checked.
<?php
// URL to check
$url = "https://adnan-tech.com/";
Then, we are going to initialize the cURL.
// Initialize cURL
$curl = curl_init();
After that, we need to set the URL of cURL and make sure to return the response from server. For this, we will use cURL options.
// Set cURL options
curl_setopt_array($curl, [
// Set URL
CURLOPT_URL => $url,
// Make sure to return the response
CURLOPT_RETURNTRANSFER => 1
]);
Finally, we can execute this cURL request.
// Execute the CURL request
$response = curl_exec($curl);
Then, we will get the error from response (if there is any). If there is no error in response, it means that the URL is valid and the curl_error will return an empty string.
// Get error from CURL, it will be empty if there is no error.
$error = curl_error($curl);
We can put a condition on this variable to check if this variable has some value, it means there is an error in the request. In that case, we will display the error and stop the script. Otherwise, we will display a message that the URL is valid.
// If not empty, display the error and stop the script.
if ($error)
die($error);
// Else, the URL is valid
echo "Valid";
Here is the complete code.
<?php
// URL to check
$url = "https://adnan-tech.com/";
// Initialize CURL
$curl = curl_init();
// Set CURL options
curl_setopt_array($curl, [
// Set URL
CURLOPT_URL => $url,
// Make sure to return the response
CURLOPT_RETURNTRANSFER => 1
]);
// Execute the CURL request
$response = curl_exec($curl);
// Get error from CURL, it will be empty if there is no error.
$error = curl_error($curl);
// If not empty, display the error and stop the script.
if ($error)
die($error);
// Else, the URL is valid
echo "Valid";
That’s how you can check if a URL is valid or not in PHP.