这是我上传函数的启动代码,
function upload()
{
$str_path = "../users/$this->user_name/$this->profile_image";
if (!is_dir("../users")) {
if (!mkdir("../users")) {
throw new Exception("failed to create folder ../users");
}
}
if (!is_dir("../users/$this->user_name")) {
if (!mkdir("../users/$this->user_name")) {
throw new Exception("failed to create folder ../users/$this->user_name");
}
}
}
有一个保存所有网页的主文件夹,即"项目"文件夹。我有一个模型文件夹,其中包含上传功能的类。然后我有一个进程文件夹,从中调用上传函数,它在主"项目"文件夹中创建文件夹并上传文件。
问题是我也在"项目/用户/进程"文件夹中使用相同的功能。上传路径是在上传函数中设置的,但该函数是从两个不同的位置调用的,因此当从"项目/用户/进程"调用时,它会在"项目/用户"文件夹中创建一个文件夹,尽管我需要它创建文件夹并始终在"项目"中上传
多亏了@Masiorama,使用$_SERVER['DOCUMENT_ROOT']解决了这个问题。函数的工作代码
public function upload_profile_image($src_path) {
$base_path = $_SERVER['DOCUMENT_ROOT'] . "/php246/project";
$str_path = "$base_path/users/$this->user_name/$this->profile_image";
if (!is_dir("$base_path/users")) {
if (!mkdir("$base_path/users")) {
throw new Exception("failed to create folder $base_path/users");
}
}
if (!is_dir("$base_path/users/$this->user_name")) {
if (!mkdir("$base_path/users/$this->user_name")) {
throw new Exception("failed to create folder $base_path/users/$this->user_name");
}
}
$result = @move_uploaded_file($src_path, $str_path);
if (!$result) {
throw new Exception("failed to uplaod file");
}
}