В этой статье приведен пример работы с файлами PHP. Поделитесь для вашей справки следующим образом:
1. Загрузка файла
Загрузить домен: вход
Обычные текстовые поля (текст, пароль, область текста, радио, флажок и т.д.): Отправляйте данные на сервер в виде байтовых потоков
Файл: Отправка файла в двоичной кодировке в прошлое очень проста в реализации, и ее нужно только добавить в тег формы. enctype="составные/данные формы"
____________
После того, как клиент отправит файл, сервер примет его с помощью $_FILES
Так называемая загрузка файла заключается в перемещении временного файла, показанного выше, в указанное место назначения.
Функция использования move_uploaded_file( файл,новый путь) Возвращает значение bool
1.1 Случай загрузки файла
// for example move_uploaded_file($_FILES['myfile']['tmp_name'], 'd:/upload/');
1.2 Не допускайте слишком большой загрузки файлов
знания
1 ГБ 1 МБ 1 КБ
$max_size = 3 * 1024 * 1024; // Constraint 3M
if($_FILES['myfile']['size'] > $max_size){
Echo'uploads pictures larger than 3M';
exit;
}
// upload
if(move_uploaded_file($_FILES['myfile']['tmp_name'], $path)){
Echo'upload success';
} else {
Echo'failed upload';
}Обратите внимание, что php .ini файлы могут изменять ограничения на загрузку файлов: разрешить ли загрузку, загрузку во временный каталог, максимальное ограничение файлов, максимальное количество загрузок за раз
1.3 Предотвращение перезаписи файлов
1. На стороне сервера мы проверяем, что при перемещении в пункт назначения мы можем избежать дублирования имен файлов, используя случайные числа для именования новых файлов. 2. Сохранение папок по дате
1.4 Определяет тип загружаемого файла
Общее требование is:.Jpg.png.gif формат изображения
Чтобы предотвратить изменение и загрузку суффиксов файлов, Finfo может быть расширен PHP для получения более точных типов файлов.
// To prevent users from modifying file suffixes, an extended Finfo implementation of PHP is used # 1. Open PHP extension in php.ini extension=php_fileinfo.dll # 2. Using Extended Classes to Get the Real Type of Uploaded Files $finfo = new Finfo(FILEINFO_MIME_TYPE); $mime_type = $finfo->file($_FILES['myfile']['tmp_name']);
Самоинкапсулированный класс загружаемых файлов
/*
* Description: File upload class
* Author: SGW
* Time: 2018-7-31
*/
class Upload
{
// Membership attributes
Private $_maxsize = 2 * 1024 * 1024; // Upload file maximum range 2M
Private $_upload_path ='upload/'; // Upload file save path
Private $_prefix='odshen_'; // prefix of filename
Private $allow_type = array ('.jpg','.png','.gif','.jpeg'); and // file type that allows upload
private $allow_mime_type = array('image/jpeg','image/png','image/gif','image/jpg');
/**
* Set Sets Private Properties
*@ param [str] $p [attribute name]
*@ param [mix] $v [assign values to attributes]
*/
public function __set($p,$v)
{
if(property_exists($this,$p)){
$this -> $p = $v;
}
}
/**
* get gets private properties
*@ param [str] $p [attribute name]
*/
public function __get($p)
{
if(property_exists($this,$p)){
return $this -> $p;
}
}
/**
* Upload File Method
*@ param [mix] $file [uploaded file]
*/
public function doUpload($file)
{
// Judging the size of files uploaded by users
$max_size = $this - > Max size; // maximum constraint is 2M
if($file['size'] > $max_size){
Echo'upload files too large, re-upload';
exit;
}
# Prevent uploaded files from being overwritten
$prefix = $this->_prefix;
// File name unique
$filename = uniqid($prefix,true);
// File suffix to intercept strrchr after the last point from the uploaded file name
$ext = strrchr($file['name'],'.');
// Subdirectory saves uploaded files and saves them in date format
$sub_path = $this->_upload_path.date('Ymd').'/'; // upload/20180731/
# If the current directory does not exist, you need to create the absolute path first.
$now_path = __DIR__.'/';
$now_path = str_replace('\','/',$now_path.$sub_path);
if(!is_dir($now_path)){
mkdir($now_path,0777,true);
}
# Restrict file types uploaded by users
if(!in_array($ext,$this->allow_type)){
Echo'File type is not supported';
exit;
}
# To prevent users from modifying the suffix of files, an extended Finfo implementation of PHP is used to obtain the exact type of each file in the network.
$finfo = new Finfo(FILEINFO_MIME_TYPE);
$mime_type = $finfo -> file($file['tmp_name']);
if(!in_array($mime_type,$this->allow_mime_type)){
Echo'File type is not supported';
exit;
}
// Parametric 1: Files to be moved (temporary files)
// Parametric 2: Destination
// Returns the result Boolean type
if(move_uploaded_file($file['tmp_name'],$now_path.$filename.$ext)){
// If the upload succeeds in returning the uploaded file address to facilitate the use of the picture elsewhere, you need to be able to find the picture.
return $sub_path . $filename.$ext;
}else{
// echo'failed upload';
return false;
}
}
}2. Загрузка файла
Большие файлы загружаются с помощью стороннего программного обеспечения, такого как Baidu cloud disk и Xunlei; если файлы небольшие, загрузите их напрямую с помощью php.
Достаточно следующего метода
// First receive the name of the file passed in the address bar, that is, which file is downloaded.
$filename = $_GET['filename'];
if($filename==''){
Echo'File not found, download failed';
exit;
}
// Path of Stitching Files
$full_name = 'img/'.$filename;
// The picture is GBK coded under Windows system, and the PHP file is UTF-8 coded.
// Usually you need to change the encoding of the PHP file to GBK first
$full_name = iconv('utf-8','gbk',$full_name);
$filesize = filesize($full_name);
# [Main] Start downloading and tell the browser through the header header that I'm responding to file resources.
// The returned file
header("Content-type: application/octet-stream");
// Returns by byte size
header("Accept-Ranges: bytes");
// Display file size
header("Content-Length: $filesize");
// Here the client pop-up dialog box, the corresponding file name
header("Content-Disposition: attachment; filename=".$filename);
// Start reading file resources and respond to browsers
$fp = fopen($full_name,'r');
while(!feof($fp)){
$data = fread($fp,1024);
echo $data;
}
fclose($fp);3. Категория подкачки
Объединение начальной загрузки
/*
* Paging Display Data
*/
class Page
{
Private $_total; // Total number of records
Private $_pagesize; // Number of records displayed per page
Private $_pagenow; // Current page number
Private $_url; // The URL address that jumps when clicking on a hyperlink
/**
* Set Sets Private Properties
*@ param [str] $p [attribute name]
*@ param [mix] $v [assign values to attributes]
*/
public function __set($p,$v)
{
if(property_exists($this,$p)){
$this -> $p = $v;
}
}
/**
* get gets private properties
*@ param [str] $p [attribute name]
*/
public function __get($p)
{
if(property_exists($this,$p)){
return $this -> $p;
}
}
// Dynamic creation of paging navigation bar
public function create()
{
// Define Home Button
// Current page highlighting
$first_active = $this->_pagenow == 1?'active':'';
$url = $this -> _url.'?page=';
$first = 1;
$PAGE = <<
Больше читателей, интересующихся контентом, связанным с PHP, могут ознакомиться с темами этого сайта: Краткое описание работы с файлами PHP, Краткое описание навыков работы с каталогами PHP, Краткое описание часто используемых алгоритмов и методов обхода в PHP, Курс структуры данных и алгоритмов PHP, Краткое описание алгоритмов программирования PHP и краткое описание навыков сетевого программирования PHP.
Я надеюсь, что эта статья будет полезна для разработки PHP – программ для всех.