php 网页ftp 代码二 文件上传

 更新时间:2016年11月25日 16:31  点击:2052

<?php
    $ftpserver=$_POST[ftpserver];
    $ftpport=$_POST[ftpport];
    $ftpuser=$_POST[ftpuser];
    $ftppassword=$_POST[ftppassword];
    $ftp=@ftp_connect($ftpserver,$ftpport);
    if(!$ftp){ echo "连接FTP服务器".$ftpserver."的端口".$ftpport."失败";exit;}
    $rs=@ftp_login($ftp,$ftpuser,$ftppassword);
    if(!$rs){ echo "用户名或密码错误,连接FTP服务器失败";exit;}
    $curDir=stripslashes($_POST[curDir]);
    $localfile=str_replace("\","/",stripslashes($_POST[file1]));
    
    if($localfile)
    {
     $filename=substr(strrchr($localfile,"/"),1);
     if($curDir=="/")
     {
      $remotefile=$curDir.$filename;
     }else{
      $remotefile=$curDir."/".$filename;
     }
     $rs=ftp_put($ftp,$remotefile,$localfile,FTP_ASCII);
     if($rs)
     {
      echo "<script>alert('上传文件成功');history.back();</script>";
      exit;
     }else{
      echo "<script>alert('上传文件失败');history.back();</script>";
      exit;
     }
    
    }else{
      echo "<script>alert('没有选择上传文件');history.back();</script>";
      exit;
    }
?>
<?php
    $ftpserver=$_POST[ftpserver];
    $ftpport=$_POST[ftpport];
    $ftpuser=$_POST[ftpuser];
    $ftppassword=$_POST[ftppassword];
    $ftp=@ftp_connect($ftpserver,$ftpport);
    if(!$ftp){ echo "连接FTP服务器".$ftpserver."的端口".$ftpport."失败";exit;}
    $rs=@ftp_login($ftp,$ftpuser,$ftppassword);
    if(!$rs){ echo "用户名或密码错误,连接FTP服务器失败";exit;}
    $curDir=stripslashes($_POST[curDir]);
    $dirname=stripslashes($_POST[name]);
    
    if($dirname)
    {
     if($curDir=="/")
     {
      $dirpath=$curDir.$dirname;
     }else{
      $dirpath=$curDir."/".$dirname;
     }
     $rs=ftp_mkdir($ftp,$dirpath);
     if($rs)
     {
      echo "<script>alert('创建文件夹成功');history.back();</script>";
      exit;
     }else{
      echo "<script>alert('创建文件夹失败');history.back();</script>";
      exit;
     }
    
    }else{
      echo "<script>alert('文件夹不能为空');history.back();</script>";
      exit;
    }
?>

php 网页ftp 代码

<?php
 $ftpserver="127.0.0.1";
 $ftpport="21";
 $ftpuser="anonymous";
 $ftppassword="";
 if($_POST)
 {
  $action=$_POST[action];
  switch($action)
  {
   case "open":
   case "change":
    $ftpserver=$_POST[ftpserver];
    $ftpport=$_POST[ftpport];
    $ftpuser=$_POST[ftpuser];
    $ftppassword=$_POST[ftppassword];
    $ftp=@ftp_connect($ftpserver,$ftpport);
    if(!$ftp){ echo "连接FTP服务器".$ftpserver."的端口".$ftpport."失败";exit;}
    $rs=@ftp_login($ftp,$ftpuser,$ftppassword);
    if(!$rs){ echo "用户名或密码错误,连接FTP服务器失败";exit;}
    $curDir=$_POST[curDir];
    if($curDir=="") $curDir="/";
    if($curDir=="/")
    {
     $parentDir="/";
    }else{
     if(strrpos($curDir,"/")==0)
     {
      $parentDir="/";
     }else{
      $parentDir=substr($curDir,0,strrpos($curDir,"/"));
     }
    }
    $arr=ftp_rawlist($ftp,$curDir);
    if(count($arr)>1)
    {
     foreach($arr as $val)
     {
         if($curDir=="/")
      {
          $val="/" . trim(strrchr($val," "));
      }else{
          $val=$curDir . "/" . trim(strrchr($val," "));
      }
      
      $file_size=ftp_size($ftp,$val);
      if($file_size==-1)
      {//为目录
       $dirlist[]=str_replace("\\","/",$val);
      }else{
       $filelist[]=str_replace("\\","/",$val);
      }
     }
    }
    break;
   case "close":
    break;
   
   
  }
 
 }

下面来看看WEB页面形式了.


?>

    真正支持单文件和多文件上传类代码,修正了$_FILES[$field]['name']中的$field不能用变量只能和表单中的文件名name="userfile"一致的缺点$_FILES['userfile']['name'],这里<input type="file" name="userfile"> 中的文件名可以随意取。

//index.htm
1、单文件上传
<form method="post" action="./upload.php" name="frmUpload" enctype="multipart/form-data" >
<input type="file" name="userfile" style="WIDTH: 282px">
<input type="submit" align="center" name="upfiles" value="确定"></form>
2、多文件上传
<form method="post" action="./upload.php" name="frmUpload" enctype="multipart/form-data" >
<input type="file" name="userfile[]" style="WIDTH: 282px">
<input type="file" name="userfile[]" style="WIDTH: 282px">
<input type="file" name="userfile[]" style="WIDTH: 282px">
<input type="submit" align="center" name="upfiles" value="确定">
</form>
--------------------------------------------------------------------------------------------------------------------------------
//upload.php
<?php

class File_upload{
public $upload_path='./upload/';//上传文件的路径
public $allow_type=array();//允许上传的文件类型
public $max_size='20480';//允许的最大文件大小
public $overwrite=false;//是否设置成覆盖模式
public $renamed=false;//是否直接使用上传文件的名称,还是系统自动命名

/**
* 私有变量
*/
private $upload_file=array();//保存上传成功文件的信息
private $upload_file_num=0;//上传成功文件的数目
private $succ_upload_file=array();//成功保存的文件信息
/**
* 构造器
*
* @param string $upload_path
* @param string $allow_type
* @param string $max_size
*/
public function __construct($upload_path='./upload/',$allow_type='jpg|bmp|png|gif|jpeg',$max_size='204800')
{
$this->set_upload_path($upload_path);
$this->set_allow_type($allow_type);
$this->max_size=$max_size;
$this->get_upload_files();
}
/**
* 设置上传路径,并判定
*
* @param string $path
*/
public function set_upload_path($path)
{
if(file_exists($path)){
if(is_writeable($path)){
$this->upload_path=$path;
}else{
if(@chmod($path,'0666'))
$this->upload_path=$path;
}
}else{
if(@mkdir($path,'0666')){
$this->upload_path=$path;
}
}
}
//设置上传文件类型
public function set_allow_type($types){
$this->allow_type=explode("|",$types);
}
//上传文件
public function get_upload_files()
{
foreach ($_FILES AS $key=>$field)
{
$this->get_upload_files_detial($key);
}
}
//上传文件数据存放到数组中
public function get_upload_files_detial($field){
if(is_array($_FILES["$field"]['name']))
{
for($i=0;$i<count($_FILES[$field]['name']);$i++)
{
if(0==$_FILES[$field]['error'][$i])
{
$this->upload_file[$this->upload_file_num]['name']=$_FILES[$field]['name'][$i];
$this->upload_file[$this->upload_file_num]['type']=$_FILES[$field]['type'][$i];
$this->upload_file[$this->upload_file_num]['size']=$_FILES[$field]['size'][$i];
$this->upload_file[$this->upload_file_num]['tmp_name']=$_FILES[$field]['tmp_name'][$i];
$this->upload_file[$this->upload_file_num]['error']=$_FILES[$field]['error'][$i];
$this->upload_file_num++;
}
}
}
else {
if(0==$_FILES["$field"]['error'])
{
$this->upload_file[$this->upload_file_num]['name']=$_FILES["$field"]['name'];
$this->upload_file[$this->upload_file_num]['type']=$_FILES["$field"]['type'];
$this->upload_file[$this->upload_file_num]['size']=$_FILES["$field"]['size'];
$this->upload_file[$this->upload_file_num]['tmp_name']=$_FILES["$field"]['tmp_name'];
$this->upload_file[$this->upload_file_num]['error']=$_FILES["$field"]['error'];
$this->upload_file_num++;
}
}
}
/**
* 检查上传文件是构满足指定条件
*
*/
public function check($i)
{
if(!empty($this->upload_file[$i]['name'])){
//检查文件大小
if($this->upload_file[$i]['size']>$this->max_size*1024)$this->upload_file[$i]['error']=2;
//设置默认服务端文件名
$this->upload_file[$i]['filename']=$this->upload_path.$this->upload_file[$i]['name'];
//获取文件路径信息
$file_info=pathinfo($this->upload_file[$i]['name']);
//获取文件扩展名
$file_ext=$file_info['extension'];
//检查文件类型
if(!in_array($file_ext,$this->allow_type))$this->upload_file[$i]['error']=5;
//需要重命名的
if($this->renamed){
list($usec, $sec) = explode(" ",microtime());
$this->upload_file[$i]['filename']=$sec.substr($usec,2).'.'.$file_ext;
unset($usec);
unset($sec);
}
//检查文件是否存在
if(file_exists($this->upload_file[$i]['filename'])){
if($this->overwrite){
@unlink($this->upload_file[$i]['filename']);
}else{
$j=0;
do{
$j++;
$temp_file=str_replace('.'.$file_ext,'('.$j.').'.$file_ext,$this->upload_file[$i]['filename']);
}while (file_exists($temp_file));
$this->upload_file[$i]['filename']=$temp_file;
unset($temp_file);
unset($j);
}
}
//检查完毕
} else $this->upload_file[$i]['error']=6;
}
/**
* 上传文件
*
* @return true
*/
public function upload()
{
$upload_msg='';
for($i=0;$i<$this->upload_file_num;$i++)
{
if(!empty($this->upload_file[$i]['name']))
{
//检查文件
$this->check($i);
if (0==$this->upload_file[$i]['error'])
{
//上传文件
if(!@move_uploaded_file($this->upload_file[$i]['tmp_name'],$this->upload_file[$i]['filename']))
{
$upload_msg.='上传文件'.$this->upload_file[$i]['name'].' 出错:'.$this->error($this->upload_file[$i]['error']).'!<br>';
}else
{
$this->succ_upload_file[]=$this->upload_file[$i]['filename'];
$upload_msg.='上传文件'.$this->upload_file[$i]['name'].' 成功了<br>';
}
}else $upload_msg.='上传文件'.$this->upload_file[$i]['name'].' 出错:'.$this->error($this->upload_file[$i]['error']).'!<br>';
}
}
echo $upload_msg;
}
//错误信息
public function error($error)
{
switch ($error) {
case 1:
return '文件大小超过php.ini 中 upload_max_filesize 选项限制的值';
break;
case 2:
return '文件的大小超过了 HTML 表单中 MAX_FILE_SIZE 选项指定的值';
break;
case 3:
return '文件只有部分被上传';
break;
case 4:
return '没有文件被上传';
break;
case 5:
return '这个文件不允许被上传';
break;
case 6:
return '文件名为空';
break;
default:
return '出错';
break;
}
}
//获取成功的数据信息为数组(备用)
public function get_succ_file(){
return $this->succ_upload_file;
}
}
$upload=new File_upload('./upload/','jpg|bmp|png|gif|jpeg');
$upload->upload();
$t=$upload->get_succ_file();
print_r($t);

?>

 代码如下 复制代码

 

<?php

class Uploader
{
    var $_base_dir = null;
    var $_rel_dir = null;
    var $_random_fname = false;
    var $_random_fname_len = 5;
    var $_fname_filter = null;
    var $_ftype_filter = null;
    var $_origin_paths = array();

    function Uploader( $base_dir, $rel_dir )
    {
        $this->_base_dir = $base_dir;
        $this->_rel_dir = $rel_dir;
    }
    function setRandomFileName($random_fname, $random_fname_len=5)
    {
        $this->_random_fname = $random_fname;
        $this->_random_fname_len = $random_fname_len;
    }
    function setFileTypeFilter($filter)
    {
        $this->_ftype_filter = $filter;
    }
    function addFile($file, $origin_path='')
    {
        $file = trim($file);
        $origin_path = trim($origin_path);
        if( array_key_exists($file, $this->_origin_paths) )
            return;
        $this->_origin_paths[$file] = $origin_path;
    }
    function upload()
    {
        foreach( $this->_origin_paths as $file => $origin_path )
        {
            $result = $this->_uploadFile($file, $origin_path);

            if( $result != 'Success' )
                return $result;
        }
        return 'Success';
    }
     /*
      * @desc   上传附件
      * @return  成功返回Success 失败返回失败类型
      * @param   $file 文件名 $orgin_path 文件路径
      */
    function _uploadFile($file, $origin_path)  //上传附件
    {
        $ffile = $_FILES[$file]['tmp_name'];     //文件被上传后在服务端储存的临时文件名。
        $fname = $_FILES[$file]['name'];         //客户端机器文件的原名称。
        $fsize = $_FILES[$file]['size'];         //已上传文件的大小
        $ftype = $_FILES[$file]['type'];         //文件的 MIME 类型
        $new_path = '';
       
        if( !empty($fname) && is_uploaded_file($ffile) )
        {
            if( !empty($this->_ftype_filter) && !is_null($this->_ftype_filter) )
            {
                $match = false;
                $extensions = explode(',', $this->_ftype_filter);
                foreach($extensions as $extension)
                {
                    if( strtolower(strrchr($fname,'.')) == '.'.strtolower(trim($extension)) )
                    {
                        $match  = true;
                        break;
                    }
                }
                if( !$match )
                    return 'ErrorFileTypeFilterNotMatch';
            }
            $fpath = $this->_base_dir . $this->_rel_dir;
            if( $this->_random_fname )
             $fname = $this->_getUniqueFileName($fname, $this->_random_fname_len);
            copy( $ffile, $fpath . $fname ) or die( 'upload failed!' );
            $new_path = $this->_rel_dir . $fname;
        }
        if( !empty($origin_path) && !empty($new_path) && $origin_path!=$new_path )
        {
            $this->delete($origin_path);
        }
        if( !empty($new_path) )
            $this->_origin_paths[$file] = $new_path;            
        $Erroe=$_FILES[$file]['error'];   
        switch($Erroe){
          case 1:
              return 'ErrExceedUploadMaxFileSize';
              break;
          case 2:
              return 'ErrExceedHtmlMaxFileSize';
              break;
          case 3:
              return 'ErrPartFileTrans';
              break;
//          case 4:
//              return 'ErrNoFileTrans';
//              break;
          default:
             return 'Success';
        }     
    }
     /*
      * @desc   取得路径 
      * @return  路径
      * @param   无
      */
    function getFilePath()
    {
        return $this->_origin_paths;
    }
    function getFileAbsPath()
    {
        $paths = array();
        foreach( $this->_origin_paths as $path )
        {
            $paths[] = $this->_base_dir . $path;
        }
        return $paths;
    }
    function delete( $fpath )
    {
        if( !empty($fpath) && is_file($this->_base_dir . $fpath) )
            unlink( $this->_base_dir . $fpath ) or die( 'unlink error' );
    }
    function _getUniqueFileName( $fname, $len )
    {
        $timestamp = date('YmdHis');
        srand((double)microtime()*1000000);
        for( $i=0, $randfname=''; $i<$len; $i++ )
        {
            $num = rand(0, 35);
            if( $num < 10 )
                $randfname .=  chr( ord('0')+$num );
            else
                $randfname .=  chr( ord('a')+$num-10 );
        }
        return $timestamp.'_'.$randfname.strtolower(strrchr($fname,'.'));
    }
}
?>

[!--infotagslink--]

相关文章

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

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

    这篇文章主要介绍了JupyterNotebook读取csv文件出现的问题及解决,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教...2023-01-06
  • 不打开网页直接查看网站的源代码

      有一种方法,可以不打开网站而直接查看到这个网站的源代码..   这样可以有效地防止误入恶意网站...   在浏览器地址栏输入:   view-source:http://...2016-09-20
  • php 调用goolge地图代码

    <?php require('path.inc.php'); header('content-Type: text/html; charset=utf-8'); $borough_id = intval($_GET['id']); if(!$borough_id){ echo ' ...2016-11-25
  • 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
  • JS基于Mootools实现的个性菜单效果代码

    本文实例讲述了JS基于Mootools实现的个性菜单效果代码。分享给大家供大家参考,具体如下:这里演示基于Mootools做的带动画的垂直型菜单,是一个初学者写的,用来学习Mootools的使用有帮助,下载时请注意要将外部引用的mootools...2015-10-23
  • JS+CSS实现分类动态选择及移动功能效果代码

    本文实例讲述了JS+CSS实现分类动态选择及移动功能效果代码。分享给大家供大家参考,具体如下:这是一个类似选项卡功能的选择插件,与普通的TAb区别是加入了动画效果,多用于商品类网站,用作商品分类功能,不过其它网站也可以用,...2015-10-21
  • JS实现自定义简单网页软键盘效果代码

    本文实例讲述了JS实现自定义简单网页软键盘效果。分享给大家供大家参考,具体如下:这是一款自定义的简单点的网页软键盘,没有使用任何控件,仅是为了练习JavaScript编写水平,安全性方面没有过多考虑,有顾虑的可以不用,目的是学...2015-11-08
  • php 取除连续空格与换行代码

    php 取除连续空格与换行代码,这些我们都用到str_replace与正则函数 第一种: $content=str_replace("n","",$content); echo $content; 第二种: $content=preg_replac...2016-11-25
  • php无刷新利用iframe实现页面无刷新上传文件(1/2)

    利用form表单的target属性和iframe 一、上传文件的一个php教程方法。 该方法接受一个$file参数,该参数为从客户端获取的$_files变量,返回重新命名后的文件名,如果上传失...2016-11-25
  • Php文件上传类class.upload.php用法示例

    本文章来人大家介绍一个php文件上传类的使用方法,期望此实例对各位php入门者会有不小帮助哦。 简介 Class.upload.php是用于管理上传文件的php文件上传类, 它可以帮...2016-11-25
  • php简单用户登陆程序代码

    php简单用户登陆程序代码 这些教程很对初学者来讲是很有用的哦,这款就下面这一点点代码了哦。 <center> <p>&nbsp;</p> <p>&nbsp;</p> <form name="form1...2016-11-25
  • php批量替换内容或指定目录下所有文件内容

    要替换字符串中的内容我们只要利用php相关函数,如strstr,str_replace,正则表达式了,那么我们要替换目录所有文件的内容就需要先遍历目录再打开文件再利用上面讲的函数替...2016-11-25
  • PHP实现清除wordpress里恶意代码

    公司一些wordpress网站由于下载的插件存在恶意代码,导致整个服务器所有网站PHP文件都存在恶意代码,就写了个简单的脚本清除。恶意代码示例...2015-10-23
  • PHP文件上传一些小收获

    又码了一个周末的代码,这次在做一些关于文件上传的东西。(PHP UPLOAD)小有收获项目是一个BT种子列表,用户有权限上传自己的种子,然后配合BT TRACK服务器把种子的信息写出来...2016-11-25
  • jQuery实现简单的文件上传进度条效果

    本文实例讲述了jQuery实现文件上传进度条效果的代码。分享给大家供大家参考。具体如下: 运行效果截图如下:具体代码如下:<!DOCTYPE html><html><head><meta charset="utf-8"><title>upload</title><link rel="stylesheet...2015-11-24