php 文件下载方法

 更新时间:2016年11月25日 17:31  点击:2106
文章也很简单我们只要用利用head 发送头部信息就能实现把文件下载到本了,有直接发送header信息也有把文件保存在服务器上再用header来发送哦,有需要的朋友参考下。

用的是表头方式下载

 代码如下 复制代码
Header( "Content-type:   application/octet-stream ");
Header( "Accept-Ranges:   bytes ");
Header( "Accept-Length:   ".filesize($file_dir   .   $file_name));
Header( "Content-Disposition:   attachment;   filename= "   .   $file_name);

判断文件存在再下载

 代码如下 复制代码
<?php
    if( isset( $_REQUEST["download"] ) )
    {
            $tfile = $_REQUEST["download"];
           
            if (file_exists($tfile))
            {
                $downfilename=substr($tfile,strrpos($tfile, "/")+1);
               //文件保存的名字可以修改为你需要的,可以和链接给的名字不一样
                // Prompt the user to download the new torrent file.
                header( "Content-type: application/octet-streamn" );
                header( "Content-disposition: attachment; filename=$downfilenamen" );
                header( "Content-transfer-encoding: binaryn");
                header( "Content-length: " . @filesize($tfile ) . "n" );
                // Send the torrent file
                $fp = @fopen( $tfile, "r" );
                @fpassthru( $fp );
                @fclose( $fp );
             }
           
            exit();
     }
?>

pdf文件下载

 代码如下 复制代码

<?php
$filename = $_SERVER['DOCUMENT_ROOT'] . "/path/to/file/my_file.pdf";
header("Cache-Control: public");
header("Content-Description: File Transfer");
header('Content-disposition: attachment; filename='.basename($filename));
header("Content-Type: application/pdf"); //pdf格式的

?>


下面讲讲header中的Content-type:
不同的下载文件,对应不同的content-type,下面是大全:
PHP code
{
'ez' => 'application/andrew-inset',
'hqx' => 'application/mac-binhex40',
'cpt' => 'application/mac-compactpro',
'doc' => 'application/msword',
'bin' => 'application/octet-stream',
'dms' => 'application/octet-stream',
'lha' => 'application/octet-stream',
'lzh' => 'application/octet-stream',
'exe' => 'application/octet-stream',
'class' => 'application/octet-stream',
'so' => 'application/octet-stream',
'dll' => 'application/octet-stream',
'oda' => 'application/oda',
'pdf' => 'application/pdf',
'ai' => 'application/postscript',
'eps' => 'application/postscript',
'ps' => 'application/postscript',
'smi' => 'application/smil',
'smil' => 'application/smil',
'mif' => 'application/vnd.mif',
'xls' => 'application/vnd.ms-excel',
'ppt' => 'application/vnd.ms-powerpoint',
'wbxml' => 'application/vnd.wap.wbxml',
'wmlc' => 'application/vnd.wap.wmlc',
'wmlsc' => 'application/vnd.wap.wmlscriptc',
'bcpio' => 'application/x-bcpio',
'vcd' => 'application/x-cdlink',
'pgn' => 'application/x-chess-pgn',
'cpio' => 'application/x-cpio',
'csh' => 'application/x-csh',
'dcr' => 'application/x-director',
'dir' => 'application/x-director',
'dxr' => 'application/x-director',
'dvi' => 'application/x-dvi',
'spl' => 'application/x-futuresplash',
'gtar' => 'application/x-gtar',
'hdf' => 'application/x-hdf',
'js' => 'application/x-javascript',
'skp' => 'application/x-koan',
'skd' => 'application/x-koan',
'skt' => 'application/x-koan',
'skm' => 'application/x-koan',
'latex' => 'application/x-latex',
'nc' => 'application/x-netcdf',
'cdf' => 'application/x-netcdf',
'sh' => 'application/x-sh',
'shar' => 'application/x-shar',
'swf' => 'application/x-shockwave-flash',
'sit' => 'application/x-stuffit',
'sv4cpio' => 'application/x-sv4cpio',
'sv4crc' => 'application/x-sv4crc',
'tar' => 'application/x-tar',
'tcl' => 'application/x-tcl',
'tex' => 'application/x-tex',
'texinfo' => 'application/x-texinfo',
'texi' => 'application/x-texinfo',
't' => 'application/x-troff',
'tr' => 'application/x-troff',
'roff' => 'application/x-troff',
'man' => 'application/x-troff-man',
'me' => 'application/x-troff-me',
'ms' => 'application/x-troff-ms',
'ustar' => 'application/x-ustar',
'src' => 'application/x-wais-source',
'xhtml' => 'application/xhtml+xml',
'xht' => 'application/xhtml+xml',
'zip' => 'application/zip',
'au' => 'audio/basic',
'snd' => 'audio/basic',
'mid' => 'audio/midi',
'midi' => 'audio/midi',
'kar' => 'audio/midi',
'mpga' => 'audio/mpeg',
'mp2' => 'audio/mpeg',
'mp3' => 'audio/mpeg',
'aif' => 'audio/x-aiff',
'aiff' => 'audio/x-aiff',
'aifc' => 'audio/x-aiff',
'm3u' => 'audio/x-mpegurl',
'ram' => 'audio/x-pn-realaudio',
'rm' => 'audio/x-pn-realaudio',
'rpm' => 'audio/x-pn-realaudio-plugin',
'ra' => 'audio/x-realaudio',
'wav' => 'audio/x-wav',
'pdb' => 'chemical/x-pdb',
'xyz' => 'chemical/x-xyz',
'bmp' => 'image/bmp',
'gif' => 'image/gif',
'ief' => 'image/ief',
'jpeg' => 'image/jpeg',
'jpg' => 'image/jpeg',
'jpe' => 'image/jpeg',
'png' => 'image/png',
'tiff' => 'image/tiff',
'tif' => 'image/tiff',
'djvu' => 'image/vnd.djvu',
'djv' => 'image/vnd.djvu',
'wbmp' => 'image/vnd.wap.wbmp',
'ras' => 'image/x-cmu-raster',
'pnm' => 'image/x-portable-anymap',
'pbm' => 'image/x-portable-bitmap',
'pgm' => 'image/x-portable-graymap',
'ppm' => 'image/x-portable-pixmap',
'rgb' => 'image/x-rgb',
'xbm' => 'image/x-xbitmap',
'xpm' => 'image/x-xpixmap',
'xwd' => 'image/x-xwindowdump',
'igs' => 'model/iges',
'iges' => 'model/iges',
'msh' => 'model/mesh',
'mesh' => 'model/mesh',
'silo' => 'model/mesh',
'wrl' => 'model/vrml',
'vrml' => 'model/vrml',
'css' => 'text/css',
'html' => 'text/html',
'htm' => 'text/html',
'asc' => 'text/plain',
'txt' => 'text/plain',
'rtx' => 'text/richtext',
'rtf' => 'text/rtf',
'sgml' => 'text/sgml',
'sgm' => 'text/sgml',
'tsv' => 'text/tab-separated-values',
'wml' => 'text/vnd.wap.wml',
'wmls' => 'text/vnd.wap.wmlscript',
'etx' => 'text/x-setext',
'xsl' => 'text/xml',
'xml' => 'text/xml',
'mpeg' => 'video/mpeg',
'mpg' => 'video/mpeg',
'mpe' => 'video/mpeg',
'qt' => 'video/quicktime',
'mov' => 'video/quicktime',
'mxu' => 'video/vnd.mpegurl',
'avi' => 'video/x-msvideo',
'movie' => 'video/x-sgi-movie',
'ice' => 'x-conference/x-cooltalk',
}

