search
HomeBackend DevelopmentPHP TutorialPHP file upload form is extracted from drupal code_PHP tutorial

drupal文件上传表单的例子

复制代码 代码如下:

function upload_form() {
$form = array();
// If this #attribute is not present, upload will fail on submit
$form['#attributes']['enctype'] = 'multipart/form-data';
$form['file_upload'] = array(
'#title' => t('Upload file'),
'#type' => 'file',
);
$form['submit_upload'] = array(
'#type' => 'submit',
'#value' => 'Submit'
);
return $form;
}
function upload_submit($form, &$form_state) {
$validators = array();
$dest = file_directory_path();
$file = file_save_upload('file_upload', $validators, $dest);
//$file will be 0 if the upload doesn't exist, or the $dest directory
//isn't writable
if ($file != 0) {
$file->filepath; // 文件相对路径
}
else {
form_set_error('myform', t("Failed to save the file."));
}
}

PHP文件上传功能代码实例教程
在PHP网站开发中,PHP程序如何实现文件上传功能,一直是新手的课题。而且文件上传功能一般都用得着,比如图片上传。今天就结合具体代码实例和详细注解和大家分享如何编写PHP文件上传代码,适合php初学者学习。
  PHP代码实例主要讲述的是图片上传,看懂程序后你可以修改相关文件类型就可以实现其他文件的上传功能。
编程环境
  PHP5.2.4,基本上PHP4.3以上版本,此代码都可以使用
准备工作
  检查upload_tmp_dir项
  如果PHP的开发环境是自行搭建的,你需要在编写文件上传程序前编辑php.ini文件,找到并编辑upload_tmp_dir选项,此项用来设定文件上传至服务器时的临时文件夹,比如upload_tmp_dir = E:/phpos/uploads,然后再重启Apache。如果PHP的开发环境使用的是傻瓜式一键安装包,一般upload_tmp_dir都是设定好了的,你也可以用phpinfo()函数查看下配置。
  编写一个upload文件,设定文件上传表单
复制代码 代码如下:



  



注意
  1、表单中enctype=”multipart/form-data”必须指定,以便让服务器知道文件带有常规的表单信息。
  2、必须有一个可以设置上传文件最大长度的表单区域,即允许上传文件的最大值(按字节计算),它是隐藏值域,即max_file_size,通过设置其Value(值)可以限制上传文件的大小,避免用户在花时间等待上传大文件之后才发现该文件太大了的麻烦。但是一般别人可以绕过这个值,所以安全起见,最好是在php.ini文件中配置upload_max_filesize选项,设定文件上传的大小,默认是2M。
文件上传程序
复制代码 代码如下:

function uploadfile($type,$name,$ext,$size,$error,$tmp_name,$targetname,$upload_dir)
{
$MAX_SIZE = 2000000;
$FILE_MIMES = array('image/pjpeg','image/jpeg','image/jpg','image/gif','image/png');
$FILE_EXTS = array('.jpg','.gif','.png','.JPG','.GIF','.PNG');
$file_path = $upload_dir.$targetname;
if(!is_dir($upload_dir))
{
if(!mkdir($upload_dir))
die("文件上传目录不存在并且无法创建文件上传目录");
if(!chmod($upload_dir,0755))
die("文件上传目录的权限无法设定为可读可写");
}
if($size>$MAX_SIZE)
die("上传的文件大小超过了规定大小");
if($size == 0)
die("请选择上传的文件");
if(!in_array($type,$FILE_MIMES) || !in_array($ext,$FILE_EXTS))
die("请上传符合要求的文件类型");
if(!move_uploaded_file($tmp_name, $file_path))
die("复制文件失败,请重新上传");
switch($error)
{
case 0:
return ;
case 1:
die("上传的文件超过了 php.ini 中 upload_max_filesize 选项限制的值");
case 2:
die("上传文件的大小超过了 HTML 表单中 MAX_FILE_SIZE 选项指定的值");
case 3:
die("文件只有部分被上传");
case 4:
die("没有文件被上传");
}
}

Parameter Description
$type, $name, $size, $error, $tmp_name correspond to the relevant variables in the global variable $_FILES, that is:
$_FILES['userfile']['type']: The MIME type of the file requires the browser to provide support for this information, such as the image type "image/gif".
$_FILES['userfile']['name']: The original name of the client file.
$_FILES['userfile']['size']: The size of the uploaded file, in bytes.
$_FILES['userfile']['tmp_name']: The temporary file name stored on the server after the file is uploaded.
$_FILES['userfile']['error']: The error code related to the file upload, that is,
Value: 0: No error occurred, the file upload was successful.
Value: 1: The uploaded file exceeds the limit of the upload_max_filesize option in php.ini.
Value: 2: The size of the uploaded file exceeds the value specified by the MAX_FILE_SIZE option in the HTML form.
Value: 3: Only part of the file was uploaded.
Value: 4: No files were uploaded.
$ext: Upload file extension
$targetname: The final file name after uploading
$upload_dir: Which directory to upload to, using a relative path
Comments:
No. 3 Line ~ Line 6: Set the size of the image file to upload, as well as the MIME type and extension of the file. Since this code is an image file upload program, all image types are listed in the two arrays, such as PNG, GIF, and JEPG. wait.
Line 17~Line 24: If the file is empty, size is equal to 0; if the extension or type of the image file does not match, it will jump out.
Line 26: The function of the move_uploaded_file function is to move the file in the server temporary directory set by upload_tmp_dir to the file specified by $file_path. Note that if the target file already exists, the target file will be overwritten
How to upload multiple document? For example, to upload 3 files at the same time
just copy the code
as follows:


changed to


Copy the code The code is as follows:




Correspondingly, when calling this function, $_FILES['userfile']['name'][0] represents the related files of the first file information, and so on, and so on.
Summary
This function is the simplest core code in PHP file upload. Image upload is just one of them. You only need to modify or expand the relevant information of the $FILE_MIMES and $FILE_EXTS arrays to achieve other types of file uploads. Function. On the periphery of the function, you can write other related codes according to your own needs to achieve other functions, such as association with the database, etc.

http://www.bkjia.com/PHPjc/322934.html

truehttp: //www.bkjia.com/PHPjc/322934.htmlTechArticleDrupal file upload form example copy code The code is as follows: function upload_form() { $form = array(); / / If this #attribute is not present, upload will fail on submit $form['#attri...
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
PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

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

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

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

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.

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

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.

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor