Это мой первый пост, и я действительно не был бы, если бы у меня не было вариантов (последнее, что я хочу быть, это раздражает без причины). Я работаю над этим скриптом в течение нескольких дней, ударяя головой о клавиатуру, пытаясь понять, почему она не работает.
Файл 1: это частичный класс загрузки, предназначенный для использования из внешнего файла.
<?php
namespace Tools\File;
class Upload {
protected $destination;
protected $max = 51200;
protected $messages = array();
protected $permitted = array('image/gif','image/jpeg', 'image/pjpeg', 'image/png');
public function __construct($path){
if (!is_dir($path) || !is_writable($path)) {
throw new \Exception ("$path must be a valid,writable directory");
}
$this->destination = $path;
}
public function upload(){
$upload = current($_FILES);
if ($this->checkFile($uploaded)){
$this->moveFile($uploaded);
}
}
protected function checkFile($file){
return true;
}
protected function moveFile ($file) {
$success = move_uploaded_file($file ['tmp_name'] , $this->destination . $file['name']);
if ($success){
$result = $file['name'] . 'was uploaded successfully';
$this->messages[] = $result;
}else{
$this->messages[] = 'Could not upload' . $file['name'];
}
}
public function getMessages(){
return $this->messages;
}
}
Файл 2: форма для загрузки изображений
<head>
<?php use Tools\File\Upload as FileUploader; ?>
</head>
<body>
<?php
if(isset($_POST['upload'])){
// difine the path to the upload folder
$destination = 'C:/Uploads/';
// Include upload class
require_once '../Tools/File/Upload.php';
// Creates new instance of the upload class as loader
try{
$loader = new FileUploader ($destination);
$loader->getMessages();
}catch(Exception $e){
echo $e->getMessages();
}
}
// Checks and echos result
if(isset($result)){
echo '<ul>';
foreach($result as $message){
echo "<li>$message</li>";
}
echo '</ul>';
}
?>
<form id="uploadImage" enctype="multipart/form-data" action="<?php htmlspecialchars($_SERVER['PHP_SELF']) ?>" method="post">
<p>
<label for="image">Upload Image</label>
<input type="hidden" name="MAX_FILE_SIZE" value="<?= $max; ?>">
<input type="file" name="image" id="image">
</p>
<p>
<input type="submit" name="upload" value="upload" id="uplaod">
</p>
</form>
<!-- For checking the Files Super global-->
<pre>
<?php
if(isset($_POST['upload'])){ print_r($_FILES);}?>
</pre>
</body>
Форма отлично работает. Файлы загружаются отлично, когда функция "move_uploaded_file" вызывается внутри самого файла 2, но, похоже, она вообще не вызывает класс.
Я потерял подсчет количества раз, когда я был над кодом. Перестановка и попытка всего, что я знаю, чтобы заставить его работать.
Любая помощь была бы высоко оценена. Заранее благодарим за то, что нашли время.
Вам нужно вызвать метод загрузки из второго файла. В противном случае он будет создавать экземпляр класса Upload, но не активировать какую-либо операцию загрузки.
try {
$loader = new FileUploader ($destination);
$loader->upload();
$loader->getMessages();
} catch(Exception $e){
echo $e->getMessages();
}