2012-08-22 1 views
0

Эй, ребята, что я пытаюсь сделать, это сборка страницы для различных игр на разных игровых консолях. Я признаю, что я новичок в php, и я просто пытаюсь понять, что происходит. Я столкнулся с какой-то странной проблемой, загрузив изображения. Я не понимаю, почему это не удается, потому что один атрибут в массиве работает отлично. Он без проблем загружает результаты из формы. Остальные три атрибута не работают. Используя ту же самую функцию и методы.

//// this the form block for uploading //// 


<form action="process.php" method="post" enctype="multipart/form-data"> 
    <!--xbox --> 
       <div class="form"> 
        <h3>Xbox 360</h3> 

        <!-- title of post/ game name --> 
        <p><label for="xboxtitle"> Title of Game </lable></p> 
        <input type="text" name="xboxtitle" size=20 /><br /> 

        <!-- image uploader --> 
        <p><label for="xbox-image">Game Image:</label><sup>*png, png, bmp, jpeg and jpg only!</sup></p> 
        <input type="file" name="xboximage" /><br /> 
        <input type="hidden" name="MAX_FILE_SIZE" value="100000" /> 

        <!-- large text box --> 
        <p><label for="xboxtext">Displayed text:</label><sup> * limit of 250 characters allowed.</sup></p> 
        <textarea cols=40 rows=10 name="xboxtext"></textarea> 

        <!-- price box --> 
         <p><label for="xboxprice">Price of item</label></p> 
         <input type="text" name="xboxprice" size=8 /><br /> 

       </div>     



<!-- p3 --> 
       <div class="form"> 

        <h3>Playstation 3</h3> 

        <!-- title of post/ game name --> 
        <p><label for="ps3title"> Title of Game </lable></p> 
        <input type="text" name="ps3title" size=20 /><br /> 

        <!-- image uploader --> 
        <p><label for="ps3image">Game Image:</label><sup>*png, png, bmp, jpeg and jpg only!</sup></p> 
        <input type="file" name="ps3image" /><br /> 
        <input type="hidden" name="MAX_FILE_SIZE" value="100000" /> 

        <!-- large text box --> 
        <p><label for="ps3text">Displayed text:</label><sup> * limit of 250 characters allowed.</sup></p> 
        <textarea cols=40 rows=10 name="ps3text"></textarea> 

        <!-- price box --> 
         <p><label for="ps3price">Price of item</label></p> 
         <input type="text" name="ps3price" size=8 /><br /> 


       </div> 
<!-- wii --> 
       <div class="form"> 
        <h3>Wii</h3> 

        <!-- title of post/ game name --> 
        <p><label for="wiititle"> Title of Game </lable></p> 
        <input type="text" name="wiititle" size=20 /><br /> 

        <!-- image uploader --> 
        <p><label for="wiiimage">Game Image:</label><sup>*png, png, bmp, jpeg and jpg only!</sup></p> 
        <input type="file" name="wiiimage" /><br /> 
        <input type="hidden" name="MAX_FILE_SIZE" value="100000" /> 

        <!-- large text box --> 
        <p><label for="wiitext">Displayed text:</label><sup> * limit of 250 characters allowed.</sup></p> 
        <textarea cols=40 rows=10 name="wiitext"></textarea> 

        <!-- price box --> 
         <p><label for="wiiprice">Price of item</label></p> 
         <input type="text" name="wiiprice" size=8 /><br /> 

        </div> 



<!-- PC --> 
       <div class="form"> 
        <h3>PC</h3> 

        <!-- title of post/ game name --> 
        <p><label for="pctitle"> Title of Game </lable></p> 
        <input type="text" name="pctitle" size=20 /><br /> 

        <!-- image uploader --> 
        <p><label for="pcimage">Game Image:</label><sup>*png, png, bmp, jpeg and jpg only!</sup></p> 
        <input type="file" name="pcimage" /><br /> 
        <input type="hidden" name="MAX_FILE_SIZE" value="100000" /> 

        <!-- large text box --> 
        <p><label for="pctext">Displayed text:</label><sup> * limit of 250 characters allowed.</sup></p> 
        <textarea cols=40 rows=10 name="pctext"></textarea> 

        <!-- price box --> 
         <p><label for="pcprice">Price of item</label></p> 
         <input type="text" name="pcprice" size=8 /><br /> 

       </div> 
     <p><input type="submit" id="submit" class="bigbutton" value="Upload" /></p> 
