search
HomeBackend DevelopmentPHP TutorialPHP header function download file implementation code_PHP tutorial

PHP header function download file implementation code_PHP tutorial

Jul 13, 2016 pm 05:15 PM
headerphpdownloadcodeusefunctionexistaccomplishdocumentof

The header function is widely used in php. The header can not only send the original HTTP header information to the client, but also directly implement the file download operation. Next, the editor will introduce it to you and welcome all friends for reference.

The header function is most commonly used not for downloading but for sending http classes

Jump

It will execute the last one, but conditionally, for example:

The code is as follows Copy code
 代码如下 复制代码

header('Location:http://www.bKjia.c0m");
header('Location:http://www.g.cn');
header('Location:http://www.baidu.com');

这个就会跳到百度

header('Location:http://www.bKjia.c0m');echo '帮客之家;
header('Location:http://www.g.cn');
header('Location:http://www.baidu.com');

header('Location:http://www.bKjia.c0m");

header('Location:http://www.g.cn');

header('Location:http://www.baidu.com');


This will jump to Baidu

header('Location:http://www.bKjia.c0m');echo 'Bang Ke Home;

header('Location:http://www.g.cn');
 代码如下 复制代码

header('HTTP/1.1 401 Unauthorized');
header('status: 401 Unauthorized');
?>

header('Location:http://www.baidu.com');

This will jump to google
 代码如下 复制代码

header('HTTP/1.1 404 Not Found');
header("status: 404 Not Found");
?>

Send status


Output the status value to the browser, mainly used for access control

The code is as follows Copy code
 代码如下 复制代码

$filename = '路径+实际文件名';
//文件的类型
header('Content-type: application/pdf');
//下载显示的名字
header('Content-Disposition: attachment; filename="保存时的文件名.pdf"');
readfile("$filename");
exit();
?>

header('HTTP/1.1 401 Unauthorized'); header('status: 401 Unauthorized'); ?>
 代码如下 复制代码
header(‘Content-type: application/octet-stream’);//输出的类型,根据下面提供的MIME表,选择相应的类型
header(‘Content-Disposition: attachment; filename=”下载显示名字.rar”‘);//下载显示的名字
readfile(‘服务器上的文件名.rar’);//
For example, if you want to restrict a user from accessing this page, you can set the status to 404, as shown below, so that the browser will display that the page does not exist
The code is as follows Copy code
header('HTTP/1.1 404 Not Found'); header("status: 404 Not Found"); ?>
Download Example
The code is as follows Copy code
$filename = 'path + actual file name'; //Type of file header('Content-type: application/pdf'); //Download the displayed name header('Content-Disposition: attachment; filename="File name when saving.pdf"'); readfile("$filename"); exit(); ?>
Header function performs corresponding conversion,
The code is as follows Copy code
header('Content-type: application/octet -stream');//Output type, select the corresponding type according to the MIME table provided below header(‘Content-Disposition: attachment; filename=”Download display name.rar”‘);//Download display name readfile(‘File name on the server.rar’);//

要下的文件,包括路径

常用的MIME类型
.doc    application/msword
.docx   application/vnd.openxmlformats-officedocument.wordprocessingml.document
.rtf    application/rtf
.xls    application/vnd.ms-excel application/x-excel
.xlsx   application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
.ppt    application/vnd.ms-powerpoint
.pptx   application/vnd.openxmlformats-officedocument.presentationml.presentation
.pps   application/vnd.ms-powerpoint
.ppsx  application/vnd.openxmlformats-officedocument.presentationml.slideshow
.pdf   application/pdf
.swf   application/x-shockwave-flash
.dll   application/x-msdownload
.exe   application/octet-stream
.msi   application/octet-stream
.chm   application/octet-stream
.cab   application/octet-stream
.ocx   application/octet-stream
.rar  application/octet-stream
.tar  application/x-tar
.tgz  application/x-compressed
.zip  application/x-zip-compressed
.z    application/x-compress
.wav   audio/wav
.wma   audio/x-ms-wma
.wmv   video/x-ms-wmv
.mp3 .mp2 .mpe .mpeg .mpg   audio/mpeg
.rm   application/vnd.rn-realmedia
.mid .midi .rmi   audio/mid
.bmp   image/bmp
.gif   image/gif
.png   image/png
.tif .tiff    image/tiff
.jpe .jpeg .jpg    image/jpeg
.txt  text/plain
.xml  text/xml
.html text/html
.css  text/css
.js   text/javascript

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/628850.htmlTechArticle在php中header函数的使用很大,header不但可以向客户端发送原始的 HTTP 报头信息,同时还可以直接实现文件下载操作,接下来小编给大家介绍...
Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How to make PHP applications fasterHow to make PHP applications fasterMay 12, 2025 am 12:12 AM

TomakePHPapplicationsfaster,followthesesteps:1)UseOpcodeCachinglikeOPcachetostoreprecompiledscriptbytecode.2)MinimizeDatabaseQueriesbyusingquerycachingandefficientindexing.3)LeveragePHP7 Featuresforbettercodeefficiency.4)ImplementCachingStrategiessuc

