PHP Get URL: Download HTML Pages or Get the Page URL in PHP

This article contains information on two things:

  1. How to get your script's URL in PHP

  2. How to download and save an HTML file in PHP

1. Get Your Script's URL in PHP

Getting the URL of your own PHP script is surprisingly tricky in PHP. You can use the following PHP; none of the variables we use here are guaranteed to be defined by your server, but usually they will be.

$url =
'http://' .
'?' .

echo $url;

$url is set to, for example:


... or whatever your script's URL is.

Note that we've hard-coded 'http' here. If you want to check whether your URL in fact starts with 'https' or something else, you'll need to check the

2. Download an HTML File in PHP

You can download an HTML file from a URL in PHP (phew that was a lot of acryonyms!) using the curl functions.

The following PHP page downloads an HTML page and saves it as "content.html". You can use the PHP here as the basis of your own web page scrapers.


// Create a URL handle.
$ch = curl_init();

// Tell curl what URL we want.
curl_setopt($ch, CURLOPT_URL, http://localhost:4000);

// We want to return the web page from curl_exec, not 
// print it.

// Set this if you don't want the content header.
curl_setopt($ch, CURLOPT_HEADER, 0);

// Download the HTML from the URL.
$content = curl_exec($ch);

// Check to see if there were errors.
if(curl_errno($ch)) {
    // We have an error. Show the error message.
    echo curl_error($ch);
else {
    // No error. Save the page content.
    $file = 'content.html';
    // Open a file for writing.
    $fh = fopen($file, 'w');
    if(!$fh) {
        // Couldn't create the file.
        echo "Unable to create $file";
    else {
        // Write the retrieved
        // html to the file.
        fwrite($fh, $content);
        // Display a message to say
        // we've saved the file OK.
        echo "Saved $file";
        // Close the file.

// Close the curl handle.