</form> 




///// this is the process.php page /// 
<?php 
include ("includes/logincheck.php"); 
?> 

<?php 

// Call our connection file 
require("dbacess.php"); 


/////////////////////////////////////////////////////////////////////////////////////////////////// 

    // create validating image types function 
function is_valid_type($file) 
{ 
    // This is an array that holds all the valid image MIME types 
    $valid_types = array("image/jpg", "image/jpeg", "image/bmp", "image/gif", "image/png"); 

    if (in_array($file['type'], $valid_types)) 
     return 1; 
    return 0; 
} 


// declare possible forms in array. 
$arr = array("xbox","ps3", "wii", "pc"); 

// push the array through the following code 
//while giving $value the proper form prefix 
foreach ($arr as &$value) { 

//$value Variables 
    $title = $_POST[$value . 'title']; 
    $text = $_POST[$value . 'text']; 
    $price = $_POST[$value . 'price']; 
    $image = $_FILES[$value .'image']; 

//validate info or redirect 
if ($title && $text && $price && $image['name'] != "") 
    { 

    // Sanitize our inputs 
    $title = mysql_real_escape_string($title); 
    $text = mysql_real_escape_string($text); 
    $price = mysql_real_escape_string($price); 
    $image['name'] = mysql_real_escape_string($image['name']); 

    // Build our target path full string. This is where the file will be moved to 
    // Build Partial Target Path 
    $TARGET_PATH = "../../images/newreleasesuploads/"; 
    $TARGET_PATH .= "$value/"; 

    //creates upload path 
    $UPLOAD_PATH = $TARGET_PATH; 
    $UPLOAD_PATH .= $image['name']; 


    // Check to make sure that our file is actually an image 
    // You check the file type instead of the extension because the extension can easily be faked 
    if (!is_valid_type($image)) 
    { 
     $_SESSION['error'] = "You must upload a jpeg, gif, png, or bmp in {$value} field. Please select a correct file type."; 
     header("Location: welcome.php"); 
     exit; 
    } 

    // Here we check to see if a file with that name already exists 
    // You could get past filename problems by appending a timestamp to the filename and then continuing 
    if (file_exists($UPLOAD_PATH)) 
    { 
     $_SESSION['error'] = "A file with that name already exists when trying to update $value page. Please rename file something different or remove the existing files"; 
     header("Location: welcome.php"); 
     exit; 
    } 

    //create current date variable 
    $date = date("Y-m-d"); 
    $date .= date(" h:i:s"); 
    // count # of entries 
    $entry = mysql_query("SELECT * FROM new{$value}"); 
    $NUMBER_OF_ROWS = mysql_num_rows($entry); 

    // Count # of entries delete if index is 10 or more. 
    if($NUMBER_OF_ROWS >=10){ 

     // find oldest entry by date 
      $sqldate ="SELECT * FROM new{$value} 
      WHERE date = (SELECT MIN(date) FROM new{$value})"; 
      $oldestdate = mysql_query($sqldate) or die ("could not access DB to find oldest entry" . mysql_error()); 

      //grabs data from that row 
      $row = mysql_fetch_assoc($oldestdate); 

      //adds filename to delete path 
      $DELETE =$TARGET_PATH; 
      $DELETE .=$row['filename']; 

      // parse row date to variable 
      $deletedate = $row['id']; 

      //terminates entry 
      $deletedate = "DELETE FROM new{$value} 
      WHERE id = $deletedate"; 
      $deleteoldest = mysql_query($deletedate) or die ("could not delete oldest date entry" . mysql_error()); 

      //terminates file 
      unlink($DELETE); 

      $_SESSION['message'] .= "The oldest entry was deleted to make room for the new upload."; 


     } 

    // attempt to move the file from its temporary directory to its new home 
    if (move_uploaded_file($image['tmp_name'], $UPLOAD_PATH)) 
    { 

     // Placing a reference of the images location into the database, *not* putting the image into the database. 
     $sql = "insert into new{$value} (date, title, description, price, filename) values ('$date', '$title', '$text', '$price', '" . $image['name'] . "')"; 
     $result = mysql_query($sql) or die ("Could not insert data into DB: " . mysql_error()); 
     //message to let user know image was uploaded correctly 
     $_SESSION['message'] .= "The {$value} entry was uploaded correctly"; 


    } 

    else { 
     // A common cause of file moving failures is because of bad permissions on the directory attempting to be written to 
     // Make sure you chmod the directory to be writable also make sure directory is not READ ONLY 
     $_SESSION['error'] = "Could not upload file. Check read/write permissions on the directory"; 
     header("Location: welcome.php"); 
     exit; 

    } 
} 


// declare variable for error display 
$i = 0; 
// validate to make sure all are filled 
if($title !=""){$i++;} 
if($text !=""){$i++;} 
if($price !=""){$i++;} 
if($image['name'] !=""){$i++;} 

elseif ($i!=0) { 


    //validate that more then one but not all box 
     $_SESSION['error'] = "Only $i of the fields for $value were filled. Please refill all fields or no fields for $value"; 
     header("Location: welcome.php"); 
     exit; 

    } 


} 



