Pregunta

un poco de fondo:

Tengo nuestro sitio web de la iglesia en el plan de alojamiento compartido de Godaddy. Mientras odio Windows y mudaría el sitio a un servidor basado en Linux, esta no es mi cuenta de alojamiento, así que no puedo hacer eso. Actualmente estoy tratando de implementar una GUI para cargar sermones al sitio web. Sé cómo hacer esto en un servidor Linux, así que pensé que el código de Windows sería similar. El único lugar que me estoy atascando es el camino de carga. El camino absoluto en nuestro servidor de Godaddy es

D:\Hosting\5402716\html\WFBC\wacofamily.com\sermons\2014\

Sin embargo, la barra posterior escapa de caracteres especiales, así que pensé que necesitaba dos.

D:\\Hosting\\5402716\\html\\WFBC\\wacofamily.com\\sermons\\2014\\

El problema:

Luego probé la carga, pero recibo este error:

Se recibió el siguiente mensaje a nivel del sistema: permisos o archivo de error relacionado con el archivo en movimiento a d: alojamiento, 02716htmlwfbcwacofamily.comsermons4wfbc20130106am.mp3

Parece que el PHP está eliminando todas las barras invertidas, excepto \ 54 y \ 201. Según este sitio , \ 54 es una coma y 201 no está utilizada (o en blanco). Esto explica por qué estoy recibiendo la coma y el 201 en 2014 está desapareciendo. Pero no explica por qué la doble barra invertida no se convierte en una sola barra invertida. Aquí está el script PHP que se supone que debe subir la imagen:

<?php
    error_reporting(E_ALL);
    ini_set('display_errors', 'on');
    require_once 'authorize.php';
    if(!(strtolower($this_user_type) == 'admin') && !(strtolower($this_user_type) == 'administrator') && !(strtolower($this_user_type) == 'elder')) {
        header('Location: /login.php?message=You%20do%20not%20have%20permission%20to%20view%20this%20page.%20%20You%20are%20a(n)%20'.$this_user_type.'.');
        exit;
    }
    ini_set('upload_max_filesize', '20971520');
    ini_set('post_max_size', '20971520');
    ini_set('memory_limit', '20971520');
    ini_set('max_input_time', 360);
    ini_set('max_execution_time', 360);
    require_once 'appConfig.php';
    require_once 'databaseConnection.php';
    $php_errors = array(1 => 'Maximum file size in php.ini exceeded', 2 => 'Maximum file size in HTML form exceeded', 3 => 'Only part of the file was uploaded', 4 => 'No file was selected to upload.');
    $article_id = htmlentities(trim($_REQUEST['sermon_id']));
    $date = htmlentities(trim($_REQUEST['date']));
    $pastor = htmlentities(trim($_REQUEST['pastor']));
    $title = htmlentities(trim($_REQUEST['title']));
    $passage = htmlentities(trim($_REQUEST['passage']));
    $folder_name = date('Y', strtotime($date));
    if (!is_dir('../../sermons/'.$folder_name."/")) {
        mkdir('../../sermons/'.$folder_name, 0777) or handle_error("the server couldn't upload the image you selected.", 'could not create directory');
    }
    $upload_dir = HOST_WWW_ROOT.'sermons\\'.$folder_name.'\\';
    $image_fieldname = "sermon_mp3";
    ($_FILES[$image_fieldname]['error'] == 0) or handle_error("the server couldn't upload the image you selected.", $php_errors[$_FILES[$image_fieldname]['error']]);
    @is_uploaded_file($_FILES[$image_fieldname]['tmp_name']) or handle_error("you were trying to do something naughty. Shame on you!", "Uploaded request: file named '{$_FILES[$image_fieldname]['tmp_name']}'");
    $upload_filename = $upload_dir.$_FILES[$image_fieldname]['name'];
    @move_uploaded_file($_FILES[$image_fieldname]['tmp_name'], $upload_filename) or handle_error("we had a problem saving your image to its permanent location.", "permissions or related error moving file to {$upload_filename}");
    if ($article_id) {
        $stmt = $mysqli->prepare("UPDATE `wfbcsermons`.`sermons` SET `date`=?, `pastor`=?, `sermon`=?, `book`=?, `chapter`=?, `end_chapter`=?, `start_verse`=?, `end_verse`=?, `path`=? WHERE `id`=?;") or handle_error("There was a problem updating the database.", "prepare failed :".htmlspecialchars($mysqli->error));
        $stmt->bind_param('sssssssssi', $sermon_date, $sermon_pastor, $sermon_title, $book, $chapter, $end_chapter, $start_verse, $end_verse, $sermon_path, $id) or handle_error("There was a problem updating the database.", "bind_param failed :".htmlspecialchars($stmt->error));
        $sermon_date = $date;
        $sermon_pastor = $pastor;
        $sermon_title = $title;
        $passage_pieces = explode(" ", $passage);
        $book = $passage_pieces[0];
        $number_pieces = explode("-", $passage_pieces[1]);
        $start_pieces = explode(":", $number_pieces[0]);
        $chapter = $start_pieces[0];
        $start_verse = $start_pieces[1];
        $end_pieces = explode(":", $number_pieces[1]);
        $end_chapter = $start_pieces[0];
        $end_verse = $start_pieces[1];
        $sermon_path = 'http://www.wacofamily.com/sermons/'.$folder_name.'/'.$_FILES[$image_fieldname]['name'];
        $id = $sermon_id;
        $stmt->execute() or handle_error("There was a problem updating the database.", "execute failed :".htmlspecialchars($stmt->error));
    }
    else {
        $stmt = $mysqli->prepare("INSERT INTO `wfbcsermons`.`sermons` (`date`, `pastor`, `sermon`, `book`, `chapter`, `end_chapter`, `start_verse`, `end_verse`, `path`) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?);") or handle_error("There was a problem updating the database.", "prepare failed :".htmlspecialchars($mysqli->error));
        $stmt->bind_param('sssssssssi', $sermon_date, $sermon_pastor, $sermon_title, $book, $chapter, $end_chapter, $start_verse, $end_verse, $sermon_path) or handle_error("There was a problem updating the database.", "bind_param failed :".htmlspecialchars($stmt->error));
        $sermon_date = $date;
        $sermon_pastor = $pastor;
        $sermon_title = $title;
        $passage_pieces = explode(" ", $passage);
        $book = $passage_pieces[0];
        $number_pieces = explode("-", $passage_pieces[1]);
        $start_pieces = explode(":", $number_pieces[0]);
        $chapter = $start_pieces[0];
        $start_verse = $start_pieces[1];
        $end_pieces = explode(":", $number_pieces[1]);
        $end_chapter = $start_pieces[0];
        $end_verse = $start_pieces[1];
        $sermon_path = 'http://www.wacofamily.com/sermons/'.$folder_name.'/'.$_FILES[$image_fieldname]['name'];
        $stmt->execute() or handle_error("There was a problem updating the database.", "execute failed :".htmlspecialchars($stmt->error));
    }
    $stmt->close();
    $mysqli->close();
    header("Location: ../../admin.php");
    exit();
