Lslschr
Lslschr

Reputation: 25

Download .js file with php

I got following files:

index.php:

<html>

<head>
  <title>Admin Panel</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>

<body>
  <br /><br />
  <div class="container">
    <h2 align="center">Admin Panel</a></h2>
    <br />
    <div align="right">
      <a href="download_current.php"><button  type="button" name="create_folder" id="create_folder" class="btn btn-success">Get current file</button></a>
    </div>
    <br />
    <div class="table-responsive" id="folder_table">

    </div>
  </div>
</body>

</html>
<div id="uploadModal" class="modal fade" role="dialog">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal">&times;</button>
        <h4 class="modal-title">Upload File</h4>
      </div>
      <div class="modal-body">
        <form method="post" id="upload_form" enctype='multipart/form-data' action="upfile.php">
          <p>Select Js File
            <input type="file" name="upload_file" accept=".js"/></p>
          <br />
          <input type="hidden" name="hidden_folder_name" id="hidden_folder_name" />
          <input type="submit" name="upload_button" class="btn btn-info" value="Upload" />
        </form>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
      </div>
    </div>
  </div>
</div>

<div id="filelistModal" class="modal fade" role="dialog">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal">&times;</button>
        <h4 class="modal-title">File List</h4>
      </div>
      <div class="modal-body" id="file_list">

      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
      </div>
    </div>
  </div>
</div>

<script>
  $(document).ready(function() {

    load_folder_list();

    function load_folder_list() {
      var action = "fetch";
      $.ajax({
        url: "action.php",
        method: "POST",
        data: {
          action: action
        },
        success: function(data) {
          $('#folder_table').html(data);
        }
      });
    }

    $(document).on('click', '.upload', function() {
      var folder_name = $(this).data("name");
      $('#hidden_folder_name').val(folder_name);
      $('#uploadModal').modal('show');
    });

    $('#upload_form').on('submit', function() {
      $.ajax({
        url: "upfile.php",
        method: "POST",
        data: new FormData(this),
        contentType: false,
        cache: false,
        processData: false,
      });
    });



    $(document).on('click', '.view_files', function() {
      var folder_name = $(this).data("name");
      var action = "fetch_files";
      $.ajax({
        url: "action.php",
        method: "POST",
        data: {
          action: action,
          folder_name: folder_name
        },
        success: function(data) {
          $('#file_list').html(data);
          $('#filelistModal').modal('show');
        }
      });
    });

    $(document).on('click', '.remove_file', function() {
      var path = $(this).attr("id");
      var action = "remove_file";
      $.ajax({
        url: "action.php",
        method: "POST",
        data: {
          path: path,
          action: action
        },
        success: function(data) {
          $('#filelistModal').modal('hide');
          load_folder_list();
        }
      });
    });
  });
</script>

action.php:

<?php

function format_folder_size($size)
{
    if ($size >= 1073741824) {
        $size = number_format($size / 1073741824, 2) . ' GB';
    } elseif ($size >= 1048576) {
        $size = number_format($size / 1048576, 2) . ' MB';
    } elseif ($size >= 1024) {
        $size = number_format($size / 1024, 2) . ' KB';
    } elseif ($size > 1) {
        $size = $size . ' bytes';
    } elseif ($size == 1) {
        $size = $size . ' byte';
    } else {
        $size = '0 bytes';
    }
    return $size;
}

function get_folder_size($folder_name)
{
    $total_size = 0;
    $file_data = scandir($folder_name);
    foreach ($file_data as $file) {
        if ($file === '.' or $file === '..') {
            continue;
        } else {
            $path = $folder_name . '/' . $file;
            $total_size = $total_size + filesize($path);
        }
    }
    return format_folder_size($total_size);
}

if (isset($_POST["action"])) {
    if ($_POST["action"] == "fetch") {
        $folder = array_filter(glob('*'), 'is_dir');

        $output = '
  <table class="table table-bordered table-striped">
   <tr>
    <th>Folder Name</th>
    <th>Total File</th>
    <th>Size</th>
    <th>Upload File</th>
    <th>View Uploaded File</th>
   </tr>
   ';
        if (count($folder) > 0) {
            foreach ($folder as $name) {
                $output .= '
     <tr>
      <td>' . $name . '</td>
      <td>' . (count(scandir($name)) - 2) . '</td>
      <td>' . get_folder_size($name) . '</td>
      <td><button type="button" name="upload" data-name="' . $name . '" class="upload btn btn-info btn-xs">Upload File</button></td>
      <td><button type="button" name="view_files" data-name="' . $name . '" class="view_files btn btn-default btn-xs">View Files</button></td>
     </tr>';
            }
        } else {
            $output .= '
    <tr>
     <td colspan="6">No Folder Found</td>
    </tr>
   ';
        }
        $output .= '</table>';
        echo $output;
    }


    if ($_POST["action"] == "fetch_files") {
        $file_data = scandir($_POST["folder_name"]);
        $output = '
  <table class="table table-bordered table-striped">
   <tr>
    <th>File Name</th>
    <th>Download</th>
   </tr>
  ';

        foreach ($file_data as $file) {
            if ($file === '.' or $file === '..') {
                continue;
            } else {
                $script = 'download.php';
                $downloadlink = $script . '/' . $_POST["folder_name"] . '/' . $file;
                $path = $_POST["folder_name"] . '/' . $file;
                $output .= '
    <tr>
     <td contenteditable="false" data-folder_name="' . $_POST["folder_name"] . '"  data-file_name = "' . $file . '" class="change_file_name">' . $file . '</td>
     <td><a href="' . $downloadlink . '"><button name="remove_file" class="remove_file btn btn-danger btn-xs" id="' . $path . '">Get it</button></td></a>
    </tr>
    ';
            }
        }
        $output .= '</table>';
        echo $output;
    }
    function test()
    {
        if ($_POST["action"] == "remove_file") {
            if (file_exists($_POST["path"])) {
                readfile($_POST["path"]);
            }
        }
    }
}

download.php

<?php

//file path in server

$path = $_POST["folder_name"] . '/' . $file;

// check if file exist in server

if (file_exists($path)) {

    header("Cache-Control: public");

    header('Content-Description: File Transfer');

    header('Content-Type: application/x-javascript');

    header('Content-Disposition: attachment; filename="' . basename($path) . '"');

    header('Content-Length: ' . filesize($path));

    // Clear output buffer

    flush();

    readfile($path);

    exit();
} else {

    echo "File not found.";
}
?>

The Problem now is that when I download the javascript files from my server then it downloads the file but without any content in it. On the server the files have content in it, so it must be a problem while downloading it from the website. I think the problem is at the download.php but in my opinion the syntax are correct. It could be also a problem at the remove_file fucntion in the index.php and action.php. See $(document).on('click', '.remove_file', function() in index.php

Upvotes: 1

Views: 1710

Answers (1)

Angshu31
Angshu31

Reputation: 1270

I'd say you need html for this. I don't know if you can use PHP for this. If you really need to use PHP:

<?php
  echo "<a href='file.js' download>Click Here to Download</a>";
?>

Essentially, what this does is create a link, in which the user clicks to download the file.

Upvotes: 1

Related Questions