// return to upload page 
header("Location: welcome.php"); 
     exit; 
?> 

Что происходит это значение Xbox в массиве проталкивает однако ps3 Wii и ПК все отправить обратно ошибку «Вы должны загрузить JPEG, GIF, PNG или BMP в ps3 поле. Пожалуйста, выберите правильный файл тип." которое должно быть, если изображение является неправильным типом файла. Однако я могу загрузить одно и то же изображение одновременно или синхронно, и xbox будет проходить каждый раз, в то время как другие будут терпеть неудачу. Может ли кто-нибудь сказать мне, почему это так? и, возможно, как это исправить?

Спасибо за ваше время заранее

+0

* Соответствующий * код не должен быть слишком длинным для публикации здесь. Большинство проблем касаются не более 20-30 строк. Пожалуйста, разместите * соответствующий * код. – Matt

+0

Скопируйте, вставьте, выберите, Ctrl + K. Человек, это была боль. И да, код * слишком длинный. – deceze

ответ

0

Fixed моей собственной проблемы после того, как делать некоторые дополнительные исследования у меня было два варианта. Проблема заключалась в том, что я пытался загрузить несколько файлов без конфигурации на Apache. вариант 1) изменить форму, как так (это позволяет только одну загрузку в то время)

   <div class="form"> 
       <form action="newreleasesprocess.php" method="post" enctype="multipart/form-data"> 
       <h3>Playstation 3</h3> 

       <!-- title of post/ game name --> 
       <p><label for="ps3title"> Title of Game </lable></p> 
       <input type="text" name="ps3title" size=20 /><br /> 

       <!-- image uploader --> 
       <p><label for="ps3image">Game Image:</label><sup>*png, png, bmp, jpeg and jpg only!</sup></p> 
       <input type="file" name="ps3image" /><br /> 
       <input type="hidden" name="MAX_FILE_SIZE" value="100000" /> 

       <!-- large text box --> 
       <p><label for="ps3text">Displayed text:</label><sup> * limit of 250 characters allowed.</sup></p> 
       <textarea cols=40 rows=10 name="ps3text"></textarea> 

       <!-- price box --> 
        <p><label for="ps3price">Price of item</label></p> 
        <input type="text" name="ps3price" size=8 /><br /> 
        <p><input type="submit" id="submit" value="Upload" /></p> 
    </form> 


      </div> 

Однако это избавляется от загрузки нескольких сразу и за то, что я использую его для этого не хорошо.

вариант 2) переконфигурировать max_file_uploads в .ini конфигурации от 1 до 4 (или то, что вы хотите)


Я пошел с опцией 2.

надеюсь, что это решение поможет кому-либо еще, кто сталкивается с тем же вопросом Еще раз спасибо всем, кто заглянул в мою проблему

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