Новичок в Ubuntu не может загружать изображения в каталог для веб-страницы через xampp отлично работал на Windows - PullRequest
0 голосов
/ 15 февраля 2019

Привет, я новичок в Linux Ubuntu 18.04.Я установил веб-сервер xampp.У меня есть php-код, который отлично работает в среде Windows с xampp.Однако теперь я переключился на Linux, и когда я заканчиваю страницу, чтобы загрузить изображение в каталог, похоже, что страница завершает обработку, но сам каталог пуст.Может кто-нибудь, пожалуйста, помогите, я попробовал разрешения, как другие форумы и видео упомянули, но это не имеет значения.Я новичок в Linux, поэтому, пожалуйста, будьте терпеливы со мной

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

Kunal

Редактировать мой код, как он сказал, это может быть немного громоздким, я изучаю php allвызовы базы данных работают нормально.

<?php
     require_once $_SERVER['DOCUMENT_ROOT'].'/ECommerce/core/init.php';
include 'includes/head.php';
include 'includes/navigation.php';
$dbpath='';
if(isset($_GET['add'])||isset($_GET['edit'])){
  $brandQuery = $db->query("SELECT * FROM brand ORDER BY brand");
  $parentQuery = $db->query("SELECT * FROM catergories WHERE parent =0 ORDER BY category");
  $title =((isset($_POST['title'])&& $_POST['title'] !='')?sanitize($_POST['title']):'');
  $brand =((isset($_POST['brand']) && !empty($_POST['brand']))?sanitize($_POST['brand']):'');
  $parent =((isset($_POST['parent']) && !empty($_POST['parent']))?sanitize($_POST['parent']):'');
  $category =((isset($_POST['child'])) && !empty($_POST['child'])?sanitize($_POST['child']):'');
  $price =((isset($_POST['price'])&& $_POST['price'] !='')?sanitize($_POST['price']):'');
  $list_price =((isset($_POST['list_price'])&& $_POST['list_price'] !='')?sanitize($_POST['list_price']):'');
  $description =((isset($_POST['description'])&& $_POST['description'] !='')?sanitize($_POST['description']):'');
  $available =((isset($_POST['available'])&& $_POST['available'] !='')?sanitize($_POST['available']):'');
  $size =((isset($_POST['size'])&& $_POST['size'] !='')?sanitize($_POST['size']):'');
  $saved_image='';

if(isset($_GET['edit'])){
  $edit_id = (int)$_GET['edit'];
  $productResults= $db->query("SELECT * FROM products WHERE id ='$edit_id'");
  $product = mysqli_fetch_assoc($productResults);
  if (isset($_GET['delete_image'])){
    $image_url = $_SERVER['DOCUMENT_ROOT'].$product['image'];echo $image_url;
    unlink($image_url);
    $db->query("UPDATE products SET image=''WHERE id ='$edit_id'");
    header('Location: products.php?edit='.$edit_id);
  }
  $category = ((isset($_POST['child']) && $_POST['child']!= '')?sanitize($_POST['child']):$product['categories']);
  $title = ((isset($_POST['title']) && $_POST['title']!='')?sanitize($_POST['title']):$product['title']);
  $brand = ((isset($_POST['brand']) && $_POST['brand']!='')?sanitize($_POST['brand']):$product['brand']);
  $parentQ = $db->query("SELECT * FROM catergories WHERE id ='$category'");
  $parentResult= mysqli_fetch_assoc($parentQ);
  $parent = ((isset($_POST['parent']) && $_POST['parent'] !='')?sanitize($_POST['parent']):$parentResult['parent']);
  $price = ((isset($_POST['price']) && $_POST['price']!='')?sanitize($_POST['price']):$product['price']);
  $list_price = ((isset($_POST['list_price']) && $_POST['list_price']!='')?sanitize($_POST['list_price']):$product['list_price']);
  $description = ((isset($_POST['description']) && $_POST['description']!='')?sanitize($_POST['description']):$product['description']);
  $available = ((isset($_POST['available']) && $_POST['available']!='')?sanitize($_POST['available']):$product['Available']);
  $size = ((isset($_POST['size']) && $_POST['size']!='')?sanitize($_POST['size']):$product['size']);
  $saved_image=(($product['image'] !='')?$product['image']:'');
  $dbpath=$saved_image;
}
if($_POST){

  $categories =sanitize($_POST['child']);
  $price =sanitize($_POST['price']);
  $list_price =sanitize($_POST['list_price']);
  $size =sanitize($_POST['size']);
  $description =sanitize($_POST['description']);
  $errors = array();
  $size= sanitize($_POST['size']);
  $dbPath='';
  $required = array('title','price','parent','child');
  $available = sanitize($_POST['available']);

foreach ($required as $field) {
  if($_POST[$field]== ''){
    $errors[] ='All fields With an Asterisk are required.';
    break;
  }
}
if(!empty($_FILES)) {
  var_dump ($_FILES);
  $photo=$_FILES['photo'];
  $name=$photo['name'];
  $nameArray = explode('.',$name);
  $fileExt = $nameArray[1];
  $mime = explode ('/',$photo['type']);
  $mimeType=$mime[0];
  $mimeExt =$mime[1];
  $tmpLoc=$photo['tmp_name'];
  $fileSize=$photo['size'];
  $allowed= array('png','jpg','JPEG','GIF');
  $uploadName = md5(microtime()).'.'.$fileExt;
  $uploadPath= '/ECommerce/stock/'.$uploadName;
  $dbpath ='/ECommerce/stock/'.$uploadName;
  if($mimeType !='image'){
    $errors[]='The File must be an image';
  }
  if(!in_array($fileExt,$allowed)){
    $errors[]='The file extenstion must be a PNG, JPG,JPEG or GIF.';
  }
  if($fileSize > 15000000){
    $errors[]='The file size must be under 15MB.';
  }
  if ($fileExt != $mimeExt && ($mimeExt ==='jpeg' && $fileExt !='jpg')){
    $errors[]='The File extension does not match the file';
  }
}
if(!empty($errors)){
  echo display_errors($errors);
}else{
  //upload file and insert into database
  move_uploaded_file($tmpLoc,$uploadPath);
  $insertSQL="INSERT INTO  products (`title`,`price`,`list_price`,`brand`,`categories`,`size`,`image`,`description`,`Available`)
  VALUES('$title','$price','$list_price','$brand','$category','$size','$dbpath','$description','$available')";
if(isset($_GET['edit'])){
  $insertSQL="UPDATE products SET title ='$title', price = '$price', list_price = '$list_price',
  brand='$brand', categories ='$category', size='$size' , Available='$available',image='$dbpath',description='$description' WHERE id='$edit_id'";
}

$db->query($insertSQL);
header('Location: products.php');
}
}

?>
<h2 class="text-center"><?=((isset($_GET['edit']))?'Edit A ':'Add A New');?>Product</h2><hr>
<form action="products.php?<?=((isset($_GET['edit']))?'edit='.$edit_id:'add=1');?>" method="POST" ENCTYPE="multipart/form-data">
  <div class="form-group col-md-3">
<label for="title">Title*:</label>
<input type="text" name="title"class="form-control" id="title" value="<?=$title;?>">
  </div>
  <div class="form-group col-md-3">
    <label for="brand">Brand:</label>
    <select class="form-control" id="brand" name="brand">
      <option value=""<?=(($brand =='')?' selected':'');?>></option>
      <?php while($b=mysqli_fetch_assoc($brandQuery)): ?>
        <option value="<?=$b['id'];?>"<?=(($brand == $b['id'])?' selected':'');?>><?=$b['brand'];?></option>
      <?php endwhile;?>
    </select>
    </div>
    <div class="form-group col-md-3">
      <label for="parent">Parent Category*:</label>
      <select class="form-control" id="parent" name="parent">
        <option value=""<?=(($parent =='')?' selected':'');?>></option>
        <?php while($p= mysqli_fetch_assoc($parentQuery)): ?>
          <option value="<?=$p['id'];?>"<?=(($parent == $p['id'])?' selected':'');?>><?=$p['category'];?></option>
        <?php endwhile; ?>
      </select>
    </div>
    <div class="form-group col-md-3">
      <label for="child">Child Category*:</label>
      <select id="child" name="child" class="form-control">
      </select>
    </div>
    <div class="form-group col-md-3">
      <label for="price">Price*:</label>
      <input type="text" id="price" name="price" class="form-control" value="<?=$price;?>">
    </div>
    <div class="form-group col-md-3">
      <label for="price">List Price*:</label>
      <input type="text" id="list_price" name="list_price" class="form-control" value="<?=$list_price;?>">
    </div>
  <div class="form-group col-md-3">
    <label>Size*:</label>
    <input type="text" id="size" name="size" class="form-control" value="<?=$size;?>">
  </div>
  <div class="form-group col-md-3">
    <label>Available:</label>
    <input type="text" id="size" name="available" class="form-control" value="<?=$available;?>">
  </div>

<br>
  <div class="form-group col-md-6">
<?php if($saved_image !=''): ?>
  <div class="saved-image"><img src="<?=$saved_image;?>" alt="saved image"/><br>
    <a href = "products.php?delete_image=1&edit=<?=$edit_id;?>" class="text-danger"> Delete Image</a>
  </div>
<?php else: ?>
  <label for="photo">Product Photo:</label>
  <input type="file" name="photo" id="photo" class="form-control" accept="image/*" >
<?php endif;?>
</div>
<div class="form-group col-md-6">
  <label for="description">Description:</label>
  <textarea id="description" name="description" class="form-control" rows="6"><?=$description;?></textarea>
</div>
<div class="form-group pull-right">
<a href="products.php" class="btn btn-default">Cancel</a>
<input type="submit" value="<?=((isset($_GET['edit']))?'Edit  ':'Add ');?> Product" class="btn btn-success pull-left">

</div><div class ="clearfix"></div>
</form>

    </div>
      </div>

      </div>
    </div>
  </div>
</div>
<?php }else{
$sql = "SELECT * FROM products WHERE deleted = 0";
$presults =$db->query($sql);
if (isset($_GET['featured'])){
  $id = (int)$_GET['id'];
  $featured = (int)$_GET['featured'];
  $featuredsql = "UPDATE products SET featured ='$featured' WHERE id='$id'";
  $db->query($featuredsql);
  header('Location: products.php');
}
 ?>
<h2 class="text-center">Products </h2>
<a href="products.php?add=1" class="btn btn-success pull-right" id="add-product-btn">Add Product</a><div class="clearfix"></div>
<hr>
<table class="table table-bordered table-condensed table-striped">
  <thead><th></th><th>Product</th><th>Price</th><th>Category</th><th>Featured</th><th>Sold</th></thead>
  <tbody>
    <?php while($product = mysqli_fetch_assoc($presults)):
        $childID= $product['categories'];
        $catsql="SELECT* FROM catergories WHERE id = '$childID'";
        $result=$db->query($catsql);
        $child= mysqli_fetch_assoc($result);
        $parentID = $child['parent'];
        $psql="SELECT * FROM catergories WHERE id ='$parentID'";
        $presult=$db->query($psql);
        $parent= mysqli_fetch_assoc($presult);
        $category = $parent['category'].'-'.$child['category'];
      ?>
      <tr>
        <td>
          <a href="products.php?edit=<?=$product['id'];?>" class="btn btn-xs btn-default"><span class="glyphicon glyphicon-pencil"></span> </a>
          <a href="products.php?delete=<?=$product['id'];?>" class="btn btn-xs btn-default"><span class="glyphicon glyphicon-remove"></span> </a>
        </td>
        <td><?=$product['title'];?></td>
        <td><?=money($product['price']);?></td>
        <td><?=$category;?></td>
        <td><a href="products.php?featured=<?=(($product['featured']==0)?'1':'0')?>&id=<?=$product['id'];?>" class="btn btn-xs btn-default" >
          <span class="glyphicon glyphicon-<?=(($product['featured']==1)?'minus':'plus');?>"></span>
        </a>&nbsp <?=(($product['featured']== 1)?'Featured Product':'');?></td>

        <td>0</td>
      </tr>
    <?php endwhile; ?>
  </tbody>
</table>
 <?php
} include 'includes/footer.php';?>
<script>
jQuery('document').ready(function(){
get_child_options('<?=$category;?>');
});
</script>

 ?>

