2014-08-31 3 views
0

Например, теперь, когда я убиваю скрипт с использованием die() или exit(), мои страницы выглядят наполовину разбитыми, потому что нижняя часть html страницы не загружалась, так как она была введена с использованием функции include().что является альтернативой exit(); без разбивки страницы

Итак, есть ли способ сказать PHP «не разрешать выполнение каких-либо команд, кроме остальной загрузки веб-страницы»?

Я использую это для сценария загрузки изображений.

фронт: enter image description here

, но когда у меня есть неправильный тип файла загруженного или нет файла на всех, он ломает мой веб-страницу, потому что я установил выход();

enter image description here enter image description here

Что я могу сделать, чтобы исправить это? Вот мой код, и вы увидите выход(); 's

if (isset($_POST['submit'])) 
{ 
    $file_uniq_id = uniqid(); 

    // Access the $_FILES global variable for this specific file being uploaded 
    // and create local PHP variables from the $_FILES array of information 

    $fileName = $_FILES["uploaded_file"]["name"]; // The file name 
    $fileTmpLoc = $_FILES["uploaded_file"]["tmp_name"]; // File in the PHP tmp folder 
    $fileType = $_FILES["uploaded_file"]["type"]; // The type of file it is 
    $fileSize = $_FILES["uploaded_file"]["size"]; // File size in bytes 
    $fileErrorMsg = $_FILES["uploaded_file"]["error"]; // 0 for false... and 1 for true 
    $kaboom = explode(".", $fileName); // Split file name into an array using the dot 
    $fileExt = end($kaboom); // Now target the last array element to get the file extension 

    // START PHP Image Upload Error Handling -------------------------------------------------- 

    if (!$fileTmpLoc) 
    { // if file not chosen 
     echo "ERROR: Please browse for a file before clicking the upload button."; 
     exit(); 
    } 
    else 
    if ($fileSize > 5242880) 
    { // if file size is larger than 5 Megabytes 
     echo "ERROR: Your file was larger than 5 Megabytes in size."; 
     unlink($fileTmpLoc); // Remove the uploaded file from the PHP temp folder 
     exit(); 
    } 
    else 
    if (!preg_match("/.(gif|jpg|png)$/i", $fileName)) 
    { 

     // This condition is only if you wish to allow uploading of specific file types 

     echo "ERROR: Your image was not .gif, .jpg, or .png."; 
     unlink($fileTmpLoc); // Remove the uploaded file from the PHP temp folder 
     exit(); 
    } 
    else 
    if ($fileErrorMsg == 1) 
    { // if file upload error key is equal to 1 
     echo "ERROR: An error occured while processing the file. Try again."; 
     exit(); 
    } 

    // END PHP Image Upload Error Handling ---------------------------------------------------- 
    // Place it into your "uploads" folder mow using the move_uploaded_file() function 

    $moveResult = move_uploaded_file($fileTmpLoc, "uploads/$fileName"); 

    // Check to make sure the move result is true before continuing 

    if ($moveResult != true) 
    { 
     echo "ERROR: File not uploaded. Try again."; 
     unlink($fileTmpLoc); // Remove the uploaded file from the PHP temp folder 
     exit(); 
    } 

    // unlink($fileTmpLoc); // Remove the uploaded file from the PHP temp folder 
    // ---------- Include Adams Universal Image Resizing Function -------- 

    include_once ("libs/ak_php_img_lib_1.0.php"); 

    $target_file = "uploads/$fileName"; 
    $resized_file = "uploads/" . $file_uniq_id . "." . $fileExt; 
    $resized_file_final = $file_uniq_id . "." . $fileExt; 
    mysql_query("UPDATE users SET profile_image = '$resized_file_final' WHERE id = '$id' "); 
    $wmax = 128; 
    $hmax = 128; 
    ak_img_resize($target_file, $resized_file, $wmax, $hmax, $fileExt); 
    unlink($target_file); 

    // ----------- End Adams Universal Image Resizing Function ----------- 
    // Display things to the page so you can see what is happening for testing purposes 

    echo "The file named <strong>$fileName</strong> uploaded successfuly.<br /><br />"; 
    echo "It is <strong>$fileSize</strong> bytes in size.<br /><br />"; 
    echo "It is an <strong>$fileType</strong> type of file.<br /><br />"; 
    echo "The file extension is <strong>$fileExt</strong><br /><br />"; 
    echo "The Error Message output for this upload is: <strong>$fileErrorMsg</strong><br /><br />"; 
    echo "The new name for the file is: <strong>$resized_file_final</strong>"; 
} 
+0

это ломается работа? – matthew5025

+4

Не эхо внутри функций. Отделите свою бизнес-логику от уровня презентации (html) – Pinoniq

+0

@Fred -ii- что это значит ...? –

ответ

1

