vercel-community / php

🐘 PHP Runtime for ▲ Vercel Serverless Functions (support 7.4-8.3)
https://php.vercel.app
MIT License
1.26k stars 292 forks source link

Struggling to get pages to load #229

Open goup-david opened 2 years ago

goup-david commented 2 years ago

Question

Struggling to load pages and files that are not the main index.php file.

This is my file structure:

MyPHPProject
    - index.php
    - vercel.json
    - api
        - index.php
    - another-page
        - index.php

Below is my vercel.json file:

{
    "functions": {
        "api/*.php": {
            "runtime": "vercel-php@0.4.0"
        }
    },
    "routes": [
        { "src": "/(.*)",  "dest": "/api/index.php" }
      ]
}

This is my api/index.php file:

<?php include __DIR__ . '/../index.php'; ?>

This is my index.php file (in main route):

<html>
    <head></head>

<body>

<div class="testbackground">
    <a href="/another-page">Another Page</a>

    <h1>Hello there!</h1>

    <?php include __DIR__ . '/another-page/index.php'; ?>
</div>
</body>
</html>

My another-page/index.php file is:

<h1>This better work</h1>

When I go to my server I get the following:

Another Page
Hello there!
This better work

However when I go to /another-page, it doesn't load the correct index.php file.

Any help is much appreciated.

f3l1x commented 2 years ago

Hi. There is only one entrypoint to your app and it's in /api/index.php according to your setup. Just place a little router to /api/index.php and that should work.

goup-david commented 2 years ago

Hi,

Isn't that what I already have in my vercel.json file:

{
    "functions": {
        "api/*.php": {
            "runtime": "vercel-php@0.4.0"
        }
    },
    "routes": [
        { "src": "/(.*)",  "dest": "/api/index.php" }
      ]
}
f3l1x commented 2 years ago

Well, can you prepare a MVP and share the code?

goup-david commented 2 years ago

I've made the repo public see here: https://github.com/goup-david/testingphp

The vercel link is https://testingphp.vercel.app/

goup-david commented 2 years ago

@f3l1x any chance you got a look at this? Would really appreciate the help

f3l1x commented 2 years ago

Your api/index.php should contain something like:

if (str_starts_with($_SERVER['REQUEST_URI'], '/another-page') {
  require __DIR__ . '/../another-page/index.php';
} else {
  require __DIR__ . '/../index.php';
}

You must route that by your own. Because everything is pointing to your /api/index.php.

goup-david commented 2 years ago

How does that work with regards to style sheets? Within my code directory I have a file style.css, and within my index.php I include it:

However the file doesn't get called and if I go to /style.css it brings up the index.php page?

f3l1x commented 2 years ago

Take a look how Laravel devs solve it: https://github.com/juicyfx/vercel-php/issues/207#issuecomment-1007984117