一个段经典的代码可以用来获取用户的真实IP地址,包括可以是内网或是外网,有需要的朋友可以参考一下。
 代码如下 复制代码
/**
 * 获得用户的真实IP地址
 *
 * @return  string
 */
function real_ip(){
    static $realip = NULL;
 
    if ($realip !== NULL){
        return $realip;
    }
 
    if (isset($_SERVER)){
        if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])){
            $arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
            /* 取X-Forwarded-For中第一个非unknown的有效IP字符串 */
            foreach ($arr AS $ip){
                $ip = trim($ip);
 
                if ($ip != 'unknown'){
                    $realip = $ip;
 
                    break;
                }
            }
        }
        elseif (isset($_SERVER['HTTP_CLIENT_IP'])){
            $realip = $_SERVER['HTTP_CLIENT_IP'];
        }
        else{
            if (isset($_SERVER['REMOTE_ADDR'])){
                $realip = $_SERVER['REMOTE_ADDR'];
            }
            else{
                $realip = '0.0.0.0';
            }
        }
    }
    else{
        if (getenv('HTTP_X_FORWARDED_FOR')){
            $realip = getenv('HTTP_X_FORWARDED_FOR');
        }
        elseif (getenv('HTTP_CLIENT_IP')){
            $realip = getenv('HTTP_CLIENT_IP');
        }
        else{
            $realip = getenv('REMOTE_ADDR');
        }
    }
 
    preg_match("/[d.]{7,15}/", $realip, $onlineip);
    $realip = !empty($onlineip[0]) ? $onlineip[0] : '0.0.0.0';
 
    return $realip;
}
提供二款利用遍历批量修改文件的文件名的php代码,有需要的朋友可以参考一下。

实例一

 代码如下 复制代码
