- 4 years ago
- Zaid Bin Khalid
- 5661 Views
-
11
PHP is a very strong language that allows you to download a file from a server. You just need to set the header of PHP for that.
Below code will help you to understand the process of how you can download any file from server forcefully using the PHP function.
<?php
function DownloadFile($stringFilePath){
$file_to_download = $stringFilePath; // file to be downloaded
header("Expires: 0");
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
header("Cache-Control: no-store, no-cache, must-revalidate");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache"); header("Content-type: application/file");
header('Content-length: '.filesize($file_to_download));
header('Content-disposition: attachment; filename="'.basename($file_to_download).'"');
readfile($file_to_download);
}
?>
In the above code snippet, we create a function. What is a function in PHP? It is very simple to understand.
A function is a user define code that can be used multiple times. It is a set of code as you can see in the above snippet. To create a function in PHP we use Function keyword and then we define a Function Name. And in small brackets, we pass function parameters that can be accessed within the function.
Note: Every function has its own scope. How we write a function? Below code will help you.
<?php
function Here_You_Can_Write_Your_Function_Name(){
//.. Here you can write your code example.
echo 'Hi world, I am Zaid!';
}
?>
Now, how we call this function and run function code? It is also very simple in PHP. You just need to write function name given example below.
<?php
Here_You_Can_Write_Your_Function_Name();
?>
This function gives “Hi world, I am Zaid!” output. We can do this using a function parameter, an example given below.
<?php
function Here_You_Can_Write_Your_Function_Name($string){
//.. Here you can write your code example.
echo $string;
}
?>
Now you can pass anything into $string variable like.
<?php
Here_You_Can_Write_Your_Function_Name('Hello World, I am Zaid!');
?>
I hope you understand how PHP function works. Now, to download file form a server you just need to pass a full path of a file into the DownloadFile($stringFilePath) function.
- 4 years ago
- Zaid Bin Khalid
- 5661 Views
-
11