所以我有一个PHP脚本,我从html表单上传图像。 php文件如下所示:
<?php
function generateRandomString($length = 10) {
$characters =
'0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$charactersLength = strlen($characters);
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, $charactersLength - 1)];
}
return $randomString;
}
$herman_is_the_best;
if(isset($_POST["place"]) && isset($_POST["submit"])) {
$herman_is_the_best = $_POST["place"];
$target_dir = "../places/" . $herman_is_the_best . "/" ;
$realtarget = $target_dir . generateRandomString() . "." .
pathinfo($target_file,PATHINFO_EXTENSION);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
//check if there is a folder for the location alredy
$direction = "../places/" . $herman_is_the_best . "/";
if(!is_dir($direction)){
//make direction for place
mkdir($direction);
// url encode the address
$address = urlencode($herman_is_the_best);
// google map geocode api url
$url = "https://maps.googleapis.com/maps/api/geocode/json?address=". $address ."&key=AIzaSyDeqk1Oc6TkKQkQph_-P_4U9jTLLJv0G98";
// get the json response
$resp_json = file_get_contents($url);
// decode the json
$resp = json_decode($resp_json, true);
// response status will be 'OK', if able to geocode given address
if($resp['status']=='OK'){
// get the important data
$lati = $resp['results'][0]['geometry']['location']['lat'];
$longi = $resp['results'][0]['geometry']['location']['lng'];
// verify if data is complete
if($lati && $longi){
// put the data in the array
$data_arr = array();
array_push(
$data_arr,
$lati,
$longi
);
}
}
$my_file = '../places/' . $herman_is_the_best .'/cordinates.txt';
$handle = fopen($my_file, 'w') or die('Cannot open file: '.$my_file); //implicitly creates file
$long = $data_arr[0];
$lati = $data_arr[1];
fwrite($handle, $long . "\r\n"
. $lati);
}
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($realtarget)) {
echo "Sorry, there was an error";
$uploadOk = 0;
}
// Check file size
if ($_FILES["fileToUpload"]["size"] > 500000000) {
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"], $realtarget))
{
echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has
been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
}
?>
上传文件的实际部分与w3教程中使用的部分相同。我添加了一些代码,使它成为一个位置文件夹,如果之前没有该位置的位置文件夹,并在一个称为坐标的txt文件中添加该位置的坐标。
奇怪的是,有时文件会上传到父目录,并且不会创建位置文件夹。其他时候会创建场所文件夹,而根本不会上传图像文件。
所以我的问题是这里发生了什么。我不明白为什么它有时会做一件事,而其他时候却没有完全相同的图片。
<form action="upload.php" id="uploadForm" class="" method="post" enctype="multipart/form-data" style="width:100%; height:100%; font-size:400px">
<input type="file" class="inputfile" name="fileToUpload" id="fileToUpload">
<label for="fileToUpload" style="margin-left:35%; margin-top:8%; width:30%; height:16%; text-align:center"> <img style="width:70%; margin-top:6%"src="img/image.svg"></img></label>
<input id="searchTextField" type="text" style="width:32%; height:50px; margin-left:33%; font-size:22pt; margin-top:30%" name="place">
<script>
function initialize() {
var options = {
types: ['(cities)']
};
var input = document.getElementById('searchTextField');
var autocomplete = new google.maps.places.Autocomplete(input, options);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
<input style="width:30%; height:8% ; font-size:23pt; margin-top:40%;
margin-left:35%" type="button" class="btn btn-success "
onclick="submitFirst();" id="connectWorld" value="Connect the world!"
name="submit">
<input id="submitbutton" type="submit" style="display:none"></input>
</form>
有人知道这里的问题是什么吗?
答案 0 :(得分:0)
试试这段代码:
HTML表格:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>File Upload with PHP</title>
</head>
<body>
<form action="fileUpload.php" method="post" enctype="multipart/form-data">
Upload a File:
<input type="file" name="file" id="fileToUpload">
<input type="submit" name="submit" value="Upload File Now" >
</form>
</body>
</html>
PHP脚本:
<?php
$currentDir = getcwd();
$uploadDirectory = "/uploads/";
$errors = []; // Store all foreseen and unforseen errors here
$fileExtensions = ['jpeg','jpg','png']; // Get all the file extensions
$fileName = $_FILES['myfile']['name'];
$fileSize = $_FILES['myfile']['size'];
$fileTmpName = $_FILES['myfile']['tmp_name'];
$fileType = $_FILES['myfile']['type'];
$fileExtension = strtolower(end(explode('.',$fileName)));
$uploadPath = $currentDir . $uploadDirectory . basename($fileName);
if (isset($_POST['submit'])) {
if (! in_array($fileExtension,$fileExtensions)) {
$errors[] = "This file extension is not allowed. Please upload a JPEG or PNG file";
}
if ($fileSize > 2000000) {
$errors[] = "This file is more than 2MB. Sorry, it has to be less than or equal to 2MB";
}
if (empty($errors)) {
$didUpload = move_uploaded_file($fileTmpName, $uploadPath);
if ($didUpload) {
echo "The file " . basename($fileName) . " has been uploaded";
} else {
echo "An error occurred somewhere. Try again or contact the admin";
}
} else {
foreach ($errors as $error) {
echo $error . "These are the errors" . "\n";
}
}
}
?>
作为编写自己的代码的替代方法,请考虑使用开源图像PHP upload库来消除必须编写大量代码的痛苦。