<?php
//利用PHP目录和文件函数遍历用户给出目录的所有的文件和文件夹,修改文件名称
function fRename($dirname){
 if(!is_dir($dirname)){
  echo "{$dirname}不是一个有效的目录!";
  exit();
 }
 $handle = opendir($dirname);
 while(($fn = readdir($handle))!==false){
  if($fn!='.'&&$fn!='..'){
   $curDir = $dirname.'/'.$fn;
   if(is_dir($curDir)){
    fRename($curDir);
   }
   else{
    $path = pathinfo($curDir);
    $newname = $path['dirname'].'/'.rand(0,100).'.'.$path['extension'];
    rename($curDir,$newname);   
    echo $curDir.'---'.$newname."<br>";   
   }
  }
 }
}
//给出一个目录名称调用函数
fRename('pl');
?>

实例二

 代码如下 复制代码

<?php
$dir = './';

if ($dh = opendir($dir)) {
    while (($file = readdir($dh)) !== false) {
        if ($file == "." || $file == "..") continue;
        if(filetype($dir . $file) == 'file')
        {
            $newfile = str_replace('[1]', '', $file);
            rename($dir . $file, $dir . $newfile);
        }
    }
    closedir($dh);
}

提供一个实例的php自定义函数,这是一个可以批量修改文件后缀名的php程序,有需要的朋友可以参考一下。
 代码如下 复制代码

<?php
function foreachDir($path){
$handle=opendir($path);
if($handle){
while (false !== ($file = readdir($handle))) {
if($file!="." && $file!='..'){
if(is_dir($path.$file)){
echo $path.$file."<br/>";
foreachDir($path.$file);
}else{
echo "--".$path."/".$file."<br/>";
$ext = strripos($file,'.');
$aaa = substr($file,0,$ext);
rename($path.'/'.$file,$path.'/'.$aaa.'.JPG');
// die();
}
}
}
return false;
}
}
foreachDir('D:xampphtdocsTNF2');
本文章给php初学者讲了两个php中实例的字符替换函数,一个是str_ireplace()一个是substr_replace()这两个函数都比较好用,有需要的参考一下。

字符串的替换技术可以通过以下两个常用函数实现:str_ireplace()函数和substr_replace()函数
str_ireplace()函数
使用新的子字符串替换原始字符串中被指定要替换的字符串,语法:
mixed str_ireplace(mixed search,mixed replace,mixed subject[,int&count])
参数search:必要参数,指定需要查找的字符串。
参数replace:必要参数,指定替换的值。
参数subject:必要参数,指定查找的范围。
参数count:可选参数,(带中括号的为可选参数),获取执行替换的数量。

实例:

 代码如下 复制代码
<?php
$str2=”某某”;
$str1=”**”;
$str=”某某网站的地址是www.111cn.net ,某某网站主要记录一些学习php的笔记和感想以及各种软件知识”;
echo str_ireplace($str2,$str1,$str);    //str2查找的值,str1替换的值,str范围
?>

在本例中,我们将演示带有数组和 count 变量的 str_ireplace() 函数:

 代码如下 复制代码

<?php
$arr = array("blue","red","green","yellow");
print_r(str_ireplace("red","pink",$arr,$i));
echo "Replacements: $i";
?>

输出:

Array
(
[0] => blue
[1] => pink
[2] => green
[3] => yellow
)

Replacements: 1例子 3

 代码如下 复制代码

<?php
$find = array("Hello","world");
$replace = array("B");
$arr = array("Hello","world","!");
print_r(str_ireplace($find,$replace,$arr));
?>输出:

Array
(
[0] => B
[1] =>
[2] => !
)


 

substr_replace()函数
对指定字符串中的部分字符串进行替换,语法:
string substr_replace(string str,string repl,int start,[int length])
参数str:指定要操作的原始字符串。
参数repl:必要参数,指定替换后的新字符串。
参数start:指定替换字符串开始的位置。
参数length:指定返回的字符串长度。
实例:

 代码如下 复制代码

<?php
substr_replace('eggs','x',-1,-1); //eggxs
substr_replace('eggs','x',-1,-2); //eggxs
substr_replace('eggs','x',-1,-2); //eggxs
?> Same as:
<?php
substr_replace('eggs','x',-1,0); //eggxs
?>

<?php
substr_replace('huevos','x',-2,-2); //huevxos
substr_replace('huevos','x',-2,-3); //huevxos
substr_replace('huevos','x',-2,-3); //huevxos
?> Same as:

<?php
substr_replace('huevos','x',-2,0); //huevxos
?>

更多详细内容请查看:http://www.111cn.net/phper/21/32954.htm

[!--infotagslink--]

