-3

I want to use the require_once function inside a php file but whenever i do it creates a fatal error and it halts the script. i have a modules folder where their are 4 folders which are pages, scripts,db and uploads. Inside the pages folder i have a file(home.php) where i want to include the other one in, the other file(connection.php) is inside of the scripts folder. I wrote this in home.php:

<?php
    require_once('../scripts/connection.php');
?>
<section class="p-5">
    <div class="container-lg shadow">
        <?php
                    if(ISSET($_SESSION['success'])){
                ?>
        <div class="alert alert-success">
            <?php echo $_SESSION['success']; header("refresh: 2");?>
        </div>
            <?php
                        unset($_SESSION['success']);
                    }
            ?>
        <div class="row row-cols-1 row-cols-md-3 g-4">
            <div class="col">
                <?php foreach($postSnkr as $rows => $postSnkr) { ?>
                <div class="card">
                    <?php echo("<img src='uploads/".$postSnkr['slika']."'>");?>
                    <div class="card-body">
                        <h5 class="card-title"><?php echo($postSnkr['model'])?></h5>
                        <h6 class="card-subtitle mb-2 text-muted"><?php echo($postSnkr['barva'])?></h6>
                        <ul class="list-group list-group-flush">
                            <li class="list-group-item">Releas date: <?php echo($postSnkr['datum_izdaje']);?>
                            </li>
                            <li class="list-group-item">Size: <?php echo($postSnkr['velikost']);?></li>
                            <li class="list-group-item">Price: <?php echo($postSnkr['cena']);?></li>
                        </ul>
                        <a href="checkout.php" class="btn btn-primary" value="">Buy</a>
                    </div>
                </div>
                <?php } ?>
            </div>
        </div>
    </div>

</section>

in connection.php:

<?php
        
        if(!is_file('db/sneaker_haven.sqlite3')){
            file_put_contents('db/sneaker_haven.sqlite3', null);
        }

        $conn = new PDO('sqlite:db/sneaker_haven.sqlite3');

        $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
?>

and in index.php:

<body>
    <div class="container-fluid">
        <div class="wave"></div>
        <div class="wave"></div>
        <div class="wave"></div>
        <?php
            require_once("modules/pages/header.php");     
        ?>
        <br>
        <div class="container my-5">
                <?php
                    if(isset($_GET['page'])){
                        switch ($_GET['page']) {
                            case "login":
                                require_once("modules/pages/login.php");
                                break;
                            case "reg":
                                require_once("modules/pages/register.php");
                                break;
                            case "create_post":
                                require_once("modules/pages/create_post.php");
                                break;
                            case "profile":
                                require_once("modules/pages/profile.php");
                                break;
                            case "home":
                                require_once("modules/pages/home.php");
                                break;
                            default:
                                # code...
                                break;
                        }
                    }
                    if(isset($_SESSION['loggedin']) && $_SESSION['loggedin'] == true){
                        require_once("modules/pages/home.php");
                    }elseif(isset($_SESSION['loggedin']) && $_SESSION['loggedin'] == false){
                        require_once("modules/pages/login.php");
                    }
                ?>
        </div>
        <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/js/bootstrap.bundle.min.js" integrity="sha384-w76AqPfDkMBDXo30jS1Sgez6pr3x5MlQ1ZAGC+nuZB+EYdgRZgiwxhTBTkF7CXvN" crossorigin="anonymous"></script>
</body>

I tried to use the require_once function inside of home.php but it did not work it halted the script error message: Closed without sending a request; it was probably just an unused speculative preconnection

fetal error:

require_once(../../modules/scripts/connection.php): Failed to open stream: No such file or directory in /home/gogi/Desktop/sc/Online-sneaker--Marketplace/modules/pages/home.php on line 2

[Thu Feb 23 19:37:46 2023] PHP Fatal error:  Uncaught Error: Failed opening required '../../modules/scripts/connection.php' (include_path='.:/usr/share/php') in /home/gogi/Desktop/sc/Online-sneaker--Marketplace/modules/pages/home.php:2
Stack trace:
#0 /home/gogi/Desktop/sc/Online-sneaker--Marketplace/index.php(48): require_once()
#1 {main}
  thrown in /home/gogi/Desktop/sc/Online-sneaker--Marketplace/modules/pages/home.php on line 2

