To open an external URL in PHP, we will use cURL which is a PHP library, a cURL is also a command-line tool that is used to send files and download data over HTTP and FTP.
Check live view below.

We will take 2 steps to do this.
- Create an HTML form with only a button with a name attribute.
- Create a PHP cURL function that is used to open an external URL.
Create HTML Form
1 2 3 4 5 6 7 8 |
<!DOCTYPE html> <html> <body> <form method="POST"> <button name="clickHere">Click Here To Open External URL in PHP</button> </form> </body> </html> |
This form is only used for clicking the button to open an external URL.
Create PHP Script to Open External URL
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
<?php function openURL($url) { // Create a new cURL resource $ch = curl_init(); // Set the file URL to fetch through cURL curl_setopt($ch, CURLOPT_URL, $url); // Do not check the SSL certificates curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // Return the actual result of the curl result instead of success code curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_HEADER, 0); $data = curl_exec($ch); curl_close($ch); return $data; } if (isset($_POST['clickHere'])) { echo openURL('https://phpcoder.tech/'); } ?> |
Code Explanations:
$ch = curl_init();
- Create a new cURL resource
curl_setopt($ch, CURLOPT_URL, $url);
- Set the file URL to fetch through cURL
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
- Do not check the SSL certificates
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
- Return the actual result of the curl result instead of the success code
At the last, we call the function on the time of button click.
To know more about the PHP cURL library you check here: https://www.php.net/manual/en/book.curl.php
Here is the live view of the complete source code to How we open the external URL.
Also Check:
- How to Get HTML Tag Value in PHP
- How to Keep Value After Page Reload in PHP
- 2 Ways to Open URL in New Tab Using JavaScript
- How to Embed PDF in Website Using HTML
Happy Coding..!
One Reply to “How to Open an External URL in PHP”