相关文章

  • php读取zip文件(删除文件,提取文件,增加文件)实例

    下面小编来给大家演示几个php操作zip文件的实例,我们可以读取zip包中指定文件与删除zip包中指定文件,下面来给大这介绍一下。 从zip压缩文件中提取文件 代...2016-11-25
  • Jupyter Notebook读取csv文件出现的问题及解决

    这篇文章主要介绍了JupyterNotebook读取csv文件出现的问题及解决,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教...2023-01-06
  • Photoshop打开PSD文件空白怎么解决

    有时我们接受或下载到的PSD文件打开是空白的,那么我们要如何来解决这个 问题了,下面一聚教程小伙伴就为各位介绍Photoshop打开PSD文件空白解决办法。 1、如我们打开...2016-09-14
  • C#操作本地文件及保存文件到数据库的基本方法总结

    C#使用System.IO中的文件操作方法在Windows系统中处理本地文件相当顺手,这里我们还总结了在Oracle中保存文件的方法,嗯,接下来就来看看整理的C#操作本地文件及保存文件到数据库的基本方法总结...2020-06-25
  • 解决python 使用openpyxl读写大文件的坑

    这篇文章主要介绍了解决python 使用openpyxl读写大文件的坑,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2021-03-13
  • C#实现HTTP下载文件的方法

    这篇文章主要介绍了C#实现HTTP下载文件的方法,包括了HTTP通信的创建、本地文件的写入等,非常具有实用价值,需要的朋友可以参考下...2020-06-25
  • SpringBoot实现excel文件生成和下载

    这篇文章主要为大家详细介绍了SpringBoot实现excel文件生成和下载,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...2021-02-09
  • php无刷新利用iframe实现页面无刷新上传文件(1/2)

    利用form表单的target属性和iframe 一、上传文件的一个php教程方法。 该方法接受一个$file参数,该参数为从客户端获取的$_files变量,返回重新命名后的文件名,如果上传失...2016-11-25
  • php批量替换内容或指定目录下所有文件内容

    要替换字符串中的内容我们只要利用php相关函数,如strstr,str_replace,正则表达式了,那么我们要替换目录所有文件的内容就需要先遍历目录再打开文件再利用上面讲的函数替...2016-11-25
  • PHP文件上传一些小收获

    又码了一个周末的代码,这次在做一些关于文件上传的东西。(PHP UPLOAD)小有收获项目是一个BT种子列表,用户有权限上传自己的种子,然后配合BT TRACK服务器把种子的信息写出来...2016-11-25
  • AI源文件转photoshop图像变模糊问题解决教程

    今天小编在这里就来给photoshop的这一款软件的使用者们来说下AI源文件转photoshop图像变模糊问题的解决教程,各位想知道具体解决方法的使用者们,那么下面就快来跟着小编...2016-09-14
  • C++万能库头文件在vs中的安装步骤(图文)

    这篇文章主要介绍了C++万能库头文件在vs中的安装步骤(图文),文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2021-02-23
  • Zend studio文件注释模板设置方法

    步骤:Window -> PHP -> Editor -> Templates,这里可以设置(增、删、改、导入等)管理你的模板。新建文件注释、函数注释、代码块等模板的实例新建模板,分别输入Name、Description、Patterna)文件注释Name: 3cfileDescriptio...2013-10-04
  • C#路径,文件,目录及IO常见操作汇总

    这篇文章主要介绍了C#路径,文件,目录及IO常见操作,较为详细的分析并汇总了C#关于路径,文件,目录及IO常见操作,具有一定参考借鉴价值,需要的朋友可以参考下...2020-06-25
  • php文件上传你必须知道的几点

    本篇文章主要说明的是与php文件上传的相关配置的知识点。PHP文件上传功能配置主要涉及php.ini配置文件中的upload_tmp_dir、upload_max_filesize、post_max_size等选项,下面一一说明。打开php.ini配置文件找到File Upl...2015-10-21
  • C#使用StreamWriter写入文件的方法

    这篇文章主要介绍了C#使用StreamWriter写入文件的方法,涉及C#中StreamWriter类操作文件的相关技巧,需要的朋友可以参考下...2020-06-25
  • ant design中upload组件上传大文件,显示进度条进度的实例

    这篇文章主要介绍了ant design中upload组件上传大文件,显示进度条进度的实例,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2020-10-29
  • php实现文件下载实例分享

    举一个案例:复制代码 代码如下:<?phpclass Downfile { function downserver($file_name){$file_path = "./img/".$file_name;//转码,文件名转为gb2312解决中文乱码$file_name = iconv("utf-8","gb2312",$file_name...2014-06-07
  • 查找php配置文件php.ini所在路径的二种方法

    通常php.ini的位置在:复制代码 代码如下:/etc目录下或/usr/local/lib目录下。如果你还是找不到php.ini或者找到了php.ini修改后不生效(其实是没找对),请使用如下办法:1.新建php文件,写入如下代码复制代码 代码如下:<?phpe...2014-05-31
  • C# 向二进制文件进行读写的操作方法

    该例子使用 BinaryStream 和 BinaryWriter 对二进制文件进行读写操作先上代码再根据我理解的所分享给各位朋友...2020-06-25