如何获取html中的文件路径在 PHP 中?
有人可以告诉我如何在 PHP 中使用 html 获取文件路径吗?
这是我的代码:
index.php
<form action="csv_to_database.php" method="get" >
<input type="file" name="csv_file" />
<input type="submit" name="upload" value="Upload" />
</form>
和 csv_to_database.php
<?php
if (isset($_GET['csv_file'])) {
$row = 1;
if (($handle = fopen($_GET['csv_file'], "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$num = count($data);
echo "<p> $num fields in line $row: <br /></p>\n";
$row++;
for ($c=0; $c < $num; $c++) {
echo $data[$c] . "<br />\n";
}
}
fclose($handle);
}
}
?>
我的问题是,它仅在以下情况下有效: csv 数据与我的 php 文件位于同一目录中。我想我需要获取文件路径,但我不知道该怎么做。
Can somebody pls tell me how to get the filepath using html <input type="file">
in PHP?
Here are my codes:
index.php
<form action="csv_to_database.php" method="get" >
<input type="file" name="csv_file" />
<input type="submit" name="upload" value="Upload" />
</form>
and in csv_to_database.php
<?php
if (isset($_GET['csv_file'])) {
$row = 1;
if (($handle = fopen($_GET['csv_file'], "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$num = count($data);
echo "<p> $num fields in line $row: <br /></p>\n";
$row++;
for ($c=0; $c < $num; $c++) {
echo $data[$c] . "<br />\n";
}
}
fclose($handle);
}
}
?>
My problem is, it only works when the csv data is in the same directory as my php files. I think I need to get the file path but I don't know how to do it.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您不应该只使用现在拥有的
$_GET
。您的文件位于$_FILES["csv_file"]["tmp_name"]
中。最好你回顾一下本教程,基本上说你需要做这样的事情
:可以从那里去。如果您想从临时位置移动文件,请使用
move_uploaded_file
,教程中也对此进行了说明:)You shouldn't just use the
$_GET
you've got now. Your file is based in$_FILES["csv_file"]["tmp_name"]
.Best you review this tutorial, that basically says you need to do something like this:
And you can go from there. Use
move_uploaded_file
if you want to move the file from the temp location, also explained in the tutorial :)我认为查看以下链接您会受益匪浅: POST 方法上传。
首先,您应该将表单方法更改为
post
,并添加enctype="multipart/form-data"
。然后您可以从
$_FILES['csv_file']['tmp_name']
获取临时文件路径。I think you would gain a lot from taking a look at the following link: POST method uploads.
First of all, you should change your form method to
post
, and addenctype="multipart/form-data"
.Then you can get the temporary file path from
$_FILES['csv_file']['tmp_name']
.在对 fopen 的调用中,使用
$_GET['csv_file']['tmp_name']
- 这指向上传后立即位于服务器上的文件。In your call to fopen, use
$_GET['csv_file']['tmp_name']
- this points to the file on the server immediately after upload.