PHP 上传图片

Sheeraz Gul 2023年1月30日
  1. 在 PHP 中启用从 php.ini 文件上传文件以上传图像
  2. 在 PHP 中使用文件上传操作上传图像
PHP 上传图片

我们可以使用简单的文件上传操作在 PHP 中上传图像,但首先,应该从 php.ini 文件启用文件上传。本教程演示如何在 PHP 中上传图像。

在 PHP 中启用从 php.ini 文件上传文件以上传图像

对于较新版本的 PHP,文件上传默认为 on。你还可以从 php.ini 文件编辑文件上传配置。

下面是如何设置配置。

允许 HTTP 文件上传。

file_uploads = On

设置上传文件的最大允许大小。

upload_max_filesize = 2M

设置通过单个请求上传的最大文件数。

max_file_uploads = 20

在 PHP 中使用文件上传操作上传图像

根据上述配置,图像大小应低于 2 兆字节。下面的代码具有检查所选文件是否为图像的验证。

<form action="" method="post" enctype="multipart/form-data">
    <input type="file" name="image" >
    <input type="submit" value="upload" name="upload">
</form>
<?php
if(isset($_POST['upload'])){
    $input_image=$_FILES['image']['name'];
    $image_info = @getimagesize($input_image);
    if($image_info == false){
	    echo "The selected file is not image.";
    }
    else{

	    $image_array=explode('.',$input_image);
        $rand=rand(10000,99999);
        $image_new_name=$image_array[0].$rand.'.'.$image_array[1];
        $image_upload_path="uploads/".$image_new_name;
        $is_uploaded=move_uploaded_file($_FILES["image"]["tmp_name"],$image_upload_path);
        if($is_uploaded){
            echo 'Image Successfully Uploaded';
	    }
        else{
            echo 'Something Went Wrong!';
        }
    }
}
?>

上面的代码通过同一页面上的表单上传文件。首先,它验证所选文件是否为图像,然后上传。

输出:

用 PHP 上传图片

作者: Sheeraz Gul
Sheeraz Gul avatar Sheeraz Gul avatar

Sheeraz is a Doctorate fellow in Computer Science at Northwestern Polytechnical University, Xian, China. He has 7 years of Software Development experience in AI, Web, Database, and Desktop technologies. He writes tutorials in Java, PHP, Python, GoLang, R, etc., to help beginners learn the field of Computer Science.

LinkedIn Facebook

相关文章 - PHP Image