PHP上传图片
1 链接数据库
<?php
$server = "localhost";
$user = "root";
$password = "root";
$db = "shoping";
function connect($servername,$username,$password,$dbname){
$conn = mysqli_connect($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("连接失败: " . $conn->connect_error);
}else{
return $conn;
}
};
?>
2 编写上传方法
<?php
function moveimg($file,$path,$name){
if(move_uploaded_file($file,$path.'/'.$name)){
echo 'yes';
}else{
echo 'no';
}
}
?>
3 上传并存入数据库
<?php
header('Content-Type: text/html;charset=utf-8');
header('Access-Control-Allow-Origin:*');
include('../flieControl/moveimg.php');
include('../mysql/linksql.php');
$conn = connect($server,$user,$password,$db );
$filepath = '/Applications/phpstudy/WWW/shopingdb/img/';
$file = $_FILES['file']['tmp_name'];
$filename = $_FILES['file']['name'];
$PATH = $filepath.$_POST['class'];
$path = file_exists($PATH);
if($path){
moveimg($file,$PATH,$filename);
}else{
mkdir($PATH,0777,true);
moveimg($file,$PATH,$filename);
}
?>