京东6.18大促主会场领京享红包更优惠

 找回密码
 立即注册

QQ登录

只需一步,快速开始

利用PHP实现图片上传接口的实例代码

2024-11-4 06:49| 发布者: 2ae29| 查看: 149| 评论: 0

摘要: 目次弁言情况准备创建数据库创建图片上传接口测试图片上传接口弁言 在Web开发中,图片上传是一个常见的功能。无论是用户头像的上传,还是内容的图片插入,都必要利用到图片上传的功能。在这篇文章中,我们将具体介绍
目次

弁言

在Web开发中,图片上传是一个常见的功能。无论是用户头像的上传,还是内容的图片插入,都必要利用到图片上传的功能。在这篇文章中,我们将具体介绍怎样利用PHP实现图片上传接口。

情况准备

首先,我们必要一个运行PHP的情况。这里我们利用的是XAMPP,它是一个包含了Apache、MySQL、PHP和Perl的开源Web应用服务器。

创建数据库

我们必要一个数据库来存储上传的图片信息。这里我们利用MySQL数据库,创建一个名为images的数据库,并在其中创建一个名为image_info的表,用于存储图片的信息。

[code]CREATE DATABASE images; USE images; CREATE TABLE image_info ( id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255) NOT NULL, path VARCHAR(255) NOT NULL, type VARCHAR(255) NOT NULL, size INT NOT NULL, upload_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP ); [/code]

创建图片上传接口

接下来,我们创建一个PHP文件,名为[code]upload.php[/code],用于处置处罚图片的上传。

[code]<?php $target_dir = "uploads/"; $target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]); $uploadOk = 1; $imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION)); // Check if image file is a actual image or fake image if(isset($_POST["submit"])) { $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]); if($check !== false) { echo "File is an image - " . $check["mime"] . "."; $uploadOk = 1; } else { echo "File is not an image."; $uploadOk = 0; } } // Check if file already exists if (file_exists($target_file)) { echo "Sorry, file already exists."; $uploadOk = 0; } // Check file size if ($_FILES["fileToUpload"]["size"] > 500000) { echo "Sorry, your file is too large."; $uploadOk = 0; } // Allow certain file formats if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" && $imageFileType != "gif" ) { echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed."; $uploadOk = 0; } // Check if $uploadOk is set to 0 by an error if ($uploadOk == 0) { echo "Sorry, your file was not uploaded."; // if everything is ok, try to upload file } else { if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) { echo "The file ". htmlspecialchars( basename( $_FILES["fileToUpload"]["name"])). " has been uploaded."; } else { echo "Sorry, there was an error uploading your file."; } } ?> [/code]

测试图片上传接口

最后,我们可以创建一个HTML文件,包含一个表单,用于上传图片。当我们选择一张图片并点击提交按钮时,我们的图片上传接口就会被调用。

[code]<!DOCTYPE html> <html> <body> <form action="upload.php" method="post" enctype="multipart/form-data"> Select image to upload: <input type="file" name="fileToUpload" id="fileToUpload"> <input type="submit" value="Upload Image" name="submit"> </form> </body> </html> [/code]

到此这篇关于利用PHP实现图片上传接口的方法的文章就介绍到这了,更多相关PHP图片上传接口内容请搜刮脚本之家以前的文章或继续浏览下面的相关文章盼望大家以后多多支持脚本之家!


来源:https://www.jb51.net/program/318079wfc.htm
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!
关闭

站长推荐上一条 /6 下一条

QQ|手机版|小黑屋|梦想之都-俊月星空 ( 粤ICP备18056059号 )|网站地图

GMT+8, 2025-7-1 20:52 , Processed in 0.028735 second(s), 18 queries .

Powered by Mxzdjyxk! X3.5

© 2001-2025 Discuz! Team.

返回顶部