Q:

How to get file name before upload and pass to another text input field without fakepath

I want to upload an image in a folder (on server) and want to get image name on file input select and pass this image name to another text input field without fakepath. here is my code :
This is file upload php code
<?php

if (($_FILES['my_file']['name']!="")){
// Where the file is going to be stored
$target_dir = "upload/";
$file = $_FILES['my_file']['name'];
$path = pathinfo($file);
$filename = $path['filename'];
$ext = $path['extension'];
$temp_name = $_FILES['my_file']['tmp_name'];
$path_filename_ext = $target_dir.$filename.".".$ext;

// Check if file already exists
if (file_exists($path_filename_ext)) {
echo "Sorry, file already exists.";
}else{
move_uploaded_file($temp_name,$path_filename_ext);
echo "Congratulations! File Uploaded Successfully.";
}
}
?>

This is json file write code
<?php
$message = '';
$error = '';

if(isset($_POST["submit"]))
{

if(empty($_POST["filename"]))
{
$error = "<label class='text-danger'>some text </label>";
}

else
{
if(file_exists('jasonfile.json'))
{
$current_data = file_get_contents('jasonfile.json');
$array_data  = json_decode($current_data, true);

$item = array

( 
'ImageUrl'        =>     $_POST["filename"]
);
array_unshift($array_data["user"] , $item);

$final_data  = json_encode($array_data);
if(file_put_contents('jasonfile.json', $final_data)){
}}
else{
$error = 'JSON File not exits';
}}}
?>

This is my form html code
I want to get image file name and pass to 2nd text input field as value
<!DOCTYPE html>
<html>
<head></head>
<body>
<div class="container" style="width:500px;">
<h3 align="center">Upload YOUR file in folder</h3>
<form action = "?" method="post" enctype ="multipart/form-data">
<?php

?>

<form name="form" method="post" enctype="multipart/form-data" >
<input type="file" name="my_file" onchange="this.form.filename.value = this.value" /> 
<input type="text" name="filename" />
<input type="submit" name="submit" value="Upload"/>
</form>

</form>
</div>
</body>
</html>

Thanks in advance :)

A:

You can implement change event of iput file and get e.target.files[0].name;

$('input[type="file"]').change(function(e){
        var fileName = e.target.files[0].name;
        $('[name=filename]').val(fileName.replace(/C:\\fakepath\\/i, ''));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form name="form" method="post" enctype="multipart/form-data" >
<input type="file" name="my_file" onchange="this.form.filename.value = this.value" /> 
<input type="text" name="filename" />
<input type="submit" name="submit" value="Upload"/>
</form>