Ответы [ 2 ]

0 голосов
/ 15 февраля 2019

Chane

$uploadPath= '/ECommerce/stock/'.$uploadName;

до

$uploadPath=$_SERVER['DOCUMENT_ROOT'] . "/ECommerce/stock/".$uploadName; 
0 голосов
/ 15 февраля 2019
  • В Linux учитывается регистр, правильно ли вы указали пути в соответствии с регистром папок в файловой системе?
  • Является ли папка в вашем корне - если нет, возможно, вам придется отредактироватьКонфигурация apache для установки прав доступа apache для доступа к этой папке (а не только для прав доступа к папке)
  • Вы заглянули в error.log, чтобы узнать, что выводит ошибка из PHP.Windows обычно отображает ошибки при отображении, это может быть не включено для сервера Linux по умолчанию, поэтому вы можете пропустить вывод ошибок.

Кратко рассмотрите ваш код, хотя и ничего не зная, например, файлname, имя папки - вы проверяете расширения файлов, но не учитываете все в нижнем регистре (входное расширение и массив для сравнения), чтобы гарантировать, что чувствительность к регистру здесь не проблема.Например, file.JPG и file.jpeg не будут соответствовать вашему массиву.

Во-вторых, вы не проверяете результат файла move_uploaded_file, это может помочь убедиться, что оно успешно выполнено в данный момент, или нет.Как упоминалось ранее, проверьте журнал ошибок.

Просто добавьте, что этот код полон уязвимостей безопасности - отлично подходит для начала обучения, но я бы никуда не запустил его в производство.

...