user83879
0
Q:

basic code for file upload in php

<?php
	if(isset($_POST['upload_file'])){		
		$target_dir = "uploaded_files/";
		$target_file = $target_dir . basename($_FILES["select_file"]["name"]);
		$uploadOk = 1;
		$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
		
		$new_name = $target_dir."test_data.".$imageFileType;
		
		if($imageFileType != "jpg"){
			echo "File type is not supported";
		}
		else{
			if(file_exists($target_file)){
				echo "Sorry this file is already exists";
				// for file deletion
				// unlink($target_file);
				// echo "file is deleted";
			}
			else{
				if(move_uploaded_file($_FILES["select_file"]["tmp_name"], $new_name)){
					echo "your file has been successfully uploaded";
				}
				else{
					echo "please check your file";
				}
			}
		}
	}
	else{
		echo "kindly select the file for upload";
	}
?>
2
//This is the minimal code for an image upload for first time learners
//html portion
<!DOCTYPE html>
<html>
<head>
	<title>ImageUpload</title>
</head>
<body>
	<form action="upload.php" method="post" enctype="multipart/form-data">
		<label>Username</label>
		<input type="text" name="username">
		<br>
		<label>UploadImage</label>
		<input type="file" name='myfile'>
		<br/>
		<input type="submit" value="upload">
	</form>
</body>
</html>
  
 //php portion
  <?php
	$user=$_POST['username'];
	$image=$_FILES['myfile'];
	echo "Hello $user <br/>";
	echo "File Name<b>::</b> ".$image['name'];

	move_uploaded_file($image['tmp_name'],"photos/".$image['name']);
	//here the "photos" folder is in same folder as the upload.php, 
	//otherwise complete url has to be mentioned
	?>
0

New to Communities?

Join the community