check the file before downloading the file using php

依然范特西╮ 提交于 2020-01-05 05:36:06

问题


i want to check the file before downloading the file, i have controller Download and function download_file

here is my code : i tired this code and i always get no

public function download_file($namafile,$nofile)
        {
    $filecek =(site_url()."/uploads/file/".$namafile);
        $data = file_get_contents(site_url().'/uploads/file/'.$namafile);

    echo "$filecek";

    if (!file_exists($filecek)) {
      echo "no";
    }else {
force_download($namafile,$data);
      echo "yes";
    }

        }
    }

and this is link for download

<a href="<?php echo base_url(); ?>download/<?php echo $getFiles['file']; ?>/<?php echo $getFiles['nofile']; ?>"><i class="icon-download"></i> <?php echo $getFiles['kategori']; ?></a>

回答1:


site_url() won't work that way because you always get the Website Url ...

file_exists() however checks whether a directory or file exists on your server or not - so you need an absolute position..

There is a CONSTANT called FCPATH which you can use - it points to the directory where your index.php resides.

So basically you can try the following

public function download_file($namafile,$nofile)
{
    $filecek = FCPATH."uploads/file/".$namafile;

    echo "$filecek";

    if (!file_exists($filecek)) 
    {
        echo "no";
    }
    else 
    {
        force_download($namafile, NULL);
        echo "yes";
    }
}

the only condition here is - that uploads/file/ exists within your FCPATH.




回答2:


What is the output of $filecek?

IMO $filecek =(site_url()."/uploads/file/".$namafile); should be changed to $filecek =(base_url()."/uploads/file/".$namafile); because

echo base_url(); //http://example.com/website
echo site_url(); //http://example.com/website/index.php

For accessing resources base_url() is acceptable as you can't get a file in http://example.com/website/index.php/file.ext



来源:https://stackoverflow.com/questions/50426788/check-the-file-before-downloading-the-file-using-php

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!