问题
Hello I was trying to upload a photo from a website I made, to the website's hosting server's folder directory (/public_html/upload/) using php. but the folder always shows up empty. I dont know what am I doing wrong. can anyone help?
this is the html file:
<div id = "forms">
<form action="add_data.php" method="post" form enctype="multipart/form-data">
<div id = "info1">
<p> <h2> Accident Report Form </h2> </p>
</div>
<div id = "info2"><p> Please fill in the form below to report an accident </p></div>
<ol>
<li> <label for = "name" > Name: </label>
<input "type = "text" name = "name" id = "name"/> </li>
<li> <label for = "location" > Location of the accident: </label>
<input "type = "text" name = "location" id = "location" /> </li>
<li> <label for = "road" > Road Name: </label>
<input "type = "text" name = "road" id = "road"/> </li>
<li> <label for = "image" > Image: </label>
<input type="file" name="photo"><br> </li>
</ol>
<div id = "submit"><button type="submit" >Submit</button> </div><br>
</form>
</div>
And, this is the add_data.php file:
<?php
$target = "/public_html/upload";
$target = $target . basename( $_FILES['photo']['name']);
$pic=($_FILES['photo']['name']);
?>
回答1:
Imporved working Code:
<?php
$target = "/public_html/upload/";
$target = $target .$_FILES['photo']['name'];
$pic=($_FILES['photo']['tmp_name']);
move_uploaded_file($pic, $target);
?>
回答2:
I have updated your code to work.
HTML - is ok but could be formatted better, try a online formatter tool
http://jsbeautifier.org/.
Also, form opening tag should look like this
<form action="add_data.php" method="post" enctype="multipart/form-data">
PHP - Explanation provided in the comments
<?php
// Uploaded file will be stored in a temporary location and needs to
// be moved to a destination directory and given the original filename
//-----------------------------------------------------------------
// prepare target pathname
//
$target = "/public_html/upload";
$targetName = $_FILES['photo']['name'];
// get temp file name
//
$tmp = $_FILES['photo']['tmp_name'];
// use php's move_uploaded_file() function
// to copy temp file to final destination
move_uploaded_file($tmp, $targetDir . $targetName);
来源:https://stackoverflow.com/questions/28520260/how-to-upload-photo-to-my-hosting-server-folder-directory