How to download a php file without executing it?

If such php file is located on the same server/website, then just open it as normal file, e.g. $fileContents = file_get_contents($filename);

If file is on another server, you have few possible options:

1) Access it via FTP (if you have login details and access)

2) Have special URL Rewrite rule on that server which will instruct web server to send file as plain text instead of executing it (e.g. somefile.php.txt)

3) Have special script on that server and by passing file name as a parameter it will return content of that file (e.g. http://example.com/showfile.php?file=somefile.php)


This is how to download a php file instead of executing it.

Trust me it works! ..download the file php with own risk :)

<?php
function downloadThatPhp($nameOfTheFile)
    {
        header("Pragma: public");
        header("Expires: 0"); // set expiration time
        header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
        header("Content-Type: application/text/x-vCard");
        header("Content-Disposition: attachment; filename=".basename($nameOfTheFile).";");
        header("Content-Transfer-Encoding: binary");
        header("Content-Length: ".filesize($nameOfTheFile));
        @readfile($nameOfTheFile);
        exit(0);
    }

    // and this how to use:
    // download that php file with your own risk :)
    $file = $_REQUEST['file_name'];
    $downloadThis = "http://domain-name.com/".$file;
    if (file_exists($file)) {
        downloadThatPhp($downloadThis);
    }
?>

Hope this helps you bro :)


The server somehow identifies file that should be executed instead of downloaded. You have to exclude the .php file you want to download from that handling. The easiest is probably to rename the file to .php.txt.

Otherwise you should be able to configure the server to not process that particular file, or the path were it is located. How you do that depends on which server you are running.


You have to load the files content, write the content to the request and set the headers so that it's parsed as force download or octet stream.

For example:

http://server.com/download.php?name=test.php

Contents of download.php:

  <?php 
  $filename = $_GET["name"]; //Obviously needs validation
  ob_end_clean();
  header("Content-Type: application/octet-stream; "); 
  header("Content-Transfer-Encoding: binary"); 
  header("Content-Length: ". filesize($filename).";"); 
  header("Content-disposition: attachment; filename=" . $filename);
  readfile($filename);
  die();
  ?>

This code works without any modification. Although it needs validation and some security features.

Tags:

Php

Download