0

I'm making a system for adding files to a database. I use a form:

<form action="insert.php" method="post" enctype="multipart/form-data">
Fil: <input type="file" name="file" id="file">
Titel: <input type="text" name="titel" /><br />
Längd (min): <input type="text" name="langd" /><br />
Medverkande: <input type="text" name="medverkande" /><br />
Reporter: <input type="text" name="reporter" /><br />
Fotograf: <input type="text" name="fotograf" /><br />
Sökord: <input type="text" name="sokord" /><br />
<input type="submit" />
</form>

The code in insert.php:

<?php
$con = mysql_connect("database","user","password");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

mysql_select_db("165666-kltvplay", $con);

$filnamn = $_FILES["file"]["name"] ;
$sql="INSERT INTO Blad1 (ProgramID, Titel, Langd, Medverkande, Reporter, Fotograf, Sokord)
VALUES
('$filnamn','$_POST[titel]','$_POST[langd]','$_POST[medverkande]','$_POST[reporter]','$_POST[fotograf]','$_POST[sokord]')";

if (!mysql_query($sql,$con))
  {
  die('Error: ' . mysql_error());
  }
echo "En ny film inlagd: <br> ";
echo $filnamn;

mysql_close($con);
?>

But when I add the file it seems to be uploading the whole file because there is a % counter in my browser and it's taking a loooong time to complete(the files are qute big). I just want the name of the file inserted into the database (and that is working) but not to upload the whole file.

And is it possible to add just the name and not the file exetension?

  • I don't know why you would ever need to do that because the server will not have access to a file that is on your computer and not on the server. Meaning the server will not be able to "serve" that file to other visitors. It will only be able to tell you what the name was. – Mihai Stancu Jan 31 '13 at 11:00
  • [pathinfo()](http://php.net/manual/en/function.pathinfo.php) –  Jan 31 '13 at 11:07

1 Answers1

1

You'll have to do some JavaScript magic. Once the user has selected a file, you can read the file name:

var fileName = document.getElementById('file').value;

Then put that value into a hidden input field (that is inside your form):

document.getElementById('hidden-filename').value = fileName;

Then hook into the form's submit event and remove the file input so it won`t get submitted.

On the server you read the value of the hidden-filename (or whatever the name) and insert it into the DB.

Be warned though that not all browsers will return the actual file path. The name of the file will be correct, but the path may not be.

Also note that you won't be able to do anything with this file then (on the server or on the client).

AS for the last question you had (no extension), look at this: PHP, get file name without file extension

Community
  • 1
  • 1
Jan Hančič
  • 53,269
  • 16
  • 95
  • 99