search
HomeBackend DevelopmentPHP Tutorialphp上传图片到服务器

php文件上传中会用到$_FILES系统函数

一、$_FILES系统函数

PHP编程语言中的常见的$_FILES系统函数用法有:
$_FILES['myFile']['name'] 显示客户端文件的原名称。
$_FILES['myFile']['type'] 文件的 MIME 类型,例如"image/gif"。
$_FILES['myFile']['size'] 已上传文件的大小,单位为字节。
$_FILES['myFile']['tmp_name'] 储存的临时文件名,一般是系统默认。

二、常见函数

PHP编程语言中的常见的$_FILES系统函数用法有:

$_FILES['myFile']['name'] 显示客户端文件的原名称。

$_FILES['myFile']['type'] 文件的 MIME 类型,例如"image/gif"。

$_FILES['myFile']['size'] 已上传文件的大小,单位为字节。

$_FILES['myFile']['tmp_name'] 储存的临时文件名,一般是系统默认。

$_FILES['myFile']['error'] 该文件上传相关的错误代码。以下为不同代码代表的意思:

0; 文件上传成功。

1; 超过了文件大小php.ini中即系统设定的大小。

2; 超过了文件大小MAX_FILE_SIZE 选项指定的值。

3; 文件只有部分被上传。

4; 没有文件被上传。

5; 上传文件大小为0。

三、php文件上传

通过form上传文件,首先需要标记

enctype="multipart/form-data" method="post">。下面的html代码:


商家店铺名:

联系电话:

QQ:

广告语:

上传封面图:(建议320*120)

商家简介:
 

|


php代码如下:

<?php /** * Created by PhpStorm. * User: funmi * Date: 14-9-10 * Time: 下午6:57 */include_once('./common.php');if($_SGLOBAL['login']==true){    $cover_pic = upload_store_pic();    $store_name = $_POST['sjname'];    $tel_number = $_POST['sjphone'];    $ad_words = $_POST['sjad'];    $store_introduce = $_POST['sjbrief'];    $qq_number = $_POST['sjqq'];    $setarr=array(        'cover_pic'=>$cover_pic,        'store_name'=>$store_name,        'tel_number'=>$tel_number,        'ad_words'=>$ad_words,        'store_introduce'=>$store_introduce,        'qq_number'=>$qq_number    );    updatetable(tname('open_member_weixin_ap'),$setarr,array('apid'=>$_COOKIE['apid'],'id'=>$_COOKIE['id']));    $smarty->assign('loginuser',$_COOKIE['loginuser']);    $smarty->display('setting.dwt');    exit();}gourl('binding.php');function upload_store_pic(){    //文件保存路径    $save_path = './uploads/store_pic/';    if (!file_exists($save_path)) {        mkdir($save_path);    }    //定义允许上传的文件扩展名    $ext_arr = array(        'image' => array('gif', 'jpg', 'jpeg', 'png', 'bmp')    );    //最大文件大小    $max_size = 1000000;    //PHP上传失败    if (!empty($_FILES['img_file']['error'])) {        switch($_FILES['img_file']['error']){            case '1':                $error = '超过php.ini允许的大小。';                break;            case '2':                $error = '超过表单允许的大小。';                break;            case '3':                $error = '图片只有部分被上传。';                break;            case '4':                $error = '请选择图片。';                break;            case '6':                $error = '找不到临时目录。';                break;            case '7':                $error = '写文件到硬盘出错。';                break;            default:                $error = '未知错误。';        }        showmessage($error);        return '';    }    //有上传文件时    if (empty($_FILES) === false) {        //原文件名        $file_name = $_FILES['img_file']['name'];        //服务器上临时文件名        $tmp_name = $_FILES['img_file']['tmp_name'];        //文件大小        $file_size = $_FILES['img_file']['size'];        //检查文件名        if (!$file_name) {            showmessage("请选择文件。");            return '';        }        //检查目录        if (@is_dir($save_path) === false) {            showmessage("上传目录不存在。");            return '';        }        //检查目录写权限        if (@is_writable($save_path) === false) {            showmessage("上传目录没有写权限。");            return '';        }        //检查是否已上传        if (@is_uploaded_file($tmp_name) === false) {            showmessage("上传失败。");            return '';        }        //检查文件大小        if ($file_size > $max_size) {            showmessage("上传文件大小超过限制。");            return '';        }        //检查目录名        $dir_name = empty($_GET['dir']) ? 'image' : trim($_GET['dir']);        if (empty($ext_arr[$dir_name])) {            showmessage("目录名不正确。");            return '';        }        //获得文件扩展名        $temp_arr = explode(".", $file_name);        $file_ext = array_pop($temp_arr);        $file_ext = trim($file_ext);        $file_ext = strtolower($file_ext);        //检查扩展名        if (in_array($file_ext, $ext_arr[$dir_name]) === false) {            showmessage("上传文件扩展名是不允许的扩展名。");            return '';        }        //新文件名        $new_file_name = date("YmdHis") . '_' . rand(10000, 99999) . '_apid_' . $_COOKIE['apid'] . '.' . $file_ext;        //移动文件        $file_path = $save_path . $new_file_name;        if (move_uploaded_file($tmp_name, $file_path) === false) {            showmessage("上传文件失败。");            return '';        }        @chmod($file_path, 0777);        return $file_path;    }else{        return '';    }}


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
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

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 Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools