Ir para conteúdo
Fórum Script Brasil

Pesquisar na Comunidade

Mostrando resultados para as tags ''upload''.

  • Pesquisar por Tags

    Digite tags separadas por vírgulas
  • Pesquisar por Autor

Tipo de Conteúdo


Fóruns

  • Programação & Desenvolvimento
    • ASP
    • PHP
    • .NET
    • Java
    • C, C++
    • Delphi, Kylix
    • Lógica de Programação
    • Mobile
    • Visual Basic
    • Outras Linguagens de Programação
  • WEB
    • HTML, XHTML, CSS
    • Ajax, JavaScript, XML, DOM
    • Editores
  • Arte & Design
    • Corel Draw
    • Fireworks
    • Flash & ActionScript
    • Photoshop
    • Outros Programas de Arte e Design
  • Sistemas Operacionais
    • Microsoft Windows
    • GNU/Linux
    • Outros Sistemas Operacionais
  • Softwares, Hardwares e Redes
    • Microsoft Office
    • Softwares Livres
    • Outros Softwares
    • Hardware
    • Redes
  • Banco de Dados
    • Access
    • MySQL
    • PostgreSQL
    • SQL Server
    • Demais Bancos
  • Segurança e Malwares
    • Segurança
    • Remoção De Malwares
  • Empregos
    • Vagas Efetivas
    • Vagas para Estágios
    • Oportunidades para Freelances
  • Negócios & Oportunidades
    • Classificados & Serviços
    • Eventos
  • Geral
    • Avaliações de Trabalhos
    • Links
    • Outros Assuntos
    • Entretenimento
  • Script Brasil
    • Novidades e Anúncios Script Brasil
    • Mercado Livre / Mercado Sócios
    • Sugestões e Críticas
    • Apresentações

Encontrar resultados em...

Encontrar resultados que...


Data de Criação

  • Início

    FIM


Data de Atualização

  • Início

    FIM


Filtrar pelo número de...

Data de Registro

  • Início

    FIM


Grupo


AIM


MSN


Website URL


ICQ


Yahoo


Jabber


Skype


Location


