PHP Upload Image

create an HTML form that allow users to choose the image file they want to upload:


enctype="multipart/form-data":
means that no character will be encoded.that is why this type is used while uploading files to server


Example

<!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>


Move uploaded image to folder and display uploaded image


Example

<form method="post" enctype="multipart/form-data">
Select Image:<input type="file" name="image" />

<input type="submit" name="ok" value="click" />
</form>
<?php
if(isset($_POST['ok']))
{
$images=$_FILES['image'] ;
//print_r($images); $name=$images['name'];
$tempath=$images['tmp_name'];
if($name!="")
{
move_uploaded_file($tempath,'newimage/'.$name);
}
?>
<img src="<?php echo 'newimage/'.$name; ?>" height="100" width="100">
<?php
}
?>



Some rules to follow for the HTML form above:
  • Make sure that the form uses method="post"
  • The form also needs the following attribute: enctype="multipart/form-data". It specifies which content-type to use when submitting the form Without the requirements above, the file upload will not work.

    NOTE:

    The type="file" attribute of the <input> tag shows the input field as a file-select control, with a "Browse" button next to the input control