1

I have a local file that I need included in a beginning Silex application. I just got started and I have all the boiler plate code setup - particularly here.

// I need to return test.php for this route
$app = new Silex\Application();
$app->get('/', function() use($app) {
    return $string;  // put the file in a string
});
$app->run();

After some googling I found these articles: SO, PHP.net

So it looks like I can use file_get_contents() and if I need the code evaluated I could wrap it in eval(). Or I could use the other method shown in the link.

I was hoping to just use something similar to require(), but Silex needs a string returned. I imagine I could just write my own helper function parseFile() but this has to be done somewhere else already?

Update

// this does not work, I'v verified the path is correct.
return file_get_contents($path, TRUE);
Community
  • 1
  • 1
  • Is the file static text or php code? Does it work if you return the contents with `new \Symfony\Component\HttpFoundation\Response(file_get_contents($path));` – kylehyde215 Mar 05 '15 at 20:24
  • currently it is static text, but I'm looking for a PHP solution long term - the file_get_contents() solution I noted does not work. Why are you using `HttpFoundation`? This is a local file. I made the question more clear. –  Mar 05 '15 at 20:28
  • Silex uses HttpFoundation for requests/responses, and I believe when you just return a string from a controller, silex is just wrapping that in a HttpFoundation\Response. You could probably just create a subclass of Response that does the ob_get_contents thing in the constructor. Then you could just do something like `return new FileContentsResponse('path/to/file.php');`. – kylehyde215 Mar 05 '15 at 20:59

2 Answers2

0

Maybe this?

ob_start();
require 'somefile.php';
$contents = ob_get_contents();
ob_end_clean();
return $contents;
kylehyde215
  • 1,216
  • 1
  • 11
  • 18
0

The docs are a bit hard to navigate but here they are with the appropriate anchor -

Sensio Labs Documentation

As you suggested there is a more direct way.

You basically need to use the aptly named sendFile() method.

$app->get('/files/{path}', function ($path) use ($app) {
    if (!file_exists('/base/path/' . $path)) {
        $app->abort(404);
    }

    return $app->sendFile('/base/path/' . $path);
});
cade galt
  • 3,843
  • 8
  • 32
  • 48