本文介绍了PHP图像上传功能,保存在目录中,然后返回保存图像URL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用PHP将图像上传到服务器,并将其保存在目录中,然后返回图像url.
I am trying to upload an image to server using PHP and the save inside a dir, and then returning the image url.
HTML:
<input name="photo" type="file" />
PHP
save_string_to_database( upload_img($_POST['photo']));
我对PHP不太了解,我从SO那里得到了一个代码,但是它什么也没做.请帮助我修复此代码,或提供一个简单的代码来执行上传:
I have not much idea of PHP, I got a code from SO, but it did not do anything. Kindly help me to fix this code, or give a simple code to perform an upload:
function upload_img($img){
if ((($_FILES[$img]["type"] == "image/gif")
|| ($_FILES[$img]["type"] == "image/jpeg")
|| ($_FILES[$img]["type"] == "image/pjpeg")
|| ($_FILES[$img]["type"] == "image/jpg")
|| ($_FILES[$img]["type"] == "image/png"))
&& ($_FILES[$img]["size"] < 20000)
&& (strlen($_FILES[$img]["name"]) < 51)){
if ($_FILES[$img]["error"] > 0){
echo "Return Code: " . $_FILES[$img]["error"];
}
else{
// echo "Upload: " . $_FILES["image"]["name"] . "<br />";
// echo "Type: " . $_FILES["image"]["type"] . "<br />";
// echo "Size: " . ($_FILES["image"]["size"] / 1024) . " Kb<br />";
// echo "Temp file: " . $_FILES["image"]["tmp_name"] . "<br />";
if (file_exists(THEME_DIR."/images/" . $_FILES[$img]["name"])){
echo $_FILES[$img]["name"] . " already exists. ";
}
else{
move_uploaded_file($_FILES[$img]["tmp_name"],THEME_DIR."/images/" . $_FILES[$img]["name"]);
return THEME_DIR."/images/" . $_FILES[$img]["name"];
}
}
}
}
推荐答案
这是一个简单的例子.
HTML表单以上传图片
<form enctype="multipart/form-data" action="upload.php" method="POST">
<input type="hidden" name="MAX_FILE_SIZE" value="512000" />
Send this file: <input name="userfile" type="file" />
<input type="submit" value="Send File" />
</form>
您执行上传的PHP文件
<?php
$uploaddir = '/var/www/uploads/';
$uploadfile = $uploaddir . basename($_FILES['userfile']['name']);
echo "<p>";
if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
echo "File is valid, and was successfully uploaded.\n";
} else {
echo "Upload failed";
}
echo "</p>";
echo '<pre>';
echo 'Here is some more debugging info:';
print_r($_FILES);
print "</pre>";
?>
Source
这篇关于PHP图像上传功能,保存在目录中,然后返回保存图像URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!