[英]How do I set relative paths in PHP?
我有一個絕對的路徑(經過驗證的工作)
$target_path = "F:/xampplite/htdocs/host_name/p/$email.$ext";
用於
move_uploaded_file($_FILES['ufile']['tmp_name'], $target_path
但是,當我移動到生產服務器時,我需要一個相對路徑:
如果/archemarks
位於服務器的根目錄中,那么這是正確的路徑。 但是,做這樣的事情往往更好:
$new_path = dirname(__FILE__) . "/../images/" . $new_image_name;
這將獲取當前文件運行的目錄,並將圖像保存到與其處於同一級別的名為images
的目錄中。
在上面的例子中,當前運行的文件可能是:
/var/www/archemarks/include/upload.php
圖像目錄是:
/var/www/archemarks/images
例如,如果/images
是兩個目錄級別高於當前運行的文件,請使用
$new_path = dirname(__FILE__) . "/../../images/" . $new_image_name;
$target_path = __DIR__ . "/archemarks/p/$email.$ext";
$target_path = "archemarks/p/$email.$ext";
注意第一個“/”
/ =>絕對,像/ home
沒有“/”=>相對於當前文件夾
這是一條絕對的道路。 相對路徑不以/
開頭。
如果這是生產服務器上的正確路徑,那么PHP可能正在chroot
運行。 這是服務器配置問題。
下面是我用相對路徑編寫的php文件上傳器的代碼。 希望能幫助到你。 在這種情況下,上傳文件夾與我的php文件在同一個目錄中。 你可以使用../上升幾個級別並進入另一個目錄
<?php
if(function_exists("date_default_timezone_set") and function_exists("date_default_timezone_get"))
@date_default_timezone_set('America/Anchorage');
ob_start();
session_start();
// Where the file is going to be placed
$target_path = "uploads/" . date("Y/m/d") . "/" . session_id() . "/";
if(!file_exists( $target_path )){
if (!mkdir($target_path, 0755, true))
die("FAIL: Failed to create folders for upload.");
}
$maxFileSize = 1048576*3.5; /* in bytes */
/* Add the original filename to our target path.
Result is "uploads/filename.extension" */
$index = 0;
$successFiles = array();
$failFiles = null;
$forceSend = false;
if($_SESSION["security_code"]!==$_POST["captcha"]){
echo "captcha check failed, go back and try again";
return;
}
foreach($_FILES['attached']['name'] as $k => $name) {
if($name != null && !empty($name)){
if($_FILES['attached']['size'][$index] < $maxFileSize ) {
$tmp_target_path = $target_path . basename( $name );
if(move_uploaded_file($_FILES['attached']['tmp_name'][$index], $tmp_target_path)) {
$successFiles[] = array("file" => $tmp_target_path);
} else{
if($failFiles == null){
$failFiles = array();
}
$failFiles[] = array ("file" => basename( $name ), "reason" => "unable to copy the file on the server");
}
} else {
if($failFiles == null){
$failFiles = array();
}
$failFiles[] = array ("file" => basename( $name ), "reason" => "file size was greater than 3.5 MB");
}
$index++;
}
}
?>
<?php
$response = "OK";
if($failFiles != null){
$response = "FAIL:" . "File upload failed for <br/>";
foreach($failFiles as $k => $val) {
$response .= "<b>" . $val['file'] . "</b> because " . $val['reason'] . "<br/>";
}
}
?>
<script language="javascript" type="text/javascript">
window.top.window.uploadComplete("<?php echo $response; ?>");
</script>
假設/ archemarks目錄直接位於文檔根目錄下 - 並且您的示例表明它是 - ,您可以使代碼獨立於特定的操作系統或環境。 嘗試使用
$target_path = $_SERVER['DOCUMENT_ROOT'] . "/archemarks/p/$email.$ext";
作為目標位置的通用路徑。 應該工作正常。 此表示法也與腳本的位置或當前工作目錄無關。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.