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.
The PHP code in the previous example will be slightly modified to download the file from the given path. The clearstatecache function is used to clear the cache that was previously stored. Two arguments are used in the readfile function.
Output After the download link of the PDF file is clicked, the following output will appear. This article provided a simple way to forcibly download any file using the PHP script, to help readers to add the download feature in their script. I am a trainer of web programming courses. I like to write article or tutorial on various IT topics. Generally, no PHP script is required to download a file with the extensions exe and zip. If the file location of this type of file is set in the href attribute of the anchor element, then the file automatically downloads when the user clicks on the download link.
These files can be downloaded forcibly in PHP using the readfile function that does not download automatically. This tutorial shows you how to forcibly download any file using PHP script. 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. The regular expression in the above example line no-8 will simply not allow those files whose name starts or ends with a dot character.
Please check out the tutorial on regular expressions to learn the regular expressions in details. Is this website helpful to you? Please give us a like , or share your feedback to help us improve.
Connect with us on Facebook and Twitter for the latest updates. Example Try this code ». Example Run this code ».
0コメント