[Thu Feb 23 19:37:46 2023] 127.0.0.1:59784 [500]: GET /index.php - Uncaught Error: Failed opening required '../../modules/scripts/connection.php' (include_path='.:/usr/share/php') in /home/gogi/Desktop/sc/Online-sneaker--Marketplace/modules/pages/home.php:2
Stack trace:
#0 /home/gogi/Desktop/sc/Online-sneaker--Marketplace/index.php(48): require_once()
#1 {main}
  thrown in /home/gogi/Desktop/sc/Online-sneaker--Marketplace/modules/pages/home.php on line 2
Your Common Sense
  • 156,878
  • 40
  • 214
  • 345
Gogo
  • 21
  • 4
  • Closed without sending a request; it was probably just an unused speculative preconnection – Gogo Feb 23 '23 at 19:03
  • note requires's are relative from where they are included from not where they sit in the directory tree, so could be that `require_once('../scripts/connection.php');` should be `require_once('./scripts/connection.php');` – Lawrence Cherone Feb 23 '23 at 19:05
  • 2
    You could try is to use the `__DIR__` to get the absolute path to your current directory. `require_once(__DIR__ . '/../scripts/connection.php');` – Wahyu Kristianto Feb 23 '23 at 19:11
  • @WahyuKristianto it sill just convert your WRONG relative path to WRONG absolute path. The `__DIR__` constant isn't a magic wand that finds your file wherever it is. You still have to provide a CORRECT path in the first place. – Your Common Sense Feb 24 '23 at 06:12
  • @Gogo your database file suffers from the same problem. Always use absolute paths, based on either document root or a constant defined in index,php – Your Common Sense Feb 24 '23 at 06:19

1 Answers1

-1

I highly recommend the use of include paths and the setting of them with set_include_path. In my personal framework on top of everything I include (with require_once) one setup script which as itself also includes various stuff. These things are:

  • set autoloading
  • set error handling
  • determine SSL and environment (dev, test, live)
  • set include paths
  • start session
  • start localizer
  • start debugging

By default I add some paths to the include path array. I have a function for it which perserves the current paths and adds newpaths in front of the old ones. If you need new paths, you can add them later. Here is the function:

function addPaths(array $newpaths): void
{
    $oldpathsstr = get_include_path();
    $oldpaths = $oldpathsstr ? explode(PATH_SEPARATOR, $oldpathsstr) : [];
    set_include_path(implode(PATH_SEPARATOR, array_unique(array_merge($newpaths, $oldpaths))));
}

So you can add one or more paths simultaneously. Just put them in an array:

addPaths(['/my/path'])

For your task you could do maybe:

addPaths(['../modules/pages', '../modules/scripts'])

For my personal experience, I avoid using relative paths, but if you use them you could try Wayhu's hint with __DIR__. I personally use absolute paths, of course based on $_SERVER['DOCUMENT_ROOT']. So if you want to hide your modules from direct access from the user, you would place your modules folder on the same level of DOCUMENT_ROOT and do something like:

define('BASE', realpath($_SERVER['DOCUMENT_ROOT'].'/..'));

addPaths([BASE.'/modules/pages', BASE.'/modules/scripts'])

Then just include your scripts with:

require_once('connection.php');

include('login.php');

You should avoid files with the same name in different include paths, but if you do that, the file in the first path which is found would be used.

Edit:
Of course you could keep it simple without using my function:

define('BASE', realpath($_SERVER['DOCUMENT_ROOT'].'/..'));

set_include_path(BASE.'/modules/pages:'.BASE.'/modules/scripts:.:/usr/share/php')
Aranxo
  • 677
  • 4
  • 15
  • I fail to see how include paths is useful at all, especially when autoloading is used, – Your Common Sense Feb 24 '23 at 06:07
  • @YourCommonSense Well, maybe you don't want to have everything in classes, especially maybe the templates. For small websites a big framework, in which everything is object-oriented, in my opinion can be overkill. Besides that the OP seems not to use objects, so in this case include paths can be useful. – Aranxo Feb 26 '23 at 18:25
  • Include path is never useful if you know where your file is. And you should know that. – Your Common Sense Feb 26 '23 at 21:08
  • I think thats a matter of personal taste, not of good or bad practice. – Aranxo Feb 27 '23 at 11:21
  • Not at all. it's a matter of good or bad practices. Not knowing where an included file is makes your code muddled and hard to develop and debug. May be for a 2-page app it's sort of ok, but for a professional app it's just unacceptable. Not to mention that there could be a confusion when there will be two files with same name – Your Common Sense Feb 27 '23 at 11:23
  • Of course you should know where your include file is. But you can spare a lot of typing and can have more overview with include paths. But you should not overdo it. In my framework I have only three include paths, that should be enough. And of course you should avoid files with the same name. – Aranxo Feb 27 '23 at 11:37