However, zip and exe files are downloaded automatically to the hard drive by default. You can force images or other kind of files to download directly to the user's hard drive using the PHP readfile function. Here we're going to create a simple image gallery that allows users to download the image files from the browser with a single mouse click. If you see the above example code carefully, you'll find the download link pints to a "download.
Also, we've used PHP urlencode function to encode the image file names so that it can be safely passed as URL parameter, because file names may contain URL unsafe characters. I have used this script for file downloads even bigger than MB. The cache control header is used to force a download for text files or other files, even if they are opened by default inside your web browser. View the code on Gist. Create on your web page links for all the file which resists in a password protected directory or in a directory above the website root directory.
Use for our example the following download URL:. With the following example, I will use a string to receive the name of a file which is stored inside a secure MySQL database.
Let say, we have a simple database table with only two columns for the ID and the filename. The code for the file download. In the first example I used the file name inside the download URL. If you really need to protect your downloads , you need to deny the direct access of the file location using Apache directives or. Use more secure slugs to receive a file name from your database. For example you can encrypt the database row key as well.
Published in: PHP Scripts. Most JavaScript examples…. Next, the header function is used to set the necessary header information before using the readfile function. The basename function is used to retrieve the filename, and the filesize function is used to read the size of the file in bytes, which will be shown in the opening dialog box to download the file. The flush function is used to clear the output buffer. The readfile function is used with the filename only, here.
Output The following output will appear after clicking the download link of the image file. The file size of the rose. You can download the file by selecting the Save File radio button and pressing the OK button.
If the file exists at the given file location, the file path will be required to mention in the URL. In this example, we will create an HTML file with the following code, which will pass the filename with the file path:.
We will create a PHP file with the following code to download a file from the file path. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content.
While using W3Schools, you agree to have read and accepted our terms of use , cookie and privacy policy. Copyright by Refsnes Data. All Rights Reserved.
0コメント