PHP中require_once引入文件失败问题求助(Windows环境)
Let's break down what's going on here first—you're hitting a super common relative path quirk in PHP:
The relative path in require_once '..\ksUtils.php'; gets resolved relative to the current working directory of the script that's running, not the directory where dbFunctions.php is stored.
When you run register.php (in the frontEnd/ folder), the working directory is D:\Prog\xampp\htdocs\projs\MccoS\frontEnd\. So when dbFunctions.php tries to go up one level with ..\, it lands in D:\Prog\xampp\htdocs\projs\MccoS\—not the backEnd\ folder where ksUtils.php lives. That's why it can't find the file.
The HTTP request method worked because when you hit the script via http://localhost, PHP's working directory defaults to your web root (htdocs), so the relative path resolves correctly to projs/MccoS/backEnd/ksUtils.php.
Fix 1: Use __DIR__ for File-Relative Paths (Recommended)
The __DIR__ constant gives you the absolute path of the directory where the current file (here, dbFunctions.php) is located. This ensures the path is always resolved relative to the file itself, not the working directory.
Update the line in dbFunctions.php to:
require_once __DIR__ . '\..\ksUtils.php';
For cross-platform compatibility (works on both Windows and Linux), you can use PHP's built-in directory separator constant:
require_once __DIR__ . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . 'ksUtils.php';
Alternatively, PHP accepts forward slashes (/) on Windows too, so this simpler version works just fine:
require_once __DIR__ . '/../ksUtils.php';
Fix 2: Set the Include Path
You can add your project's root or backEnd directory to PHP's include_path, so you can reference files relative to that base path.
Add this line at the top of your entry script (register.php):
// Add the project root directory to the include path set_include_path(get_include_path() . PATH_SEPARATOR . realpath(__DIR__ . '\..'));
Then in dbFunctions.php, you can simplify the require line to:
require_once 'backEnd/ksUtils.php';
Fix 3: Use Absolute Paths (Not Recommended for Portability)
If you don't mind hardcoding the path (not ideal if you ever move the project), you can write the full absolute path directly:
require_once 'D:\Prog\xampp\htdocs\projs\MccoS\backEnd\ksUtils.php';
Just note this will break if you move the project to a different directory or server.
内容的提问来源于stack exchange,提问作者user9876350