Попробуйте это, идея состоит в том, что вам нужно заполнить весь скрипт, чтобы вы могли добавить нижний колонтитул страницы, чтобы страница выглядела полной. Таким образом, вместо эхо-ошибок, когда вы их найдете И ТОГДА ВЫЙТИ Сценарий, сохраните их в переменной. Затем, как только вы попадаете в основную часть сценария, то есть изображение загружается и вы хотите изменить его размер, вы решаете, была ли у вас ошибка для вывода только ошибки, а не для изменения размера изображения. Если ошибок не обнаружено, вы играете с изображением и не выводите никаких сообщений об ошибках.

if (isset($_POST['submit'])) 
{ 
    $file_uniq_id = uniqid(); 

    // Access the $_FILES global variable for this specific file being uploaded 
    // and create local PHP variables from the $_FILES array of information 

    $fileName = $_FILES["uploaded_file"]["name"]; // The file name 
    $fileTmpLoc = $_FILES["uploaded_file"]["tmp_name"]; // File in the PHP tmp folder 
    $fileType = $_FILES["uploaded_file"]["type"]; // The type of file it is 
    $fileSize = $_FILES["uploaded_file"]["size"]; // File size in bytes 
    $fileErrorMsg = $_FILES["uploaded_file"]["error"]; // 0 for false... and 1 for true 
    $kaboom = explode(".", $fileName); // Split file name into an array using the dot 
    $fileExt = end($kaboom); // Now target the last array element to get the file extension 

    // START PHP Image Upload Error Handling 

    $Err = NULL; 

    if (!$fileTmpLoc) 
    { // if file not chosen 
     $Err = "ERROR: Please browse for a file before clicking the upload button."; 
    } 
    else 
    if ($fileSize > 5242880) 
    { // if file size is larger than 5 Megabytes 
     $Err = "ERROR: Your file was larger than 5 Megabytes in size."; 
     unlink($fileTmpLoc); // Remove the uploaded file from the PHP temp folder 
    } 
    else 
    if (!preg_match("/.(gif|jpg|png)$/i", $fileName)) 
    { 
     // This condition is only if you wish to allow uploading of specific file types 

     $Err = "ERROR: Your image was not .gif, .jpg, or .png."; 
     unlink($fileTmpLoc); // Remove the uploaded file from the PHP temp folder 
    } 
    else 
    if ($fileErrorMsg == 1) 
    { // if file upload error key is equal to 1 
     $Err = "ERROR: An error occured while processing the file. Try again."; 
    } 

    // END PHP Image Upload Error Handling 
    // Place it into your "uploads" folder mow using the move_uploaded_file() function 

    $moveResult = move_uploaded_file($fileTmpLoc, "uploads/$fileName"); 

    // Check to make sure the move result is true before continuing 

    if ($moveResult != true) { 
     $Err = "ERROR: File not uploaded. Try again."; 
     // not needed PHP is supposed to do this 
     // unlink($fileTmpLoc); 
    } 

    // ---------- Include Adams Universal Image Resizing Function -------- 

    if (! isset($Err)) {  

     include_once ("libs/ak_php_img_lib_1.0.php"); 

     $target_file = "uploads/$fileName"; 
     $resized_file = "uploads/" . $file_uniq_id . "." . $fileExt; 
     $resized_file_final = $file_uniq_id . "." . $fileExt; 
     mysql_query("UPDATE users 
        SET profile_image = '$resized_file_final' 
        WHERE id = '$id' "); 
     $wmax = 128; 
     $hmax = 128; 
     ak_img_resize($target_file, $resized_file, $wmax, $hmax, $fileExt); 
     unlink($target_file); 

     // ----------- End Adams Universal Image Resizing Function ----------- 
     // Display things to the page so you can see what is happening for testing purposes 

     // as we had to process error in this if we better test again 
     echo "The file named <strong>$fileName</strong> uploaded successfuly.<br /><br />"; 
     echo "It is <strong>$fileSize</strong> bytes in size.<br /><br />"; 
     echo "It is an <strong>$fileType</strong> type of file.<br /><br />"; 
     echo "The file extension is <strong>$fileExt</strong><br /><br />"; 
     echo "The Error Message output for this upload is: <strong>$fileErrorMsg</strong><br /><br />"; 
     echo "The new name for the file is: <strong>$resized_file_final</strong>"; 

    } else { 
     echo $Err; 
    } 
} 
0

Обычно function s используются для группового кода вместе. Затем вы можете остановить функцию на полпути с помощью инструкции return;. Функции сохраняют код организованным и многоразовым. Следующим шагом было бы поместить связанные функции в классы, а затем разделить код, который генерирует выходные (эхо-инструкции) и логику в разные классы, но это уже новая парадигма для вас (загляните в объектно-ориентированное программирование - ООП. Это сложно, но очень важно, если вы хотите продвинуться).

В качестве примера группировки кода в функции кода в Условный оператор может быть введен в uploadFile-функции, например, так:

<?php 

function uploadFile($id, $file) { 
    $file_uniq_id = uniqid(); 

    // Access the $_FILES global variable for this specific file being uploaded 
    // and create local PHP variables from the $_FILES array of information 

    $fileName = $file["name"]; // The file name 
    $fileTmpLoc = $file["tmp_name"]; // File in the PHP tmp folder 
    $fileType = $file["type"]; // The type of file it is 
    $fileSize = $file["size"]; // File size in bytes 
    $fileErrorMsg = $file["error"]; // 0 for false... and 1 for true 
    $kaboom = explode(".", $fileName); // Split file name into an array using the dot 
    $fileExt = end($kaboom); // Now target the last array element to get the file extension 

    // START PHP Image Upload Error Handling -------------------------------------------------- 

    if (!$fileTmpLoc) 
    { // if file not chosen 
     echo "ERROR: Please browse for a file before clicking the upload button."; 
     return; 
    } 
    else 
    if ($fileSize > 5242880) 
    { // if file size is larger than 5 Megabytes 
     echo "ERROR: Your file was larger than 5 Megabytes in size."; 
     unlink($fileTmpLoc); // Remove the uploaded file from the PHP temp folder 
     return; 
    } 
    else 
    if (!preg_match("/.(gif|jpg|png)$/i", $fileName)) 
    { 

     // This condition is only if you wish to allow uploading of specific file types 

     echo "ERROR: Your image was not .gif, .jpg, or .png."; 
     unlink($fileTmpLoc); // Remove the uploaded file from the PHP temp folder 
     return; 
    } 
    else 
    if ($fileErrorMsg == 1) 
    { // if file upload error key is equal to 1 
     echo "ERROR: An error occured while processing the file. Try again."; 
     return; 
    } 

    // END PHP Image Upload Error Handling ---------------------------------------------------- 
    // Place it into your "uploads" folder mow using the move_uploaded_file() function 

    $moveResult = move_uploaded_file($fileTmpLoc, "uploads/$fileName"); 

    // Check to make sure the move result is true before continuing 

    if ($moveResult != true) 
    { 
     echo "ERROR: File not uploaded. Try again."; 
     unlink($fileTmpLoc); // Remove the uploaded file from the PHP temp folder 
     return; 
    } 

    // unlink($fileTmpLoc); // Remove the uploaded file from the PHP temp folder 
    // ---------- Include Adams Universal Image Resizing Function -------- 

    include_once ("libs/ak_php_img_lib_1.0.php"); 

    $target_file = "uploads/$fileName"; 
    $resized_file = "uploads/" . $file_uniq_id . "." . $fileExt; 
    $resized_file_final = $file_uniq_id . "." . $fileExt; 
    mysql_query("UPDATE users SET profile_image = '$resized_file_final' WHERE id = '$id' "); 
    $wmax = 128; 
    $hmax = 128; 
    ak_img_resize($target_file, $resized_file, $wmax, $hmax, $fileExt); 
    unlink($target_file); 

    // ----------- End Adams Universal Image Resizing Function ----------- 
    // Display things to the page so you can see what is happening for testing purposes 

    echo "The file named <strong>$fileName</strong> uploaded successfuly.<br /><br />"; 
    echo "It is <strong>$fileSize</strong> bytes in size.<br /><br />"; 
    echo "It is an <strong>$fileType</strong> type of file.<br /><br />"; 
    echo "The file extension is <strong>$fileExt</strong><br /><br />"; 
    echo "The Error Message output for this upload is: <strong>$fileErrorMsg</strong><br /><br />"; 
    echo "The new name for the file is: <strong>$resized_file_final</strong>"; 
} 

if (isset($_POST['submit'])) 
{ 
    uploadFile($id, $_FILES["uploaded_file"]); 
} 

Хотя это еще далеко от хорошо организованного кода, его решает вашу проблему, заменив exit() на return;.

+0

Казалось, что это работает отлично, но небольшая ошибка, которую не задает переменная ** $ id ** , но она выше '$ id = $ _GET ['id']; \t $ id = stripslashes ($ id); $ id = mysql_real_escape_string ($ id); \t \t \t // GET идентификатор установлен и не пустой и числовой если (Исеть ($ ID) &&! Пусто ($ ID) && is_numeric ($ ID)) { $ ID = intval ($ _ GET [» Я бы']); } // Else принимает значение из сеанса, если не пуст, и является числовым elseif (isset ($ _ SESSION ['id']) &&! Empty ($ _ SESSION ['id']) && is_numeric ($ _ SESSION ['id '])) { $ id = intval ($ _ SESSION [' id ']); } ' –

+1

См. Обновленную версию. Я добавил $ id в качестве параметра функции и передал исходный $ id, который вы указали в коде, указанном выше в вызове функции. –

+0

спасибо, еще одна мелочь, я установил его, поэтому можно загружать только определенные типы файлов, но когда я пытаюсь загрузить файл PDF, WHICH НЕ разрешен, он пытается обработать его и выдаст предупреждающие ошибки 'Warning: move_uploaded_file (/ tmp/phpSsaO6r) [function.move-uploaded-file]: не удалось открыть поток: нет такого файла или каталога в /home/u315295673/public_html/new/profile_pic.php в строке 285 Предупреждение: move_uploaded_file() [function.move-uploaded-file]: Невозможно переместить '/ tmp/phpSsaO6r' в 'uploads/pics.pdf' в /home/u315295673/public_html/new/profile_pic.php в строке 285' –

Смежные вопросы