jcadima
8/28/2017 - 4:06 PM

Form with file upload (single upload)

Form with file upload (single upload)



======== dbconfig.php =========
<?php
$dsn = 'mysql:host=localhost;dbname=singlefileupload';
$username = 'root';
$password = '';




================= index.php  ====================
<?php
// require DB config + constants
require "dbconfig.php";  

if($_SERVER['REQUEST_METHOD'] == 'POST') { 

	echo 'POST ARRAY<pre>';
	print_r($_POST); 
	echo '</pre>';
	echo "<br>====================<br>";

	echo 'FILES ARRAY<pre>';
	print_r($_FILES); 
	echo '</pre>';
	echo "<br>====================<br>";

	echo 'Detailed info:<br>';
	echo $_FILES['filelogo']['name']  . '<br>' ;
	echo $_FILES['filelogo']['type'] . '<br>' ;
	echo $_FILES['filelogo']['tmp_name'] .'<br>' ;
	echo $_FILES['filelogo']['error'] .'<br>' ;
	echo $_FILES['filelogo']['size'] .'<br>' ;

// exit;

	try {
		$db = new PDO($dsn, $username, $password);

		// specify the directory 
		$targetDir = "fileuploads/";

		// Allow only these extensions
		$allowed = ['gif','png', 'jpg'] ;

		// Get the extension name
		$extension = explode('.', $_FILES['filelogo']['name'] ) ;
		$extension = strtolower(end($extension) ) ;

		// POST values
		$name = $_POST['name'] ;
		$email = $_POST['email'] ;
		$file_name = $_FILES['filelogo']['name']; // cherry_blossom.jpg
		$targetFile = $targetDir.$file_name;  // fileuploads/cherry_blossom.jpg 

		if( in_array($extension, $allowed) && move_uploaded_file( $_FILES['filelogo']['tmp_name'] ,  $targetFile ) ) {
			//insert file information into db table


			// INSERT SINGLE PRODUCT
		    $query = 'INSERT INTO singleupload (  name, email, file_name, dateuploaded  )
		              VALUES  ( :name, :email, :file_name, :dateuploaded ) ';
		    $statement = $db->prepare($query);
		    $statement->bindValue(':name', $name );
		    $statement->bindValue(':email', $email );
		    $statement->bindValue(':file_name', $file_name );
		    $statement->bindValue(':dateuploaded', date("Y-m-d H:i:s") );
		    // $statement->execute(); 
		    $statement->execute() or die(print_r( $statement->errorInfo(), true) );
		    echo '<h2>FILE INSERT SUCCESSFUL</h2>';
		    $statement->closeCursor();


		}

	} catch (PDOException $e) {
		// print trace
	    $error_message = $e->getMessage();
	    exit();
	}

}


?>



<!DOCTYPE html>
<html>
<head>
	<meta charset=utf-8 />
	<title></title>

	<script src="https://code.jquery.com/jquery-1.8.3.js"></script>
	<!--[if IE]>
		<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
	<![endif]-->
</head>
<body>
 
<form method="post" action="" enctype="multipart/form-data">
	<div><input type="text" name="name" placeholder="Full Name"></div>
	<div><input type="text" name="email" placeholder="Email"></div>
	<div><input id="filelogo" type="file" name="filelogo"></div>
	<p><br></p>
	<img id="showimage" src="" height="200" alt="Image preview...">  
	<input type="submit" value="SUBMIT"> 
</form>


</body>



<script>


$("#filelogo").change(function() {
	var preview = document.querySelector('#showimage');
	var file    = document.querySelector('input[type=file]').files[0];
	var reader = new FileReader();

	// console.log(file) ;	
	
    if( $('#filelogo').val() !=""){
	    // readURL function is redundant so we just use reader.onload if the file size is less than 1MB
	    // 'this'  refers to the current file object
	     // check if file size is greater than 1MB OR file is not an image
        if (file.size>=1000000 || file['type'].split('/')[0] !='image'  ) {
	        alert("File Size is more than 1MB OR File is not an image") ;
        }
        else {  
	        
			reader.addEventListener("load", function () {
			    preview.src = reader.result;
			}, false);	        
	           
        
			if ( file ) {   reader.readAsDataURL(file);    }
			   
        }   

    }
    
    /* optional
	   triggers when a file selection is cancelled or there is no image currently selected
    */

    /*
    else {
	    // 
	    console.log("File selection cancelled, loading default placeholder.png") ;
	    $('#showimage').attr('src','https://regigo.com/beta/organizer/images/placeholder.png');
	}  
	*/
    
    
    

});



</script>


</html>


================== DATABASE SCHEMA ===========================

Field           Type	        NULL    KEY    Default    Extra
------------------------------------------------------------------------
id              int(11)         NO      PRI    NULL       auto_increment
name            varchar(100)    NO             NULL
email           varchar(100)    NO             NULL
file_name       varchar(100)    NO             NULL
dateuplaoded    date            NO             NULL