Interests

  1. Pessoal Boa Tarde, primeiro tópico meu. Preciso de uma grande ajuda, tenho um arquivo XML com vários cadastros de anúncios com múltiplas fotos informadas por URL em cada registro. Até consegui fazer o processo de importação de upload para meu servidor, porém quando executo o script até pela rotina cron no meu cpanel, o processamento pára no meio, nunca conclui. Já fiz um teste incluindo apenas os registros no banco de dados e o processamento é executado normalmente. Porém quando executo juntamente com o upload, o processamento não continua. Segue abaixo o bloco no qual é feito o loop para localizar todas as imagens e fazer o upload a partir do método copy, file_put_contents, curl, ou essa função ai que criei. Já tentei utilizar o método set_time_limit(0); dentro do script, porém sem sucesso. Por enquanto não tenho acesso ao arquivo php.ini no meu servidor, será que apenas alterando esse arquivo eu resolvo meu problema ou posso fazer esse upload de outra forma? Agradeço a atenção.
  2. Boa tarde, sou iniciante em php e estou querendo fazer um upload múltiplo de imagens com o banco de dados MySQL, venho procurado vários modelos na internet, mas nenhum funcionou corretamente, tentei até fazer correções. Hoje encontrei este código abaixo, que está funcionando corretamente, mas eu não estou conseguindo fazer a alteração de nome, por exemplo, a primeira foto inserida, seria foto1, a segunda inserida, foto2, e assim por diante, pois está inserindo com o nome original da imagem... Pois cada "conjunto" de fotos, ficariam em diferentes pastas que são de usuários, coisa que já está pronta, ou seja, gostaria de fazer agora essa alteração, pois em cada pasta de usuário, teria as fotos denominadas "foto1, foto2..." Será que podem me ajudar? Segue o código abaixo. O CÓDIGO NÃO É MEU, EU GOSTARIA DE ENTENDÊ-LO SE FOSSE POSSÍVEL, mas está realmente muito difícil, agradeço por qualquer forma de ajuda. index.php <?php include "conexao.inc"; ?> <form action="valida.php" method="POST" enctype="multipart/form-data"> <input type="file" name="files[]" accept="image/*" multiple/> <input type="submit"/><br><br> <?php $files = glob("user_data/*.*"); for ($i=1; $i<count($files); $i++) { $num = $files[$i]; echo ' <li--><img alt="random image" src="'.$num.'" style="width:200px;height:200px" />'; } ?> </form> valida.php <?php include "conexao.inc"; if(isset($_FILES['files'])){ $errors= array(); foreach($_FILES['files']['tmp_name'] as $key => $tmp_name ){ $file_name = $key.$_FILES['files']['name'][$key]; $file_size =$_FILES['files']['size'][$key]; $file_tmp =$_FILES['files']['tmp_name'][$key]; $file_type=$_FILES['files']['type'][$key]; if($file_size > 2097152){ $errors[]='File size must be less than 2 MB'; } $query="INSERT into upload_data (`FILE_NAME`,`FILE_SIZE`,`FILE_TYPE`) VALUES('$file_name','$file_size','$file_type'); "; $desired_dir="user_data"; if(empty($errors)==true){ if(is_dir($desired_dir)==false){ mkdir("$desired_dir", 0700); // Create directory if it does not exist } if(is_dir("$desired_dir/".$file_name)==false){ move_uploaded_file($file_tmp,"$desired_dir/".$file_name); }else{ // rename the file if another one exist $new_dir="$desired_dir/".$file_name.time(); rename($file_tmp,$new_dir) ; } mysqli_query($conexao, $query); }else{ print_r($errors); } } if(empty($error)){ echo $file_name; echo $file_tmp; echo "Success"; } } ?>
  3. Marlon Mazotti

    Erro no Upload

    Olá Pessoa, Estou utilizando esse script do codeigniter. ´Já coloquei permissão 777 na pasta "tmp" no servidor "/home/meu_site/public_html/html/tmp" Porém ainda estou recebendo a mensagem de "The upload destination folder does not appear to be writable." Alguém poderia me ajudar? Segue o script: <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * CodeIgniter * * An open source application development framework for PHP 5.1.6 or newer * * @package CodeIgniter * @author ExpressionEngine Dev Team * @copyright Copyright (c) 2008 - 2011, EllisLab, Inc. * @license http://codeigniter.com/user_guide/license.html * @link http://codeigniter.com * @since Version 1.0 * @filesource */ // ------------------------------------------------------------------------ /** * File Uploading Class * * @package CodeIgniter * @subpackage Libraries * @category Uploads * @author ExpressionEngine Dev Team * @link http://codeigniter.com/user_guide/libraries/file_uploading.html */ class CI_Upload { public $max_size = 0; public $max_width = 0; public $max_height = 0; public $max_filename = 0; public $allowed_types = ""; public $file_temp = ""; public $file_name = ""; public $orig_name = ""; public $file_type = ""; public $file_size = ""; public $file_ext = ""; public $upload_path = ""; public $overwrite = FALSE; public $encrypt_name = FALSE; public $is_image = FALSE; public $image_width = ''; public $image_height = ''; public $image_type = ''; public $image_size_str = ''; public $error_msg = array(); public $mimes = array(); public $remove_spaces = TRUE; public $xss_clean = FALSE; public $temp_prefix = "temp_file_"; public $client_name = ''; protected $_file_name_override = ''; /** * Constructor * * @access public */ public function __construct($props = array()) { if (count($props) > 0) { $this->initialize($props); } log_message('debug', "Upload Class Initialized"); } // -------------------------------------------------------------------- /** * Initialize preferences * * @param array * @return void */ public function initialize($config = array()) { $defaults = array( 'max_size' => 0, 'max_width' => 0, 'max_height' => 0, 'max_filename' => 0, 'allowed_types' => "", 'file_temp' => "", 'file_name' => "", 'orig_name' => "", 'file_type' => "", 'file_size' => "", 'file_ext' => "", 'upload_path' => "", 'overwrite' => FALSE, 'encrypt_name' => FALSE, 'is_image' => FALSE, 'image_width' => '', 'image_height' => '', 'image_type' => '', 'image_size_str' => '', 'error_msg' => array(), 'mimes' => array(), 'remove_spaces' => TRUE, 'xss_clean' => FALSE, 'temp_prefix' => "temp_file_", 'client_name' => '' ); foreach ($defaults as $key => $val) { if (isset($config[$key])) { $method = 'set_'.$key; if (method_exists($this, $method)) { $this->$method($config[$key]); } else { $this->$key = $config[$key]; } } else { $this->$key = $val; } } // if a file_name was provided in the config, use it instead of the user input // supplied file name for all uploads until initialized again $this->_file_name_override = $this->file_name; } // -------------------------------------------------------------------- /** * Perform the file upload * * @return bool */ public function do_upload($field = 'userfile') { // Is $_FILES[$field] set? If not, no reason to continue. if ( ! isset($_FILES[$field])) { $this->set_error('upload_no_file_selected'); return FALSE; } // Is the upload path valid? if ( ! $this->validate_upload_path()) { // errors will already be set by validate_upload_path() so just return FALSE return FALSE; } // Was the file able to be uploaded? If not, determine the reason why. if ( ! is_uploaded_file($_FILES[$field]['tmp_name'])) { $error = ( ! isset($_FILES[$field]['error'])) ? 4 : $_FILES[$field]['error']; switch($error) { case 1: // UPLOAD_ERR_INI_SIZE $this->set_error('upload_file_exceeds_limit'); break; case 2: // UPLOAD_ERR_FORM_SIZE $this->set_error('upload_file_exceeds_form_limit'); break; case 3: // UPLOAD_ERR_PARTIAL $this->set_error('upload_file_partial'); break; case 4: // UPLOAD_ERR_NO_FILE $this->set_error('upload_no_file_selected'); break; case 6: // UPLOAD_ERR_NO_TMP_DIR $this->set_error('upload_no_temp_directory'); break; case 7: // UPLOAD_ERR_CANT_WRITE $this->set_error('upload_unable_to_write_file'); break; case 8: // UPLOAD_ERR_EXTENSION $this->set_error('upload_stopped_by_extension'); break; default : $this->set_error('upload_no_file_selected'); break; } return FALSE; } // Set the uploaded data as class variables $this->file_temp = $_FILES[$field]['tmp_name']; $this->file_size = $_FILES[$field]['size']; $this->_file_mime_type($_FILES[$field]); $this->file_type = preg_replace("/^(.+?);.*$/", "\\1", $this->file_type); $this->file_type = strtolower(trim(stripslashes($this->file_type), '"')); $this->file_name = $this->_prep_filename($_FILES[$field]['name']); $this->file_ext = $this->get_extension($this->file_name); $this->client_name = $this->file_name; // Is the file type allowed to be uploaded? if ( ! $this->is_allowed_filetype()) { $this->set_error('upload_invalid_filetype'); return FALSE; } // if we're overriding, let's now make sure the new name and type is allowed if ($this->_file_name_override != '') { $this->file_name = $this->_prep_filename($this->_file_name_override); // If no extension was provided in the file_name config item, use the uploaded one if (strpos($this->_file_name_override, '.') === FALSE) { $this->file_name .= $this->file_ext; } // An extension was provided, lets have it! else { $this->file_ext = $this->get_extension($this->_file_name_override); } if ( ! $this->is_allowed_filetype(TRUE)) { $this->set_error('upload_invalid_filetype'); return FALSE; } } // Convert the file size to kilobytes if ($this->file_size > 0) { $this->file_size = round($this->file_size/1024, 2); } // Is the file size within the allowed maximum? if ( ! $this->is_allowed_filesize()) { $this->set_error('upload_invalid_filesize'); return FALSE; } // Are the image dimensions within the allowed size? // Note: This can fail if the server has an open_basdir restriction. if ( ! $this->is_allowed_dimensions()) { $this->set_error('upload_invalid_dimensions'); return FALSE; } // Sanitize the file name for security $this->file_name = $this->clean_file_name($this->file_name); // Truncate the file name if it's too long if ($this->max_filename > 0) { $this->file_name = $this->limit_filename_length($this->file_name, $this->max_filename); } // Remove white spaces in the name if ($this->remove_spaces == TRUE) { $this->file_name = preg_replace("/\s+/", "_", $this->file_name); } /* * Validate the file name * This function appends an number onto the end of * the file if one with the same name already exists. * If it returns false there was a problem. */ $this->orig_name = $this->file_name; if ($this->overwrite == FALSE) { $this->file_name = $this->set_filename($this->upload_path, $this->file_name); if ($this->file_name === FALSE) { return FALSE; } } /* * Run the file through the XSS hacking filter * This helps prevent malicious code from being * embedded within a file. Scripts can easily * be disguised as images or other file types. */ if ($this->xss_clean) { if ($this->do_xss_clean() === FALSE) { $this->set_error('upload_unable_to_write_file'); return FALSE; } } /* * Move the file to the final destination * To deal with different server configurations * we'll attempt to use copy() first. If that fails * we'll use move_uploaded_file(). One of the two should * reliably work in most environments */ if ( ! @copy($this->file_temp, $this->upload_path.$this->file_name)) { if ( ! @move_uploaded_file($this->file_temp, $this->upload_path.$this->file_name)) { $this->set_error('upload_destination_error'); return FALSE; } } /* * Set the finalized image dimensions * This sets the image width/height (assuming the * file was an image). We use this information * in the "data" function. */ $this->set_image_properties($this->upload_path.$this->file_name); return TRUE; } // -------------------------------------------------------------------- /** * Finalized Data Array * * Returns an associative array containing all of the information * related to the upload, allowing the developer easy access in one array. * * @return array */ public function data() { return array ( 'file_name' => $this->file_name, 'file_type' => $this->file_type, 'file_path' => $this->upload_path, 'full_path' => $this->upload_path.$this->file_name, 'raw_name' => str_replace($this->file_ext, '', $this->file_name), 'orig_name' => $this->orig_name, 'client_name' => $this->client_name, 'file_ext' => $this->file_ext, 'file_size' => $this->file_size, 'is_image' => $this->is_image(), 'image_width' => $this->image_width, 'image_height' => $this->image_height, 'image_type' => $this->image_type, 'image_size_str' => $this->image_size_str, ); } // -------------------------------------------------------------------- /** * Set Upload Path * * @param string * @return void */ public function set_upload_path($path) { // Make sure it has a trailing slash $this->upload_path = rtrim($path, '/').'/'; } // -------------------------------------------------------------------- /** * Set the file name * * This function takes a filename/path as input and looks for the * existence of a file with the same name. If found, it will append a * number to the end of the filename to avoid overwriting a pre-existing file. * * @param string * @param string * @return string */ public function set_filename($path, $filename) { if ($this->encrypt_name == TRUE) { mt_srand(); $filename = md5(uniqid(mt_rand())).$this->file_ext; } if ( ! file_exists($path.$filename)) { return $filename; } $filename = str_replace($this->file_ext, '', $filename); $new_filename = ''; for ($i = 1; $i < 100; $i++) { if ( ! file_exists($path.$filename.$i.$this->file_ext)) { $new_filename = $filename.$i.$this->file_ext; break; } } if ($new_filename == '') { $this->set_error('upload_bad_filename'); return FALSE; } else { return $new_filename; } } // -------------------------------------------------------------------- /** * Set Maximum File Size * * @param integer * @return void */ public function set_max_filesize($n) { $this->max_size = ((int) $n < 0) ? 0: (int) $n; } // -------------------------------------------------------------------- /** * Set Maximum File Name Length * * @param integer * @return void */ public function set_max_filename($n) { $this->max_filename = ((int) $n < 0) ? 0: (int) $n; } // -------------------------------------------------------------------- /** * Set Maximum Image Width * * @param integer * @return void */ public function set_max_width($n) { $this->max_width = ((int) $n < 0) ? 0: (int) $n; } // -------------------------------------------------------------------- /** * Set Maximum Image Height * * @param integer * @return void */ public function set_max_height($n) { $this->max_height = ((int) $n < 0) ? 0: (int) $n; } // -------------------------------------------------------------------- /** * Set Allowed File Types * * @param string * @return void */ public function set_allowed_types($types) { if ( ! is_array($types) && $types == '*') { $this->allowed_types = '*'; return; } $this->allowed_types = explode('|', $types); } // -------------------------------------------------------------------- /** * Set Image Properties * * Uses GD to determine the width/height/type of image * * @param string * @return void */ public function set_image_properties($path = '') { if ( ! $this->is_image()) { return; } if (function_exists('getimagesize')) { if (FALSE !== ($D = @getimagesize($path))) { $types = array(1 => 'gif', 2 => 'jpeg', 3 => 'png'); $this->image_width = $D['0']; $this->image_height = $D['1']; $this->image_type = ( ! isset($types[$D['2']])) ? 'unknown' : $types[$D['2']]; $this->image_size_str = $D['3']; // string containing height and width } } } // -------------------------------------------------------------------- /** * Set XSS Clean * * Enables the XSS flag so that the file that was uploaded * will be run through the XSS filter. * * @param bool * @return void */ public function set_xss_clean($flag = FALSE) { $this->xss_clean = ($flag == TRUE) ? TRUE : FALSE; } // -------------------------------------------------------------------- /** * Validate the image * * @return bool */ public function is_image() { // IE will sometimes return odd mime-types during upload, so here we just standardize all // jpegs or pngs to the same file type. $png_mimes = array('image/x-png'); $jpeg_mimes = array('image/jpg', 'image/jpe', 'image/jpeg', 'image/pjpeg'); if (in_array($this->file_type, $png_mimes)) { $this->file_type = 'image/png'; } if (in_array($this->file_type, $jpeg_mimes)) { $this->file_type = 'image/jpeg'; } $img_mimes = array( 'image/gif', 'image/jpeg', 'image/png', ); return (in_array($this->file_type, $img_mimes, TRUE)) ? TRUE : FALSE; } // -------------------------------------------------------------------- /** * Verify that the filetype is allowed * * @return bool */ public function is_allowed_filetype($ignore_mime = FALSE) { if ($this->allowed_types == '*') { return TRUE; } if (count($this->allowed_types) == 0 OR ! is_array($this->allowed_types)) { $this->set_error('upload_no_file_types'); return FALSE; } $ext = strtolower(ltrim($this->file_ext, '.')); if ( ! in_array($ext, $this->allowed_types)) { return FALSE; } // Images get some additional checks $image_types = array('gif', 'jpg', 'jpeg', 'png', 'jpe'); if (in_array($ext, $image_types)) { if (getimagesize($this->file_temp) === FALSE) { return FALSE; } } if ($ignore_mime === TRUE) { return TRUE; } $mime = $this->mimes_types($ext); if (is_array($mime)) { if (in_array($this->file_type, $mime, TRUE)) { return TRUE; } } elseif ($mime == $this->file_type) { return TRUE; } return FALSE; } // -------------------------------------------------------------------- /** * Verify that the file is within the allowed size * * @return bool */ public function is_allowed_filesize() { if ($this->max_size != 0 AND $this->file_size > $this->max_size) { return FALSE; } else { return TRUE; } } // -------------------------------------------------------------------- /** * Verify that the image is within the allowed width/height * * @return bool */ public function is_allowed_dimensions() { if ( ! $this->is_image()) { return TRUE; } if (function_exists('getimagesize')) { $D = @getimagesize($this->file_temp); if ($this->max_width > 0 AND $D['0'] > $this->max_width) { return FALSE; } if ($this->max_height > 0 AND $D['1'] > $this->max_height) { return FALSE; } return TRUE; } return TRUE; } // -------------------------------------------------------------------- /** * Validate Upload Path * * Verifies that it is a valid upload path with proper permissions. * * * @return bool */ public function validate_upload_path() { if ($this->upload_path == '') { $this->set_error('upload_no_filepath'); return FALSE; } if (function_exists('realpath') AND @realpath($this->upload_path) !== FALSE) { $this->upload_path = str_replace("\\", "/", realpath($this->upload_path)); } if ( ! @is_dir($this->upload_path)) { $this->set_error('upload_no_filepath'); return FALSE; } if ( ! is_really_writable($this->upload_path)) { $this->set_error('upload_not_writable'); return FALSE; } $this->upload_path = preg_replace("/(.+?)\/*$/", "\\1/", $this->upload_path); return TRUE; } // -------------------------------------------------------------------- /** * Extract the file extension * * @param string * @return string */ public function get_extension($filename) { $x = explode('.', $filename); return '.'.end($x); } // -------------------------------------------------------------------- /** * Clean the file name for security * * @param string * @return string */ public function clean_file_name($filename) { $bad = array( "<!--", "-->", "'", "<", ">", '"', '&', '$', '=', ';', '?', '/', "%20", "%22", "%3c", // < "%253c", // < "%3e", // > "%0e", // > "%28", // ( "%29", // ) "%2528", // ( "%26", // & "%24", // $ "%3f", // ? "%3b", // ; "%3d" // = ); $filename = str_replace($bad, '', $filename); return stripslashes($filename); } // -------------------------------------------------------------------- /** * Limit the File Name Length * * @param string * @return string */ public function limit_filename_length($filename, $length) { if (strlen($filename) < $length) { return $filename; } $ext = ''; if (strpos($filename, '.') !== FALSE) { $parts = explode('.', $filename); $ext = '.'.array_pop($parts); $filename = implode('.', $parts); } return substr($filename, 0, ($length - strlen($ext))).$ext; } // -------------------------------------------------------------------- /** * Runs the file through the XSS clean function * * This prevents people from embedding malicious code in their files. * I'm not sure that it won't negatively affect certain files in unexpected ways, * but so far I haven't found that it causes trouble. * * @return void */ public function do_xss_clean() { $file = $this->file_temp; if (filesize($file) == 0) { return FALSE; } if (function_exists('memory_get_usage') && memory_get_usage() && ini_get('memory_limit') != '') { $current = ini_get('memory_limit') * 1024 * 1024; // There was a bug/behavioural change in PHP 5.2, where numbers over one million get output // into scientific notation. number_format() ensures this number is an integer // http://bugs.php.net/bug.php?id=43053 $new_memory = number_format(ceil(filesize($file) + $current), 0, '.', ''); ini_set('memory_limit', $new_memory); // When an integer is used, the value is measured in bytes. - PHP.net } // If the file being uploaded is an image, then we should have no problem with XSS attacks (in theory), but // IE can be fooled into mime-type detecting a malformed image as an html file, thus executing an XSS attack on anyone // using IE who looks at the image. It does this by inspecting the first 255 bytes of an image. To get around this // CI will itself look at the first 255 bytes of an image to determine its relative safety. This can save a lot of // processor power and time if it is actually a clean image, as it will be in nearly all instances _except_ an // attempted XSS attack. if (function_exists('getimagesize') && @getimagesize($file) !== FALSE) { if (($file = @fopen($file, 'rb')) === FALSE) // "b" to force binary { return FALSE; // Couldn't open the file, return FALSE } $opening_bytes = fread($file, 256); fclose($file); // These are known to throw IE into mime-type detection chaos // <a, <body, <head, <html, <img, <plaintext, <pre, <script, <table, <title // title is basically just in SVG, but we filter it anyhow if ( ! preg_match('/<(a|body|head|html|img|plaintext|pre|script|table|title)[\s>]/i', $opening_bytes)) { return TRUE; // its an image, no "triggers" detected in the first 256 bytes, we're good } else { return FALSE; } } if (($data = @file_get_contents($file)) === FALSE) { return FALSE; } $CI =& get_instance(); return $CI->security->xss_clean($data, TRUE); } // -------------------------------------------------------------------- /** * Set an error message * * @param string * @return void */ public function set_error($msg) { $CI =& get_instance(); $CI->lang->load('upload'); if (is_array($msg)) { foreach ($msg as $val) { $msg = ($CI->lang->line($val) == FALSE) ? $val : $CI->lang->line($val); $this->error_msg[] = $msg; log_message('error', $msg); } } else { $msg = ($CI->lang->line($msg) == FALSE) ? $msg : $CI->lang->line($msg); $this->error_msg[] = $msg; log_message('error', $msg); } } // -------------------------------------------------------------------- /** * Display the error message * * @param string * @param string * @return string */ public function display_errors($open = '<p>', $close = '</p>') { $str = ''; foreach ($this->error_msg as $val) { $str .= $open.$val.$close; } return $str; } // -------------------------------------------------------------------- /** * List of Mime Types * * This is a list of mime types. We use it to validate * the "allowed types" set by the developer * * @param string * @return string */ public function mimes_types($mime) { global $mimes; if (count($this->mimes) == 0) { if (defined('ENVIRONMENT') AND is_file(APPPATH.'config/'.ENVIRONMENT.'/mimes.php')) { include(APPPATH.'config/'.ENVIRONMENT.'/mimes.php'); } elseif (is_file(APPPATH.'config/mimes.php')) { include(APPPATH.'config//mimes.php'); } else { return FALSE; } $this->mimes = $mimes; unset($mimes); } return ( ! isset($this->mimes[$mime])) ? FALSE : $this->mimes[$mime]; } // -------------------------------------------------------------------- /** * Prep Filename * * Prevents possible script execution from Apache's handling of files multiple extensions * http://httpd.apache.org/docs/1.3/mod/mod_mime.html#multipleext * * @param string * @return string */ protected function _prep_filename($filename) { if (strpos($filename, '.') === FALSE OR $this->allowed_types == '*') { return $filename; } $parts = explode('.', $filename); $ext = array_pop($parts); $filename = array_shift($parts); foreach ($parts as $part) { if ( ! in_array(strtolower($part), $this->allowed_types) OR $this->mimes_types(strtolower($part)) === FALSE) { $filename .= '.'.$part.'_'; } else { $filename .= '.'.$part; } } $filename .= '.'.$ext; return $filename; } // -------------------------------------------------------------------- /** * File MIME type * * Detects the (actual) MIME type of the uploaded file, if possible. * The input array is expected to be $_FILES[$field] * * @param array * @return void */ protected function _file_mime_type($file) { // We'll need this to validate the MIME info string (e.g. text/plain; charset=us-ascii) $regexp = '/^([a-z\-]+\/[a-z0-9\-\.\+]+)(;\s.+)?$/'; /* Fileinfo extension - most reliable method * * Unfortunately, prior to PHP 5.3 - it's only available as a PECL extension and the * more convenient FILEINFO_MIME_TYPE flag doesn't exist. */ if (function_exists('finfo_file')) { $finfo = finfo_open(FILEINFO_MIME); if (is_resource($finfo)) // It is possible that a FALSE value is returned, if there is no magic MIME database file found on the system { $mime = @finfo_file($finfo, $file['tmp_name']); finfo_close($finfo); /* According to the comments section of the PHP manual page, * it is possible that this function returns an empty string * for some files (e.g. if they don't exist in the magic MIME database) */ if (is_string($mime) && preg_match($regexp, $mime, $matches)) { $this->file_type = $matches[1]; return; } } } /* This is an ugly hack, but UNIX-type systems provide a "native" way to detect the file type, * which is still more secure than depending on the value of $_FILES[$field]['type'], and as it * was reported in issue #750 (https://github.com/EllisLab/CodeIgniter/issues/750) - it's better * than mime_content_type() as well, hence the attempts to try calling the command line with * three different functions. * * Notes: * - the DIRECTORY_SEPARATOR comparison ensures that we're not on a Windows system * - many system admins would disable the exec(), shell_exec(), popen() and similar functions * due to security concerns, hence the function_exists() checks */ if (DIRECTORY_SEPARATOR !== '\\') { $cmd = 'file --brief --mime ' . escapeshellarg($file['tmp_name']) . ' 2>&1'; if (function_exists('exec')) { /* This might look confusing, as $mime is being populated with all of the output when set in the second parameter. * However, we only neeed the last line, which is the actual return value of exec(), and as such - it overwrites * anything that could already be set for $mime previously. This effectively makes the second parameter a dummy * value, which is only put to allow us to get the return status code. */ $mime = @exec($cmd, $mime, $return_status); if ($return_status === 0 && is_string($mime) && preg_match($regexp, $mime, $matches)) { $this->file_type = $matches[1]; return; } } if ( (bool) @ini_get('safe_mode') === FALSE && function_exists('shell_exec')) { $mime = @shell_exec($cmd); if (strlen($mime) > 0) { $mime = explode("\n", trim($mime)); if (preg_match($regexp, $mime[(count($mime) - 1)], $matches)) { $this->file_type = $matches[1]; return; } } } if (function_exists('popen')) { $proc = @popen($cmd, 'r'); if (is_resource($proc)) { $mime = @fread($proc, 512); @pclose($proc); if ($mime !== FALSE) { $mime = explode("\n", trim($mime)); if (preg_match($regexp, $mime[(count($mime) - 1)], $matches)) { $this->file_type = $matches[1]; return; } } } } } // Fall back to the deprecated mime_content_type(), if available (still better than $_FILES[$field]['type']) if (function_exists('mime_content_type')) { $this->file_type = @mime_content_type($file['tmp_name']); if (strlen($this->file_type) > 0) // It's possible that mime_content_type() returns FALSE or an empty string { return; } } $this->file_type = $file['type']; } // -------------------------------------------------------------------- } // END Upload Class /* End of file Upload.php */ /* Location: ./system/libraries/Upload.php */
  4. Bom dia, criei um pequeno sistema em PHP de inserção de arquivos PDF numa base de dados PostgreSQL. Como o sistema é pequeno, não terei problemas de performance e preocupação com backups em diretório ou se alguém vai deletar a imagem no diretório. O tipo de dado do PostgreSQL que insiro o arquivo é o Bytea. No computador de casa, realizo o upload normal, o arquivo abre normal, mas no notebook e computador do trabalho ficam corrompidos. Uma coincidência é que nos computadores que dão erro, o sistema operacional é de 64BITs e consequentemente os programas instalados tem uma versão diferente. O erro que acontece é o seguinte: O arquivo fica corrompido e o PDF não consegue realizar a leitura. Pois bem, realizei o teste da funcionalidade do sistema em 3 computadores distintos. Dos 3 computadores, em apenas 1 computador, funcionou corretamente. Segue a configuração dos computadores: Desde já agradeço se alguém puder me ajudar. Obrigado
  5. Olá! Tenho um servidor dedicado, e dentro dele tem uma página PHP que faz upload, porém as vezes chega em 100% e simplesmente para, independente se o arquivo é grande ou não. Não tenho ideia do que gera esse erro. Alguém sabe o que pode ocasionar esse tipo de erro? Obrigado desde já.
  6. Boa Tarde! Tenho pouco tempo de desenvolvimento no Django + Python. Estou precisando fazer o upload de um arquivo e armazená-lo no banco de dados. Sei que não é uma boa prática como vi nas documentações, porém é um requisito negocial da aplicação. Pesquisei em vários sites e encontrei quase nada sobre isso... Alguém aqui pode me ajudar? Versões: Django 1.10.6, Python 3.5.1, PostgreSQL 9.5.3 Desde já agradeço,
  7. Pessoal sou novo esse é meu primeiro post e venho com uma duvida que me segue a meses é o seguinte eu quero fazer um site com textos e imagens e assim, eu queria poder colocar quantas imagens eu quisesse e poder descrever cada imagem por exemplo por exemplo esse post que mostra um top 10 caso a imagem não abra clique aqui pra ver a página Bom pessoal é isso eu queria poder entender a lógica desde já agradeço
  8. Boa Tarde Galera. Vou tentar explicar essa minha grande dúvida da maneira mais clara possível, vamos lá: Tenho um sistema que recebe um UPLOAD de um arquivo .CSV e insere corretamente no banco de dados todas as colunas e linhas necessárias, até que um cliente chegou a mim me questionando sobre as pastas que eram duplicadas toda vez que ele fazia um novo UPLOAD("e;Pastas duplicadas seriam digamos 2 ou mais vezes o mesmo CNPJ e CPF inseridos), então oque propus a ele foi: Sempre que houver um novo upload ele confere se o CPF/CNPJ já está inserido no banco de dados. 1º -) Se o CPF/CNPJ não estiver inserido no banco de dados ele vai e criar o INSERT de registros normalmente. 2º-) Se o CPF/CNPJ já estiver inserido, ele cria um UPDATE nos registros, e faz o UPDATE dos arquivos com esse novo UPLOAD. Espero que entendam essa minha duvida. <?php include "../_conexao/conexao.php"; //Transferir o arquivo if (isset($_POST['submit'])) { //Importar o arquivo transferido para o banco de dados $sql = mysqli_query($conexao,"SELECT cpf_cnpj FROM semaforo"); $handle = fopen($_FILES['filename']['tmp_name'], "r"); while (($data = fgetcsv($handle, 1000, ";")) !== FALSE) { if ($data[0] != 'situacao_primaria' && !empty($handle)) { $import="INSERT into semaforo(id,situacao_primaria,status,data_indicacao,tipo_de_indicacao,tipo_de_distribuicao,categoria,codigo_penumper,nome_do_cliente,cpf_cnpj,negociadores,tipo_pessoa_cliente,uf,cep,municipio_do_cliente,advogado_gestor_interno,numero_operacao,sistema_origem,numero_operacao_origem,familia_do_produto,codigo_produto,nome_do_produto,codigo_agencia,nome_agencia,descricao_segmento,segmento_secundario,descricao_segmento_secundario,situacao_secundaria,data_recebimento,data_credito_liquidacao,valor_da_operacao,valor_transferido_para_creli,valor_da_divida,valor_saldo_contabil,qdt_dias_atraso,nome_da_garantia,ajuizado,codigo_do_ajuizamento,valor_ajuizado,tipo_de_acao,motivo_da_acao,avalista_nome,avalista_cpf_cnpj,avalista_tipo_pessoa,saldo_cm1,recup_judicial_falencia,escob_adm,data_inclusao_escob)values(null,'$data[0]','$data[1]','$data[2]','$data[3]','$data[4]','$data[5]','$data[6]','$data[7]','$data[8]','$data[9]','$data[10]','$data[11]','$data[12]','$data[13]','$data[14]','$data[15]','$data[16]','$data[17]','$data[18]','$data[19]','$data[20]','$data[21]','$data[22]','$data[23]','$data[24]','$data[25]','$data[26]','$data[27]','$data[28]','$data[29]','$data[30]','$data[31]','$data[32]','$data[33]','$data[34]','$data[35]','$data[36]','$data[37]','$data[38]','$data[39]','$data[40]','$data[41]','$data[42]','$data[43]','$data[44]','$data[45]','$data[46]')"; mysqli_query($conexao, $import) or die(mysqli_error($conexao)); } } fclose($handle); print "<center>Transferir <b>SEMÁFORO</b> por arquivo CSV selecione o arquivo clicando no botão <b>escolher arquivo</b>, e envie clicando no botão <b>upload</b>.</center><br /><br />\n"; print "<form enctype='multipart/form-data' action='#' method='post'>"; print "<center><input size='50' type='file' name='filename'></center><br /><br />\n"; print "<center><input type='submit' name='submit' value='Upload'></center></form>"; //Visualizar formulário de transferência } else { print "<center>Transferir <b>SEMÁFORO</b> por arquivo CSV selecione o arquivo clicando no botão <b>escolher arquivo</b>, e envie clicando no botão <b>upload</b>.</center><br /><br />\n"; print "<form enctype='multipart/form-data' action='#' method='post'>"; print "<center><input size='50' type='file' name='filename'></center><br /><br />\n"; print "<center><input type='submit' name='submit' value='Upload'></center></form>"; } ?> Esse é meu arquivo, espero que consigam me ajudar. Agradeço desde já;
  9. Fiz um formulário de upload de imagens usando PHP (move_uploaded_file),usando este código faço o upload de imagem na pasta upload, e salvo no banco de dados usando UPDATE SET, até aí tudo bem. BANCO DE DADOS INSERINDO IMAGENS E CRIPTOGRAFANDO NOMES PASTA UPLOADS RECEBENDO AS IMAGENS O problema começa quando tenho que editar a imagem e trocar ela por outra usando update, no banco de dados ela substitui o nome da imagem normalmente. mas na pasta upload/ ela acumula as imagens ao invés de substituir elas, o mesmo se eu mandar deletar no banco de dados as imagens continuarão lá na pasta, causando um problema de espaço o que eu posso fazer para resolver isso! quando editar substituir as imagens tambem na pasta e não somente no banco! e quando deletar apagar as imagens na pasta e não somente no banco de dados! O que posso fazer para sanar isso?????
  10. Boa tarde pessoal, Estou tendo uma certa dificuldade, neste arquivo envio multiplas imagens está funcionando, porém preciso redimensioná-las, qual classe vocês indicam e como devo implantar neste código: Desde já agradeço a todos pela ajuda! <?php if(session_is_registered("$var_sessaor")) { ?> <?php include("FCKeditor/fckeditor.php"); include_once ('Redimensiona.php'); $id=$_GET['id']; require('saidas.php'); if(isset($_POST['enviar'])) { $i = 0; foreach ($_FILES['foto']["error"] as $key => $error) { $name = md5(uniqid(rand(),true)); $nome = $name.'.jpg'; $destino = '../imgs/projetos_fotos/' .$nome; move_uploaded_file( $_FILES['foto']['tmp_name'][$i], $destino ); { mysql_query("INSERT INTO projetos_fotos (projetos,foto,legenda) VALUES ('$id','$nome','$legenda')"); } $i++; } throw_alert('Fotos enviadas com sucesso!','?p=projetos_fotos2&id='.$id); } elseif(isset($_GET['foto'])) { $fotoid=$_GET['foto']; $select=mysql_query("SELECT * FROM projetos_fotos WHERE id='$fotoid'"); $vessel=mysql_fetch_array($select); @unlink('../imgs/projetos_fotos/'.$vessel['foto']); $del=mysql_query("DELETE FROM projetos_fotos WHERE id='$fotoid'"); if($del) throw_alert('Foto removida com sucesso.','?p=books_fotos&id='.$vessel['books']); } ?> <!--Stylesheets--> <link href="uploader/jquery.filer.css" type="text/css" rel="stylesheet" /> <link href="uploader/themes/jquery.filer-dragdropbox-theme.css" type="text/css" rel="stylesheet" /> <!--jQuery--> <script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script> <script type="text/javascript" src="uploader/jquery.filer.min.js?v=1.0.5"></script> <script type="text/javascript" src="uploader/custom.js?v=1.0.5"></script> <!--GERAL--> <div class="panel panel-default"> <div style="margin-top:10px; padding:5px;" class="borda"> <h1>Fotos para o Book</h1> <p><a href="?p=projetos" class="btn btn-default" style="width: 115px;">Voltar</a></p> </div> <div class="panel-heading no-collapse"> <span >Cadastrar fotos para: </span> <span style="font-weight:bold;"> <?php $id=$_GET['id']; $select=mysql_query("SELECT * FROM projetos WHERE id='$id'"); $display=mysql_fetch_array($select); print ''.$display['titulo'].''; ?> </span> </div> <!--form--> <div style="margin-top:30px; padding:10px; overflow:hidden; max-width:800px;" > <form action="?p=projetos_fotos2&id=<?php print $id; ?>" method="post" enctype="multipart/form-data"> <input type="file" name="foto[]" id="filer_input" multiple="multiple"> <input type="submit" value="Submit" name="enviar"> </form> </div> <!-- form--> <div class="panel-heading no-collapse" style="margin-top:40px;"> <span >Fotos Cadastradas</span> </div> <!--fotos--> <div style="margin-top:30px; overflow:hidden;"> <?php $sql = mysql_query("SELECT * FROM projetos_fotos WHERE projetos='$id' ORDER BY id DESC LIMIT 100"); while($x = mysql_fetch_array($sql)) { ?> <div align="center" style="width:200px; height:200px; float:left; background-color:#F4F4F4; padding:7px; margin:10px;"> <img src="../imgs/projetos_fotos/<?=$x['foto'];?>" width="185" height="139" border="0" /><br> <!--<div style="font-size:11px; margin-top:10px;">'.$display['legenda'].'</div><br />--> <div align="center" style="margin-top:10px;"> <a href="?p=projetos_fotos&foto=<?=$x['id'];?>" class="btn btn-default" onclick="return confirm('Deseja mesmo remover?')" > Excluir Foto</a> </div> </div> <?php } ?> </div> <!--fotos--> </div> <!--GERAL--> <?php } ?>
  11. Estou implantando o jQuery File Upload. Já consegui mudar a pasta de destino. Os arquivos são salvos no local desejado. Contudo, o preview dos thumbnail e o comando para Excluir imagens não funcionam porque não consigo apontar para a pasta onde as imagens foram subidas. Sempre fica apontando para o local original, onde por default, as fotos ficam gravadas.
  12. Preciso de um script PHP com o nome "selecione o arquivo" e quando eu clique ele abra o Explorer(Gerenciador de Arquivos do Computador) pra escolher somente arquivos em pdf e quero que o pdf vá pra uma determinada pasta no servidor. Algo do tipo: Arraste arquivos aqui para anexar ou escolha os arquivos... Tipo de arquivos permitidos gif, jpeg, jpe, jpg, png Porém pra PDF Alguém mim ajuda?
  13. olá, estou com um duvida, eu queria saber como eu faço para fazer upload de uma imagem por meio do codigo: <form method="post" <input type="file" id="imagem" name="imagem"> <input type="submit" value="salvar"> </form> mas o problema é que eu queria que imprimisse a imagem e não o 'nome.extensão', acho que precisa usar php ou javascript, mas em fim se puder me ajudem.
  14. Olá! Estou iniciando em php e estou com uma dúvida sobre upload de arquivos. Na verdade já conseguir fazer o script de upload, ele envia o arquivo para uma pasta e o nome do arquivo fica gravado num banco de dados mysql conforme podem notar na imagem abaixo. O que eu gostaria de fazer agora é disponibilizar esses arquivos para download em outra página. Na verdade irei subir para o banco/pasta apenas arquivos PDF, e eles precisam estar a disposição do público em outra página. Aqui o código da página de upload que achei aqui mesmo no script brasil. <?php require_once('Connections/conexao.php'); ?> <?php //MX Widgets3 include require_once('includes/wdg/WDG.php'); // Load the common classes require_once('includes/common/KT_common.php'); // Load the tNG classes require_once('includes/tng/tNG.inc.php'); // Make a transaction dispatcher instance $tNGs = new tNG_dispatcher(""); // Make unified connection variable $conn_conexao = new KT_connection($conexao, $database_conexao); //Start Restrict Access To Page $restrict = new tNG_RestrictAccess($conn_conexao, ""); //Grand Levels: Any $restrict->Execute(); //End Restrict Access To Page // Start trigger $formValidation = new tNG_FormValidation(); $tNGs->prepareValidation($formValidation); // End trigger //start Trigger_FileUpload trigger //remove this line if you want to edit the code by hand function Trigger_FileUpload(&$tNG) { $uploadObj = new tNG_FileUpload($tNG); $uploadObj->setFormFieldName("arq_nome"); $uploadObj->setDbFieldName("arq_nome"); $uploadObj->setFolder("arquivos/"); $uploadObj->setMaxSize(5000); $uploadObj->setAllowedExtensions("pdf, txt, doc, rar, zip, jpg, png"); $uploadObj->setRename("auto"); return $uploadObj->Execute(); } //end Trigger_FileUpload trigger // Make an insert transaction instance $ins_arquivos = new tNG_insert($conn_conexao); $tNGs->addTransaction($ins_arquivos); // Register triggers $ins_arquivos->registerTrigger("STARTER", "Trigger_Default_Starter", 1, "POST", "KT_Insert1"); $ins_arquivos->registerTrigger("BEFORE", "Trigger_Default_FormValidation", 10, $formValidation); $ins_arquivos->registerTrigger("END", "Trigger_Default_Redirect", 99, "arquivos.php"); $ins_arquivos->registerTrigger("AFTER", "Trigger_FileUpload", 97); // Add columns $ins_arquivos->setTable("arquivos"); $ins_arquivos->addColumn("arq_nome", "FILE_TYPE", "FILES", "arq_nome"); $ins_arquivos->addColumn("arq_data", "STRING_TYPE", "POST", "arq_data"); $ins_arquivos->addColumn("user_id", "NUMERIC_TYPE", "POST", "user_id", "{SESSION.kt_login_id}"); $ins_arquivos->setPrimaryKey("arq_id", "NUMERIC_TYPE"); // Execute all the registered transactions $tNGs->executeTransactions(); // Get the transaction recordset $rsarquivos = $tNGs->getRecordset("arquivos"); $row_rsarquivos = mysql_fetch_assoc($rsarquivos); $totalRows_rsarquivos = mysql_num_rows($rsarquivos); ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:wdg="http://ns.adobe.com/addt"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Sistema de Upload - Enviar Arquivo</title> <link href="includes/skins/mxkollection3.css" rel="stylesheet" type="text/css" media="all" /> <script src="includes/common/js/base.js" type="text/javascript"></script> <script src="includes/common/js/utility.js" type="text/javascript"></script> <script src="includes/skins/style.js" type="text/javascript"></script> <?php echo $tNGs->displayValidationRules();?> <script type="text/javascript" src="includes/common/js/sigslot_core.js"></script> <script type="text/javascript" src="includes/wdg/classes/MXWidgets.js"></script> <script type="text/javascript" src="includes/wdg/classes/MXWidgets.js.php"></script> <script type="text/javascript" src="includes/wdg/classes/Calendar.js"></script> <script type="text/javascript" src="includes/wdg/classes/SmartDate.js"></script> <script type="text/javascript" src="includes/wdg/calendar/calendar_stripped.js"></script> <script type="text/javascript" src="includes/wdg/calendar/calendar-setup_stripped.js"></script> <script src="includes/resources/calendar.js"></script> </head> <body> <?php echo $tNGs->getErrorMsg(); ?> <form method="post" id="form1" action="<?php echo KT_escapeAttribute(KT_getFullUri()); ?>" enctype="multipart/form-data"> <table cellpadding="2" cellspacing="0" class="KT_tngtable"> <tr> <td class="KT_th"><label for="arq_nome">Arquivos:</label></td> <td><input type="file" name="arq_nome" id="arq_nome" size="32" /> <?php echo $tNGs->displayFieldError("arquivos", "arq_nome"); ?></td> </tr> <tr> <td class="KT_th"><label for="arq_data">Data:</label></td> <td><input name="arq_data" id="arq_data" value="<?php echo KT_escapeAttribute($row_rsarquivos['arq_data']); ?>" size="32" wdg:mondayfirst="true" wdg:subtype="Calendar" wdg:mask="<?php echo $KT_screen_date_format; ?>" wdg:type="widget" wdg:singleclick="true" wdg:restricttomask="no" /> <?php echo $tNGs->displayFieldHint("arq_data");?> <?php echo $tNGs->displayFieldError("arquivos", "arq_data"); ?></td> </tr> <tr class="KT_buttons"> <td colspan="2"><input type="submit" name="KT_Insert1" id="KT_Insert1" value="Enviar Arquivo" /></td> </tr> </table> <input type="hidden" name="user_id" id="user_id" value="<?php echo KT_escapeAttribute($row_rsarquivos['user_id']); ?>" /> </form>
  15. Olá amigos de profissão, venho aqui apresentar uma biblioteca que trabalha com arquivos. Muito boa, além de economizar horas de trabalho, você vai ter uma boa reutilização de código. Em poucos minutos você vai ter um sistema de upload de arquivos, gerador de logs, deletar arquivos, renomear... A biblioteca está na versão 1.0.5 Baixe, use e deixe seu feedback aqui ou no site. Mais informações no site : www.bittenagency.com Abraços.
  16. Veio aqui para pedir uma ajuda... estou com um script de upload aqui e o mesmo faz somente de imagem e eu gostaria de fazer para todos os arquivos (.mp3, .txt...) e ate mesmo imagem como função dele mesmo. Segue abaixo o codigo do mesmo: Desde já obrigado!
  17. Boa tarde pessoal, Tenho o seguinte trecho do cód. <%response.buffer=true Server.ScriptTimeout = 99999999%> <% Set Upload = Server.CreateObject("Persits.Upload.1") Upload.IgnoreNoPost = True Upload.Save "xxx" For Each File in Upload.Files Response.Write "<input type=text size=10 id=upimg_01 value="&File.Filename&">" Next %> Nele eu consigo visualizar nome por nome dos arquivos enviados mas dispostos da seguinte forma: "imagem1.jpg, imagem2.jpg... assim por diante até a imagem 15 pois o upload feito tem 15 imagens no total. Eu preciso que sejam mostrados os nomes das imagens separados pois preciso atribuir uma "id" para cada nome de imagem que será repassado para um novo formulário que ai realiza o cadastro. Só preciso separar o nome de cada imagem em uma input diferente mas não consigo. Se alguém puder ajudar agradeço.
  18. Pessoal, estou fazendo uma página de update de dados que incluem um upload de imagem. Recupero os dados já cadastrados e insiro um campo tipo file para subir nova imagem, se o usuário desejar alterar este dado. A ideia é que, se este campo for definido (imagem nova escolhida) gera novo nome e altera os dados no BD, caso contrário, usar os dados de imagem anteriores ($oldImage). Mas não está funcionando... Segue o código usado: <?php $servicos = new Servicos; $dados = $servicos->listarUm(); if(empty($dados)): echo "Nenhum serviço encontrado"; else: ?> <form id="mainform" action="" method="post" enctype="multipart/form-data"> <label for="nome_servico" class="texto">Nome do Servi&ccedil;o: </label> <input type="text" name="nome_servico" class="input" value="<?php echo $dados->nome_servico; ?>"/> <br><br> <label for="descricao" class="texto">Descri&ccedil;&atilde;o do Servi&ccedil;o: </label> <textarea name="descricao" rows="" cols="" class="form-textarea"><?php echo $dados->descricao; ?></textarea> <br><br> <label for="oldImage" class="texto">Imagem Atual: </label> <img src="<?php echo $dados->imagem; ?>" width="352" height="184" name="oldImage"/> <input type="hidden" name="oldImage" value="<?php echo $dados->imagem; ?>"/> <br><br> <?php endif; ?> <label for="figura" class="texto">Alterar Imagem: </label> <table cellpadding="0" cellspacing="0" id="id-form"> <tr> <td><input type="file" name="figura" class="file_1" placeholder="Nenhuma imagem selecionada"/></td> <td> <div><a href="#" class="info"><img src="images/icons/help_p.gif"/><span>Selecione imagens sempre em formato horizontal, com as dimensões 352px de largura por 184px de altura, com as extensões PNG ou JPEG.</span></a></div> </td> </tr> </table> <br><br> <label for="fsubmit"></label> <input type="submit" name="ok" class="inputBtn" value="Atualizar" title="Atualizar"/> </form> <div class="box-evento"> <?php if(isset($_POST['ok'])): /*recuperar dados do formulário*/ $id = $_GET['id']; $nome_servico = $_POST['nome_servico']; $descricao = $_POST['descricao']; $oldImage = $_POST['oldImage']; $figura = $_FILES['figura']['name']; $temporario = $_FILES['figura']['tmp_name']; if($_FILES['figura']=""){ $imagem = $oldImage; } else if(isset($_FILES['figura'])){ define("PASTA_IMG", "imgs/"); /*Renomear a foto*/ $extensao = end(explode(".", $figura)); $novoNome = uniqid().".".$extensao; move_uploaded_file($_FILES['figura']['tmp_name'], PASTA_IMG.$novoNome); $imagem = PASTA_IMG.$novoNome; } $dataUpdate = array( $nome_servico, $imagem, $descricao, $id ); /*cadastrar no banco de dados*/ $servicos = new Servicos; $servicos->atualizar($dataUpdate); ?> <div class="status2"><?php echo "Registro atualizado com sucesso" .$nome_servico. ", " .$imagem. ", " .$descricao. ", " .$id. ", " .$novoNome. ", " .$oldImage. ", " .$_FILES['figura']; //atualizar($dataUpdate); ?></div> <?php endif; ?> </div>No retorno, estou dando um echo para verificar os dados que estão sendo enviados. E sempre cai como se o campo estivesse definido, mesmo que eu não escolha uma imagem no campo "figura". Há uma classe Servicos.php, que possui as funções listarUm() e atualizar(). Alguém poderia me ajudar a entender o que está acontecendo e como resolver? Muito obrigado pela ajuda!
  19. Boa tarde, pessoal! Criei um formulário simples para o usuário fazer a importação de um arquivo TXT, com <input type="file" name="arquivo">. No código PHP que faz a importação, se eu já definir o nome do arquivo, $file = fopen("clientes.txt","r") funciona 100%. Mas o que eu preciso é criar uma variável que armazene o nome do arquivo que o usuário selecionar quando clicar no botão <Escolher Arquivo> do formulário de importação. Já pesquisei em vários fóruns mas todos os códigos de importação de dados já trazem o nome do arquivo pré-definido em fopen(). Se alguém puder me dar uma ideia, pois já tentei os métodos $_POST['arquivo'], $_FILES['ufile']['name'] e não deu certo...
  20. mostapha

    Upload arquivo .rar

    Bom dia, Preciso de ajuda para melhorar meu código upload de arquivo. <?php /* pasta que voce deseja salvar o arquivo*/ $uploaddir = 'uploads'; //nome da pasta onde vai salvar $uploadfile = $uploaddir . $_FILES['arquivo']['name']; //dentro FILES vai nome do input file do index.php if(move_uploaded_file($_FILES['arquivo']['tmp_name'], $uploadfile)){ echo("Arquivo Enviado"); }else{ echo("Arquivo não foi possivel Salvar"); } ?> preciso fazer com que aceite apenas arquivos .rar preciso salvar os dados em um pasta na minha rede -> caminho( \\192.168.10.16\Link\dpj ) agradeceria muito se alguém me ajuda-se Att...
  21. Bom dia, sou iniciante no desenvolvimento web. Estou desenvolvendo um site que deverá ter uma página de contato com envio de email e upload de foto para meu cliente, porém, não faço a mínima ideia da média de preço que deveria cobrar. Estou utilizando php, html5 e jquery. Alguém poderia me dar uma base? Obrigada.
  22. Não entendo muito de PHP, mas estou tentando criar um explorador de arquivos, onde as pessoas possam fazer upload/download de arquivos, criar pastas, renomear/mover/deletar pastas e arquivos. Tudo isso sem permissões especiais de usuário ou senha. O que tenho até agora é isso: Dentro da pasta public_html\: upload.html <form action="upload.php" enctype="multipart/form-data" method="POST"> Enviar o arquivo: <input name="arquivo" size="20" type="file" /> <input type="submit" value="Enviar" /> </form> <font size=1><h2 align="middle"><a href="http://updroid.com.br\">Voltar</a></center>"); echo "<h1>OBS: Para fazer o download de um arquivo, clique sobre ele com o botão direito do mouse e selecione Salvar link como...</h1>"; ?> LINKS: http://www.updroid.com.br/upload.html http://www.updroid.com.br/download/download.php Grato pela atenção e ajuda de todos, Lucas M. Fernandes
  23. Pessoal, Sou novo aqui no forum, gostaria de saber se é possivel fazer o upload de apenas um pedaço de arquivo com javascript. EX: tenho um arquivo de 5GB e gostarai de fazer o upload do primeiro 1MB. É possivel com javascript? Obrigado!
  24. Boa tarde, pessoal! Estou com o seguinte problema: Estou desenvolvendo um administrador para um site e preciso enviar um arquivo '.zip' ou '.exe' para o servidor de hospedagem só que quando faço isso utilizando move_upload ou ftp_put com arquivo pequeno funciona mas com arquivo grande não funciona. Tem como eu fazer upload de arquivo com mais de 7MB para o servido? Desde já, obrigado!
  25. Heltinhu

    Upload múltiplo

    Olá pessoal seguinte... Tenho um pequeno script php que é para cadastro de imagens em uma TABELA para uma galeria de FOTOS DE IMÓVEIS e ao mesmo tempo pegar os dados do imóvel e cadastrar EM OUTRA TABELA. Bom a principio ela esta funcionando pois o script pega todas as fotos que irão ser upadas manda elas para uma pasta, cadastra o nome delas no banco de dados em uma tabela GALERIA e também pega os dados do imóvel e cadastra estes dados em TABELA chamada IMOVEIS. Porém agora é que vem o meu problema digamos que eu selecione 5 fotos de imóveis certo para cada foto que for cadastrada ele irá fazer o cadastro para imóveis, ou seja, terá 5 cadastros de imóveis repetidos sendo que o que eu quero é apenas um cadastro de imóvel com as 5 fotos deste respectivo imóvel. Segue o script... <?php if(isset($_POST['upload'])){ $IdImovel = $_POST['IdImovel']; $Categoria = $_POST['Categoria']; $Titulo = $_POST['Titulo']; $Valor = $_POST['Valor']; $Cidade = $_POST['Cidade']; $Estado = $_POST['Estado']; //INFO IMAGEM $file = $_FILES['img']; $numFile = count(array_filter($file['name'])); //PASTA PARA UPLOAD $folder = '../uploads'; //REQUISITOS $permite = array('image/jpeg', 'image/png'); $maxSize = 1024 * 1024 * 5; //MENSAGENS $msg = array(); $errorMsg = array( 1 => 'Imagem maior que o limite', 2 => 'o arquivo ultrapassa o limite', 3 => 'upload feito parcialmente', 4 =>'Não foi feito' ); if($numFile <= 0) echo'Selecione uma imagem'; else{ for($i = 0; $i < $numFile; $i++){ $name = $file['name'][$i]; $type = $file['type'][$i]; $size = $file['size'][$i]; $error = $file['error'][$i]; $tmp = $file['tmp_name'][$i]; $extensao = end(explode('.', $name)); $novoNome = 'nome' .rand().".$extensao"; if($error != 0) $msg[''] = "<b> $name:</b>".$errorMsg[$error]; else if(!in_array($type, $permite)) $msg[] = "<b>$name:</b> Erro imagem não suportada!"; else if($size > $maxSize) $msg[] = "<b>$name:</b> Erro imagem ultrapassa limite de 5MB!"; else{ if(move_uploaded_file($tmp, $folder."/".$novoNome)) $sqlFotos = mysql_query("INSERT INTO galeria (IdImovel,imagem) VALUES ('$IdImovel','$novoNome')"); $sqlImoveis = mysql_query("INSERT INTO imoveis (CatID,Titulo,Valor,Cidade,Estado) VALUES ('$Categoria','$Titulo','$Valor','$Cidade','$Estado')"); echo '<script>alert("Cadastro realizado com sucesso")</script>'; } foreach($msg as $pop) echo $pop.'<br>'; } } } ?>
×
×
  • Criar Novo...