$max_size) {
$errors[] = "Arquivo muito grande. Máximo: " . ($max_size / 1024 / 1024) . "MB";
}
if (!in_array($file_ext, $allowed_types)) {
$errors[] = "Tipo não permitido: " . $file_ext;
}
return $errors;
}
// Função para salvar arquivo
function saveFile($source, $destination, $filename) {
$target_file = $destination . $filename;
if (file_exists($target_file)) {
return ["error" => "Arquivo já existe: " . $filename];
}
if (copy($source, $target_file)) {
chmod($target_file, 0644);
return ["success" => true, "path" => $target_file, "name" => $filename];
}
return ["error" => "Erro ao salvar arquivo"];
}
// Upload via URL com cURL
if (isset($_POST['upload_url'])) {
$url = trim($_POST['url']);
if (empty($url)) {
$errors[] = "URL não pode estar vazia.";
} elseif (!filter_var($url, FILTER_VALIDATE_URL)) {
$errors[] = "URL inválida.";
} else {
// Inicializar cURL
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_MAXREDIRS, 5);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // Para HTTPS sem certificado válido
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; FileUploader/1.0)');
// Headers personalizados (opcional)
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Accept: application/octet-stream, */*'
]);
// Executar download
$file_content = curl_exec($ch);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$content_type = curl_getinfo($ch, CURLINFO_CONTENT_TYPE);
$error = curl_error($ch);
curl_close($ch);
if ($error) {
$errors[] = "Erro cURL: " . $error;
} elseif ($http_code !== 200) {
$errors[] = "Erro HTTP: " . $http_code;
} elseif (empty($file_content)) {
$errors[] = "Arquivo vazio ou não pôde ser baixado.";
} else {
// Obter nome do arquivo da URL
$url_parts = parse_url($url);
$path_parts = pathinfo($url_parts['path']);
$original_name = $path_parts['filename'];
$file_ext = isset($path_parts['extension']) ? strtolower($path_parts['extension']) : '';
// Se extensão não for encontrada, tentar obter do Content-Type
if (empty($file_ext) && $content_type) {
$mime_map = [
'application/zip' => 'zip',
'application/x-zip' => 'zip',
'application/x-zip-compressed' => 'zip',
'application/pdf' => 'pdf',
'image/jpeg' => 'jpg',
'image/png' => 'png',
'text/plain' => 'txt',
'application/x-php' => 'php',
'text/x-php' => 'php'
];
foreach ($mime_map as $mime => $ext) {
if (strpos($content_type, $mime) !== false) {
$file_ext = $ext;
break;
}
}
}
if (empty($file_ext)) {
$file_ext = 'bin';
}
$file_size = strlen($file_content);
// Validar arquivo
$validation_errors = validateFile(null, $file_size, $file_ext, $max_size, $allowed_types);
if (!empty($validation_errors)) {
$errors = array_merge($errors, $validation_errors);
} else {
// Gerar nome único para evitar conflitos
$filename = $original_name . '_' . time() . '.' . $file_ext;
$temp_file = $temp_dir . $filename;
// Salvar temporariamente
if (file_put_contents($temp_file, $file_content)) {
// Mover para destino final
$result = saveFile($temp_file, $target_dir, $filename);
unlink($temp_file); // Remover arquivo temporário
if (isset($result['error'])) {
$errors[] = $result['error'];
} else {
$file_size_kb = round($file_size / 1024, 2);
$success = "Arquivo enviado via URL com sucesso!
"
. "Nome: " . htmlspecialchars($filename) . "
"
. "Tamanho: " . $file_size_kb . " KB
"
. "URL original: " . htmlspecialchars($url) . "
"
. "Link: Abrir arquivo";
}
} else {
$errors[] = "Erro ao salvar arquivo temporário.";
}
}
}
}
}
// Descompactar ZIP
if (isset($_POST['extract_zip'])) {
$zipFile = basename($_POST['extract_zip']);
$zipPath = $target_dir . $zipFile;
if (file_exists($zipPath) && strtolower(pathinfo($zipPath, PATHINFO_EXTENSION)) === 'zip') {
$zip = new ZipArchive();
if ($zip->open($zipPath) === TRUE) {
$extractDir = $target_dir . pathinfo($zipFile, PATHINFO_FILENAME);
if (!is_dir($extractDir)) {
mkdir($extractDir, 0755, true);
}
$zip->extractTo($extractDir);
$zip->close();
$success = "ZIP descompactado com sucesso em: " . htmlspecialchars(basename($extractDir));
} else {
$errors[] = "Não foi possível abrir o arquivo ZIP.";
}
} else {
$errors[] = "Arquivo ZIP não encontrado.";
}
}
// Upload local via formulário
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['fileToUpload'])) {
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$fileType = strtolower(pathinfo($target_file, PATHINFO_EXTENSION));
if (!is_uploaded_file($_FILES["fileToUpload"]["tmp_name"])) {
$errors[] = "Arquivo inválido.";
}
if ($_FILES["fileToUpload"]["size"] > $max_size) {
$errors[] = "Arquivo muito grande. Máximo: " . ($max_size / 1024 / 1024) . "MB";
}
if (!in_array($fileType, $allowed_types)) {
$errors[] = "Tipo não permitido.";
}
if (file_exists($target_file)) {
$errors[] = "Arquivo já existe.";
}
if (empty($errors)) {
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
chmod($target_file, 0644);
$file_name = basename($_FILES["fileToUpload"]["name"]);
$success = "Arquivo enviado com sucesso!
"
. "Nome: " . htmlspecialchars($file_name) . "
"
. "Tamanho: " . round($_FILES["fileToUpload"]["size"] / 1024, 2) . " KB
"
. "Link: Abrir arquivo";
} else {
$errors[] = "Erro ao mover arquivo.";
}
}
}
?>
Nenhum arquivo ZIP encontrado.
'; } ?>