PHP下载的唯一文件


PHP download unique file

我正在尝试创建一个带有坐标的GPX文件,然后由用户下载。第一部分创建文件(正在工作)。但我似乎无法下载。我希望这个文件是动态创建并下载的,这样当多个用户使用该服务时,他们的文件就永远无法交换。

我想我应该把我的数据放在一个变量中,而不是放在文件中,但这样我可以测试它是否有效。

我是编码新手,一定会出错;)

提前谢谢大家。

以下是我迄今为止所拥有的;

<?php
// set_include_path("http://localhost/The%20Road%20Planner/tempMap/");
// $filename = uniqid('route.') . '.gpx';
$myfile = fopen('route.gpx', 'w') or die("Unable to open file!");

$route = (isset($_POST['RoutePath']) ? $_POST['RoutePath'] : null);

fwrite($myfile, '<?xml version="1.0" ?>' . '<gpx version="1.0" creator="Fabrication Junkies" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.topografix.com/GPX/1/0" xsi:schemaLocation="http://www.topografix.com/GPX/1/0 http://www.topografix.com/GPX/1/0/gpx.xsd">' . PHP_EOL . '<trk>' . PHP_EOL .
 '<name>Map</name>' . PHP_EOL . '<trkseg>'.PHP_EOL);
$coordinates = json_decode($route, true);

foreach($coordinates as $pair) {
  $output = '<trkpt lat="' . $pair['lat'] .'" lon="'. $pair['lng'] . '"></trkpt>' . PHP_EOL;
  fwrite($myfile, $output);
}
fwrite($myfile, '</trkseg>' . PHP_EOL . '</trk>' . PHP_EOL . '</gpx>');
fclose($myfile);
 header("Content-type: application/gpx+xml");
 header("Content-Disposition: attachment;Filename=route.gpx");
 echo "<xml>";
// your gpx data here
$myfile
 echo "</xml>";
?>

您必须为文件创建不同的名称。您可以将SESSION_ID添加到文件名:

<?php
$filename = session_id().'route.gpx';
$myfile = fopen($filename, 'w') or die("Unable to open file!");
?>

如果用户已登录,您可以将用户id添加到文件名中:

<?php
$filename = $user_id.'route.gpx';
?>

如果您需要在同一目录中创建文件,并且不想混合名称,可以使用uniqid()函数来创建唯一的文件名,比如这个

// preparing unique file name with time prefix
$prefix = uniqid(); // generates a uniqueId based on the microtime
$filePath = $prefix . "_route.gpx";
// opening and writing data inside
$myfile = fopen($filePath, 'w');
... fwrite() what you need inside
fclose($myfile);
// out as download
header("Content-type: application/gpx+xml");
header("Content-Disposition: attachment;Filename=route.gpx");
readfile($filePath);

你可以在这里阅读更多关于php uniqid()的信息-http://www.w3schools.com/php/func_misc_uniqid.asp