php icon indicating copy to clipboard operation
php copied to clipboard

Struggling to get pages to load

Open goup-david opened this issue 3 years ago • 8 comments

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": "[email protected]"
        }
    },
    "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.

goup-david avatar Apr 27 '22 17:04 goup-david

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.

f3l1x avatar Apr 27 '22 17:04 f3l1x

Hi,

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

{
    "functions": {
        "api/*.php": {
            "runtime": "[email protected]"
        }
    },
    "routes": [
        { "src": "/(.*)",  "dest": "/api/index.php" }
      ]
}

goup-david avatar Apr 28 '22 10:04 goup-david

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

f3l1x avatar Apr 28 '22 10:04 f3l1x

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

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

goup-david avatar Apr 28 '22 11:04 goup-david

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

goup-david avatar May 03 '22 09:05 goup-david

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.

f3l1x avatar May 03 '22 09:05 f3l1x

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?

goup-david avatar May 03 '22 13:05 goup-david

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

f3l1x avatar May 03 '22 13:05 f3l1x