?>

Aquí está la aplicación app_config.php que define host_wwww_root:

<?php
    define("DEBUG_MODE", true);
    define("SITE_ROOT", "http://www.wacofamily.com/");
    define("DATABASE_HOST", "wfbcsermons.db.5402716.hostedresource.com");
    define("DATABASE_USERNAME", "**********");
    define("DATABASE_PASSWORD", "**********");
    define("DATABASE_NAME", "wfbcsermons");
    define("HOST_WWW_ROOT", "D:\\Hosting\\5402716\\html\\WFBC\\wacofamily.com\\");
    function js_redirect($url, $seconds=0) {  
        echo "<script language=\"JavaScript\">\n";  
        echo "<!-- hide from old browser\n\n";       
        echo "function redirect() {\n";  
        echo "window.location = \"" . $url . "\";\n";  
        echo "}\n\n";  
        echo "timer = setTimeout('redirect()', '" . ($seconds*1000) . "');\n\n";  
        echo "-->\n";  
        echo "</script>\n";  
        return true;  
    }  
    function handle_error($user_error_message, $system_error_message) {
        js_redirect('http://www.wacofamily.com/error.php?error_message='.$user_error_message.'&system_error_message='.$system_error_message, 0);
        exit();
    }
    function debug_print($message) {
        if (DEBUG_MODE) {
            echo $message;
        }
    }
?>

lo que he intentado:

He probado las siguientes cadenas:

Cuatro backslashes (como en regex):

define("HOST_WWW_ROOT", "D:\\\\Hosting\\\\5402716\\\\html\\\\WFBC\\\\wacofamily.com\\\\");

One Backslash Inside Single Quotes:

define("HOST_WWW_ROOT", 'D:\Hosting\5402716\html\WFBC\wacofamily.com\\');

Uso de &#92;, que es el código de caracteres HTML para una barra invertida:

define("HOST_WWW_ROOT", "D:&#92;Hosting&#92;5402716&#92;html&#92;WFBC&#92;wacofamily.com&#92;");

usando \134, que debe ser la secuencia octal para una barra invertida

define("HOST_WWW_ROOT", "D:\134Hosting\1345402716\134html\134WFBC\134wacofamily.com\134");

usando recortes directos como Esta pregunta dijo:

define("HOST_WWW_ROOT", "D:/Hosting/402716/html/WFBC/wacofamily.com/");

Uso de Directory_Separator como Machavity sugerido:

define("HOST_WWW_ROOT", "D:".DIRECTORY_SEPARATOR."Hosting".DIRECTORY_SEPARATOR ."402716".DIRECTORY_SEPARATOR ."html".DIRECTORY_SEPARATOR ."WFBC".DIRECTORY_SEPARATOR ."wacofamily.com".DIRECTORY_SEPARATOR );

y, por supuesto, la doble barra posterior

define("HOST_WWW_ROOT", "D:\\Hosting\\5402716\\html\\WFBC\\wacofamily.com\\");

Hice estos cambios en todas las cadenas involucradas en la creación de la ruta de carga. Solo incluyí la definición host_wwww_root para ahorrar espacio.

Cuando Sirnarsh me recordó, si hago eco del camino que estoy usando, aparece con las barras invertidas. Sin embargo, es cuando paso el camino a la función Move_uploaded_File que algo va awire.

¿Fue útil?

Solución 2

OK, lo imaginé y ahora me siento tonto.Terminé usando recortes hacia adelante.La razón por la que esto no funcionó anteriormente es que los permisos (que pensé que he comprobado) no estaban puestos para permitirme escribir.Entonces, para cualquier otra persona con este problema:

  1. Utilice los barras hacia adelante
  2. Revise sus permisos (y doble el doble y triple los controles)

Otros consejos

Debe usar Stripslashes () para leer datos

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top