Skip to content
Advertisement

PHP image upload function, save in a dir and then return save image 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']));

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"];
           }
       }
   }
}

Advertisement

Answer

Here’s a simple one.

HTML form to upload image

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

Your PHP file that does the Upload

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

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement