upload file from php code example

Example 1: php upload file

<?php
   if(isset($_FILES['image'])){
      $errors= array();
      $file_name = $_FILES['image']['name'];
      $file_size =$_FILES['image']['size'];
      $file_tmp =$_FILES['image']['tmp_name'];
      $file_type=$_FILES['image']['type'];
      $file_ext=strtolower(end(explode('.',$_FILES['image']['name'])));
      
      $extensions= array("jpeg","jpg","png");
      
      if(in_array($file_ext,$extensions)=== false){
         $errors[]="extension not allowed, please choose a JPEG or PNG file.";
      }
      
      if($file_size > 2097152){
         $errors[]='File size must be excately 2 MB';
      }
      
      if(empty($errors)==true){
         move_uploaded_file($file_tmp,"images/".$file_name);
         echo "Success";
      }else{
         print_r($errors);
      }
   }
?>

Example 2: php image upload in database

<?php
error_reporting(0);
?>
<?php
$msg = "";

// If upload button is clicked ...
if (isset($_POST['upload'])) {

	$filename = $_FILES["uploadfile"]["name"];
	$tempname = $_FILES["uploadfile"]["tmp_name"];
		$folder = "image/".$filename;

	$db = mysqli_connect("localhost", "root", "", "image_upload");

		// Get all the submitted data from the form
		$sql = "INSERT INTO images (filename) VALUES ('$filename')";

		// Execute query
		mysqli_query($db, $sql);

		// Now let's move the uploaded image into the folder: image
		if (move_uploaded_file($tempname, $folder)) {
			$msg = "Image uploaded successfully";
		}else{
			$msg = "Failed to upload image";
	}
}
$result = mysqli_query($db, "SELECT * FROM images");
?>

<!DOCTYPE html>
<html>
<head>
<title>Image Upload</title>
<link rel="stylesheet" type= "text/css" href ="style.css"/>
<div id="content">

<form method="POST" action="" enctype="multipart/form-data">
	<input type="file" name="uploadfile" value=""/>

	<div>
		<button type="submit" name="upload">UPLOAD</button>
		</div>
</form>
</div>
</body>
</html>

Example 3: php upload

// To change: FILENAME, array with allowed extensions, Max Filesite, Filepath
if(upload("FILENAME", array("jpeg","jpg","png"), 209715, "C:/xampp/htdocs/")){
        echo "Success";
    }


function upload($f_name, $f_ext_allowed, $f_maxsize, $f_path){

      $f_name_2 = $_FILES[$f_name]['name'];
      $f_size  =  $_FILES[$f_name]['size'];
      $f_tmp   =  $_FILES[$f_name]['tmp_name'];
      $f_error =  $_FILES[$f_name]['error'];
      $f_ext   = strtolower(end(explode('.',$f_name_2)));
      $f_rename = $_SESSION['uid'] . "." . $f_ext;

        if($f_error == 0 && in_array($f_ext, $f_ext_allowed) 
        && $f_size < $f_maxsize && mb_strlen($f_name_2, "UTF-8") < 225 
        && preg_match("`^[-0-9A-Z_\.]+$`i", $f_name_2)){
            if(move_uploaded_file($f_tmp, $f_path . $f_name_2){
                return true;
            }else{
                return false;
            }
        }else{
            return false;
        }
}

Tags:

Css Example