PHP Performance Optimization Checklist: Improve Speed NowPHP Performance Optimization Checklist: Improve Speed NowMay 12, 2025 am 12:07 AM

ToimprovePHPapplicationspeed,followthesesteps:1)EnableopcodecachingwithAPCutoreducescriptexecutiontime.2)ImplementdatabasequerycachingusingPDOtominimizedatabasehits.3)UseHTTP/2tomultiplexrequestsandreduceconnectionoverhead.4)Limitsessionusagebyclosin

PHP Dependency Injection: Improve Code TestabilityPHP Dependency Injection: Improve Code TestabilityMay 12, 2025 am 12:03 AM

Dependency injection (DI) significantly improves the testability of PHP code by explicitly transitive dependencies. 1) DI decoupling classes and specific implementations make testing and maintenance more flexible. 2) Among the three types, the constructor injects explicit expression dependencies to keep the state consistent. 3) Use DI containers to manage complex dependencies to improve code quality and development efficiency.

PHP Performance Optimization: Database Query OptimizationPHP Performance Optimization: Database Query OptimizationMay 12, 2025 am 12:02 AM

DatabasequeryoptimizationinPHPinvolvesseveralstrategiestoenhanceperformance.1)Selectonlynecessarycolumnstoreducedatatransfer.2)Useindexingtospeedupdataretrieval.3)Implementquerycachingtostoreresultsoffrequentqueries.4)Utilizepreparedstatementsforeffi

Simple Guide: Sending Email with PHP ScriptSimple Guide: Sending Email with PHP ScriptMay 12, 2025 am 12:02 AM

PHPisusedforsendingemailsduetoitsbuilt-inmail()functionandsupportivelibrarieslikePHPMailerandSwiftMailer.1)Usethemail()functionforbasicemails,butithaslimitations.2)EmployPHPMailerforadvancedfeatureslikeHTMLemailsandattachments.3)Improvedeliverability

PHP Performance: Identifying and Fixing BottlenecksPHP Performance: Identifying and Fixing BottlenecksMay 11, 2025 am 12:13 AM

PHP performance bottlenecks can be solved through the following steps: 1) Use Xdebug or Blackfire for performance analysis to find out the problem; 2) Optimize database queries and use caches, such as APCu; 3) Use efficient functions such as array_filter to optimize array operations; 4) Configure OPcache for bytecode cache; 5) Optimize the front-end, such as reducing HTTP requests and optimizing pictures; 6) Continuously monitor and optimize performance. Through these methods, the performance of PHP applications can be significantly improved.

Dependency Injection for PHP: a quick summaryDependency Injection for PHP: a quick summaryMay 11, 2025 am 12:09 AM

DependencyInjection(DI)inPHPisadesignpatternthatmanagesandreducesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itallowspassingdependencieslikedatabaseconnectionstoclassesasparameters,facilitatingeasiertestingandscalability.

Increase PHP Performance: Caching Strategies & TechniquesIncrease PHP Performance: Caching Strategies & TechniquesMay 11, 2025 am 12:08 AM

CachingimprovesPHPperformancebystoringresultsofcomputationsorqueriesforquickretrieval,reducingserverloadandenhancingresponsetimes.Effectivestrategiesinclude:1)Opcodecaching,whichstorescompiledPHPscriptsinmemorytoskipcompilation;2)DatacachingusingMemc

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version