0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

No.1 新卒未経験エンジニアがPHPでテキストファイルダウンロード実装した時にソースコードが含まれてしまう問題に取り組んでみた

Last updated at Posted at 2017-10-02

未経験新米エンジニアが日々の業務で直面した問題や、日々インプットした知識をアウトプットしていきます。

PHPでファイルのアップロードとダウンロードが出来るツールを作った際に起きた問題について書き置きしておきます。
フレームワークはdietcakeを使っており、PHPのバージョンは5.6です。

まず起きたこととしてはタイトルにある通り、テキストファイルをダウンロードした際に下記のようなコードが、ダウンロードしたテキストファイルに含まれてしまっていたことです。

混入してしまうソースコード
<html lang="ja">
<head>
    <meta charset="utf-8">
    <title>サイトタイトル</title>
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="format-detection" content="telephone=no">
    <meta name="viewport" content="width=1220">
    <meta name="aaaaaa" content="aaaaaaa">
    <link rel="shortcut icon" href="http://aaaa.bbb">
    <script src="http://aaaa.bbb"></script>
    <script>WebFont.load({google: {families: ['Roboto', 'Roboto Condensed']}});</script>
    <script src="http://aaaa.bbb"></script>
</head>
<body>
</body>
</html>

色々調べてみたのですが、原因特定には至らず、、、
ちなみにダウンロード処理のコードは

index.php
$file_name = "test.txt";
$length = filesize("text.php");

header('Content-Type: application/force-download');
header('Content-Length: ' . $length);
header('Content-Disposition: attachment; filename="' . $file_name . '"');

readfile($file_name);

少し変えていますが大体こんな感じです。

結果から言うと、phpファイルの最後に

exit();

を加えるだけで解決しました。
おそらく、処理をexitしていなかったために、readfile後もそのまま処理が継続して行われ、コントローラーのアクションに対するビューのHTMLコードが一緒に出力されてしまったのではないかな、と推測しております。

調べても具体的な解決方法などあまり出てこなかったので投稿しておきます。

間違っていたり、補足などあればどうぞ宜しくお願い致します。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?