Home php教程 php手册 PHP图片上传实例分析[包含预览]

PHP图片上传实例分析[包含预览]

May 25, 2016 pm 04:45 PM
File Upload

图片上传与文件上传在php中都是一样直接使用move_uploaded_file($_FILES["filename"]["tmp_name"]就可以实现了,下面我来给大家分享一个站长分享文件上传例子。

前期需要了解的知识点

move_uploaded_file()文件上传函数

if(move_uploaded_file($_FILES["filename"]["tmp_name"])
{
	echo '文件上传成功';
}
Copy after login

$_FILES php全局变量

$_FILES: 经由 HTTP POST 文件上传而提交至脚本的变量。类似于旧数组 $HTTP_POST_FILES 数组(依然有效,但反对使用)

$_FILES['myFile']['name']   客户端文件的原名称。
$_FILES['myFile']['type']   文件的 MIME 类型,需要浏览器提供该信息的支持,例如"image/gif"。
$_FILES['myFile']['size']   已上传文件的大小,单位为字节。
$_FILES['myFile']['tmp_name']   文件被上传后在服务端储存的临时文件名,一般是系统默认。可以在php.ini的upload_tmp_dir 指定,但用 putenv() 函数设置是不起作用的。
$_FILES['myFile']['error']   和该文件上传相关的错误代码。['error'] 是在 PHP 4.2.0 版本中增加的。下面是它的说明:(它们在PHP3.0以后成了常量)
UPLOAD_ERR_OK             值:0; 没有错误发生,文件上传成功。
UPLOAD_ERR_INI_SIZE      值:1; 上传的文件超过了 php.ini 中 upload_max_filesize 选项限制的值。
UPLOAD_ERR_FORM_SIZE  值:2; 上传文件的大小超过了 HTML 表单中 MAX_FILE_SIZE 选项指定的值。
UPLOAD_ERR_PARTIAL          值:3; 文件只有部分被上传。
UPLOAD_ERR_NO_FILE          值:4; 没有文件被上传。    值:5; 上传文件大小为0.
Copy after login

核心文件:

upimg.htm

<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>上传图片</title>
<script language="javascript">
function $(id) {
	return document.getElementById(id);
}
function ok() {
	$("logoimg").src = $("filename").value;
}
</script>
</head>
<body>
<table border="0" align="center" cellpadding="0" cellspacing="0"> 
  <tr> 
    <td height="45" align="center" valign="middle">
  <form action="uploadf.php?submit=1" method="post" enctype="multipart/form-data" name="form1"> 请选择上传的图片 
   <input type="file" name="filename" id="filename" onchange="ok()"> 
   <!-- MAX_FILE_SIZE must precede the file input field -->
   <input type="hidden" name="MAX_FILE_SIZE" value="30000" />
   <input type="submit" name="Submit" value="上传"> 
  </form>
 </td> 
  </tr> 
</table> 
<font color="red">注意:请上传120*45像素的GIF或者jpg格式的logo图片</font><br/>
logo预览:<img  src="/static/imghw/default1.png"  data-src="images/bg-02.gif"  class="lazy"  id="logoimg" / alt="PHP图片上传实例分析[包含预览] " >
</body>
</html>
Copy after login

调用示例文件:

testUpload.htm

<?php
if (!empty($_GET[submit])) {
    $path = "uploadfiles/pic/"; //上传路径
    //echo $_FILES["filename"]["type"];
    if (!file_exists($path)) {
        //检查是否有该文件夹,如果没有就创建,并给予最高权限
        mkdir("$path", 0700);
    } //END IF
    //允许上传的文件格式
    $tp = array(
        "image/gif",
        "image/pjpeg",
        "image/png"
    );
    //检查上传文件是否在允许上传的类型
    if (!in_array($_FILES["filename"]["type"], $tp)) {
        echo "格式不对";
        exit;
    } //END IF
    if ($_FILES["filename"]["name"]) {
        $file1 = $_FILES["filename"]["name"];
        $file2 = $path . time() . $file1;
        $flag = 1;
    } //END IF
    if ($flag) $result = move_uploaded_file($_FILES["filename"]["tmp_name"], $file2);
    //特别注意这里传递给move_uploaded_file的第一个参数为上传到服务器上的临时文件
    if ($result) {
        //echo "上传成功!".$file2;
        echo "<script language=&#39;javascript&#39;>";
        echo "alert(\"上传成功!\");";
        //echo " location=&#39;add_aaa.php?pname=$file2&#39;";
        echo "</script>";
        echo ("<input type=\"button\" name=\"Submit\" value=\"确定\" onClick=\"window.opener.setFile(&#39;" . $file2 . "&#39;);window.close();\">");
        echo "图片名称:" . $file2;
    } //END IF
    
} else {
    echo "file is null!";
}
?>
调用示例文件:
testUpload.htm
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>上传图片</title>
<script>
function setFile(f1){
   document.frm.logoImg.value=f1;
}
</script>
</head>
<body>
<table border="0" align="center" cellpadding="0" cellspacing="0"> 
  <tr> 
    <td height="45" align="center" valign="middle">
  <form action="#" method="post"  name="frm"> 请选择上传的图片 
        <input name="regAd.logoImg" id="logoImg"   type="text" size="30"/>
    <label style="cursor:hand" onClick="window.open(&#39;upimg.htm&#39;,&#39;上传图片&#39;,&#39;height=200,width=400,top=200,left=200&#39;)">上传图片</label><br/>
  </form>
 </td> 
  </tr> 
</table>
</body>
</html>
Copy after login

此程序不足之处分析

上传预览功能

function $(id) {
	return document.getElementById(id);
}
function ok() {
	$("logoimg").src = $("filename").value;
}
Copy after login

这段代码其实就是一个鸡肋了,在有一些浏览器下是不兼容了,但不会影响到图片上传功能。

程序安全

对于在上传处我们并未进行数据大小限制与程序上传文件类型进行限制,这样可以利用它来上传一些像php文件,这样你的网站就不安全了哦。

本文链接:

收藏随意^^请保留教程地址.

Statement of this Website
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

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 Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Implement file upload and download in Workerman documents Implement file upload and download in Workerman documents Nov 08, 2023 pm 06:02 PM

To implement file upload and download in Workerman documents, specific code examples are required. Introduction: Workerman is a high-performance PHP asynchronous network communication framework that is simple, efficient, and easy to use. In actual development, file uploading and downloading are common functional requirements. This article will introduce how to use the Workerman framework to implement file uploading and downloading, and give specific code examples. 1. File upload: File upload refers to the operation of transferring files on the local computer to the server. The following is used

How to use Laravel to implement file upload and download functions How to use Laravel to implement file upload and download functions Nov 02, 2023 pm 04:36 PM

How to use Laravel to implement file upload and download functions Laravel is a popular PHP Web framework that provides a wealth of functions and tools to make developing Web applications easier and more efficient. One of the commonly used functions is file upload and download. This article will introduce how to use Laravel to implement file upload and download functions, and provide specific code examples. File upload File upload refers to uploading local files to the server for storage. In Laravel we can use file upload

How to solve Java file upload exception (FileUploadException) How to solve Java file upload exception (FileUploadException) Aug 18, 2023 pm 12:11 PM

How to solve Java file upload exception (FileUploadException). One problem that is often encountered in web development is FileUploadException (file upload exception). It may occur due to various reasons such as file size exceeding limit, file format mismatch, or incorrect server configuration. This article describes some ways to solve these problems and provides corresponding code examples. Limit the size of uploaded files In most scenarios, limit the file size

File Uploading and Processing in Laravel: Managing User Uploaded Files File Uploading and Processing in Laravel: Managing User Uploaded Files Aug 13, 2023 pm 06:45 PM

File Uploading and Processing in Laravel: Managing User Uploaded Files Introduction: File uploading is a very common functional requirement in modern web applications. In the Laravel framework, file uploading and processing becomes very simple and efficient. This article will introduce how to manage user-uploaded files in Laravel, including verification, storage, processing, and display of file uploads. 1. File upload File upload refers to uploading files from the client to the server. In Laravel, file uploads are very easy to handle. first,

How to use gRPC to implement file upload in Golang? How to use gRPC to implement file upload in Golang? Jun 03, 2024 pm 04:54 PM

How to implement file upload using gRPC? Create supporting service definitions, including request and response messages. On the client, the file to be uploaded is opened and split into chunks, then streamed to the server via a gRPC stream. On the server side, file chunks are received and stored into a file. The server sends a response after the file upload is completed to indicate whether the upload was successful.

How to implement FTP file upload progress bar using PHP How to implement FTP file upload progress bar using PHP Jul 30, 2023 pm 06:51 PM

How to use PHP to implement FTP file upload progress bar 1. Background introduction In website development, file upload is a common function. For the upload of large files, in order to improve the user experience, we often need to display an upload progress bar to the user to let the user know the file upload process. This article will introduce how to use PHP to implement the FTP file upload progress bar function. 2. The basic idea of ​​implementing the progress bar of FTP file upload. The progress bar of FTP file upload is usually calculated by calculating the size of the uploaded file and the size of the uploaded file.

Simplify file upload processing with Golang functions Simplify file upload processing with Golang functions May 02, 2024 pm 06:45 PM

Answer: Yes, Golang provides functions that simplify file upload processing. Details: The MultipartFile type provides access to file metadata and content. The FormFile function gets a specific file from the form request. The ParseForm and ParseMultipartForm functions are used to parse form data and multipart form data. Using these functions simplifies the file processing process and allows developers to focus on business logic.

PHP file upload guide: How to use the move_uploaded_file function to handle uploaded files PHP file upload guide: How to use the move_uploaded_file function to handle uploaded files Jul 30, 2023 pm 02:03 PM

PHP file upload guide: How to use the move_uploaded_file function to handle uploaded files In developing web applications, file upload is a common requirement. PHP provides a convenient function move_uploaded_file() for processing uploaded files. This article will introduce you how to use this function to implement the file upload function. 1. Preparation Before starting, make sure that your PHP environment has been configured with file upload parameters. You can do this by opening php.in

See all articles