Ir para conteúdo

POWERED BY:

Arquivado

Este tópico foi arquivado e está fechado para novas respostas.

Andre Summers

upload de imagens em php

Recommended Posts

Fiz um sistema de upload para enviar três arquivos de uma vez. Ele ta funcionando e talz. Mas quero que ele salve as imagens num servidor e guarde o caminho da imagem num banco de dados, pra ser usado numa posterior consulta (para ser baixado do servidor) e num e-mail de confirmação.Deu pra entender o quero? Dá pra me ajudarem, por favor? Já não sei mais onde procurar...PS: se souberem tb como limitar o tamanho dos arquivos enviados, agradeço.

Compartilhar este post


Link para o post
Compartilhar em outros sites

não tá dando certo. vou postar as paginas do sistema de upload. Me deem uma força

 

 

pagina upload.php

<html>	<head><title>Upload</title>	<style type="text/css"><!--.style1 {	font-size: 9px;	font-family: Georgia, "Times New Roman", Times, serif;	font-weight: bold;}.style2 {	font-family: "Times New Roman", Times, serif;	font-size: 12px;}.style3 {font-size: 12px}.style4 {font-family: "Times New Roman", Times, serif}-->	</style>	</head><body><?phprequire("fileuploadclass.php");#--------------------------------## Variables#--------------------------------#// The path to the directory where you want the // uploaded files to be saved. This MUST end with a // trailing slash unless you use $path = ""; to // upload to the current directory. Whatever directory// you choose, please chmod 777 that directory.	$path = "uploads/";// The name of the file field in your form.	$upload_file_name = "userfile";	$upload_file_name2 = "userfile2";	$upload_file_name3 = "userfile3"; // ACCEPT mode - if you only want to accept// a certain type of file.// possible file types that PHP recognizes includes://// OPTIONS INCLUDE://  text/plain//  image/gif//  image/jpeg//  image/png		// Accept ONLY gifs's	#$acceptable_file_types = "image/gifs";		// Accept GIF and JPEG files	#$acceptable_file_types = "image/gif|image/cdr|image/jpeg|image/pjpeg";	// Accept ALL files	$acceptable_file_types = "";// If no extension is supplied, and the browser or PHP// can not figure out what type of file it is, you can// add a default extension - like ".jpg" or ".txt"	$default_extension = ".cdr";// MODE: if your are attempting to upload// a file with the same name as another file in the// $path directory//// OPTIONS://   1 = overwrite mode//   2 = create new with incremental extention//   3 = do nothing if exists, highest protection	$mode = 2;#--------------------------------## PHP#--------------------------------#	if ($_REQUEST['submitted']) {		// Create a new instance of the class		$my_uploader = new uploader;		$my_uploader2 = new uploader;		$my_uploader3 = new uploader;				// OPTIONAL: set the max filesize of uploadable files in bytes		$my_uploader->max_filesize(300000);		$my_uploader2->max_filesize(300000);		$my_uploader3->max_filesize(300000);						// UPLOAD do arquivo		if ($my_uploader->upload($upload_file_name, $acceptable_file_types, $default_extension)) {			$success = $my_uploader->save_file($path, $mode);		}				if ($success) {			// upload concluido com sucesso!			print($my_uploader->file['name'] . " foi enviado com sucesso!<br>  <a href=\"" . $_SERVER['PHP_SELF'] . "\">O arquivo já foi armazenado em nosso servidor. Quer enviar mais arquivos? Esteja a vontade.</a><br>");						// Imprime todos os detalhes do array ...			print_r($my_uploader->file);						// Erro no upload... 			if($my_uploader->errors) {				while(list($key, $var) = each($my_uploader->errors)) {					echo $var . "<br>";				} 			} 		}// UPLOAD de arquivo 2		if ($my_uploader2->upload($upload_file_name2, $acceptable_file_types, $default_extension)) {			$success = $my_uploader2->save_file($path, $mode);		}				if ($success) {			// upload concluido com sucesso!			print("<br><br>".$my_uploader2->file['name'] . " foi enviado com sucesso!<br>  <a href=\"" . $_SERVER['PHP_SELF'] . "\">O arquivo já foi armazenado em nosso servidor. Quer enviar mais arquivos? Esteja a vontade.</a><br>");						// Imprime todos os detalhes do array ...			print_r($my_uploader2->file);						// Erro no upload... 			if($my_uploader2->errors) {				while(list($key, $var) = each($my_uploader2->errors)) {					echo $var . "<br>";				} 			} 		} // UPLOAD de arquivo 3		if ($my_uploader3->upload($upload_file_name3, $acceptable_file_types, $default_extension)) {			$success = $my_uploader3->save_file($path, $mode);		}				if ($success) {			// upload comcluido com sucesso!			print("<br><br>".$my_uploader3->file['name'] . " foi enviado com sucesso!<br>  <a href=\"" . $_SERVER['PHP_SELF'] . "\">O arquivo já foi armazenado em nosso servidor. Quer enviar mais arquivos? Esteja a vontade.</a><br>");						// Imprime todos os detalhes do array ...			print_r($my_uploader3->file);						// Erro no upload... 			if($my_uploader3->errors) {				while(list($key, $var) = each($my_uploader3->errors)) {					echo $var . "<br>";				} 			} 		}   }#--------------------------------## HTML FORM#--------------------------------#?><?php $host_bd = "meumysql.dialhost.com.br";//Host da conexão										   $usuario_bd = "aluguel_user";//Nome de usuário do banco de dados						 $senha_bd = "senha";//Senha do usuário do banco de dados							$banco_bd = "algo_bancos";//Nome do banco de dados								 ?><?$connection = @mysql_connect("$host_bd","$usuario_bd","$senha_bd") or die(mysql_error());$db = @mysql_select_db("$banco_bd", $connection) or die(mysql_error());$sql = "SELECT login FROM usuarios_padrao";$sql_result = @mysql_query($sql,$connection) or die(mysql_error());if (mysql_num_rows($sql_result) == 0){echo "nome não encontrado";} while ($row = @mysql_fetch_array ($sql_result)){$login = $row["login"];}echo "<br><br><br>Seja bem vindo, <b>$login</b>.";?><br><br>	<form enctype="multipart/form-data" action="<?= $_SERVER['../../Documents%20and%20Settings/Thiago2/Desktop/WWW.SUPERTRAFEGO.COM__upload/fileupload/fileupload/PHP_SELF']; ?>" method="POST">	<input type="hidden" name="submitted" value="true">		Faça o Upload dos arquivos desejados:<br>		<span class="style1">*Limite máximo de<span class="style3"> <span class="style4">10</span></span> <span class="style2">MB</span> por envio</span>	  <br>		<input name="<?= $upload_file_name; ?>" type="file">		<input name="verso" type="radio" value="4/0">		4/0 		<input name="verso" type="radio" value="4/1">		4/1		<input name="verso" type="radio" value="4/4">		4/4 		<input name="quantidade1" type="text" id="quantidade1" size="9" maxlength="20">		(Quantidade)<br>		<input name="<?= $upload_file_name2; ?>" type="file">		<input name="verso2" type="radio" value="4/0">		4/0 		<input name="verso2" type="radio" value="4/1">		4/1 		<input name="verso2" type="radio" value="4/4">		4/4 		<input name="quantidade2" type="text" id="quantidade2" size="9" maxlength="20">		(Quantidade)<br>		<input name="<?= $upload_file_name3; ?>" type="file">		 <input name="verso3" type="radio" value="4/0">		 4/0 		 <input name="verso3" type="radio" value="4/1">		 4/1 		 <input name="verso3" type="radio" value="4/4">		 4/4 		 <input name="quantidade3" type="text" id="quantidade3" size="9" maxlength="20">		 (Quantidade)<br> 		  		<input type="submit" value="Enviar arquivo">	</form><?php	if ($acceptable_file_types) {		print("Este formulário só aceita <b>" . str_replace("|", " ou ", $acceptable_file_types) . "</b> files\n");	}?></body></html>

 

 

 

pagina fileuploadclass.php

<?# =================================================================== ### iMarc PHP Library# Copyright 1999, 2002 David Fox, Angryrobot Productions #				(See below for full license)# # VERSION: 2.1# LAST UPDATE: 2002-06-04# CONTENT: PHP file upload class## =================================================================== ## # USAGE and SETUP instructions at the bottom of this page (README)# # =================================================================== #/*	METHODS:		max_filesize() 		- set a max filesize in bytes		max_image_size() 	- set max pixel dimenstions for image uploads		upload() 			- checks if file is acceptable, uploads file to server's temp directory		save_file() 		- moves the uploaded file and renames it depending on the save_file($overwrite_mode)				cleanup_text_file()	- (private class function) convert Mac and/or PC line breaks to UNIX	Error codes:		$errors[0] - "No file was uploaded"		$errors[1] - "Maximum file size exceeded"		$errors[2] - "Maximum image size exceeded"		$errors[3] - "Only specified file type may be uploaded"		$errors[4] - "File already exists" (save only)*/# ------------------------------------------------------------------- ## UPLOADER CLASS# ------------------------------------------------------------------- #class uploader {	var $file;	var $errors;	var $accepted;	var $max_filesize;	var $max_image_width;	var $max_image_height;	# ----------------------------------- #	# FUNCTION: 	max_filesize 	# DESCRIPTION: 	Set the maximum file size in bytes ($size), allowable by the object.	#	# ARGS: 		$size			(int) file size in bytes	#	# NOTE: PHP's configuration file also can control the maximum upload size, which is set to 2 or 4 	# megs by default. To upload larger files, you'll have to change the php.ini file first.	# ----------------------------------- #	function max_filesize($size){		$this->max_filesize = $size;	}	# ----------------------------------- #	# FUNCTION: 	max_image_size 	# DESCRIPTION: 	Sets the maximum pixel dimensions for image uploads	#	# ARGS: 		$width 			(int) maximum pixel width of image uploads	#				$height			(int) maximum pixel height of image uploads	# ----------------------------------- #	function max_image_size($width, $height){		$this->max_image_width  = $width;		$this->max_image_height = $height;	}	# ----------------------------------- #	# FUNCTION: 	upload 	# DESCRIPTION: 	Checks if the file is acceptable and copies it to 	# 	# ARGS: 		$filename		(string) form field name of uploaded file	#				$accept_type	(string) acceptable mime-types	#				$extension		(string) default filename extenstion	# ----------------------------------- #	function upload($filename='', $accept_type='', $extention='') {		if (!$filename || $filename == "none") {			$this->errors[0] = "Nenhum arquivo foi enviado";			$this->accepted  = FALSE;			return FALSE;		}				// Copy PHP's global $_FILES array to a local array		$this->file = $_FILES[$filename];		$this->file['file'] = $filename;				// test max size		if($this->max_filesize && ($this->file["size"] > $this->max_filesize)) {			$this->errors[1] = "Limite máximo de tamanho excedido. O arquivo não pode ter mais que " . $this->max_filesize/1000 . "KB (" . $this->max_filesize . " bytes).";			$this->accepted  = FALSE;			return FALSE;		}	 		 	if(ereg("image", $this->file["type"])) {	 			 		/* IMAGES */	 			 		$image = getimagesize($this->file["tmp_name"]);	 		$this->file["width"]  = $image[0];	 		$this->file["height"] = $image[1];						// test max image size			if(($this->max_image_width || $this->max_image_height) && (($this->file["width"] > $this->max_image_width) || ($this->file["height"] > $this->max_image_height))) {				$this->errors[2] = "Limite máximo de tamanho excedido. A imagem não pode ter mais que " . $this->max_image_width . " x " . $this->max_image_height . " pixels";				$this->accepted  = FALSE;				return FALSE;			}			// Image Type is returned from getimagesize() function	 		switch($image[2]) {	 			case 1:	 				$this->file["extention"] = ".gif"; break;	 			case 2:	 				$this->file["extention"] = ".jpg"; break;	 			case 3:	 				$this->file["extention"] = ".png"; break;	 			case 4:	 				$this->file["extention"] = ".swf"; break;	 			case 5:	 				$this->file["extention"] = ".psd"; break;	 			case 6:	 				$this->file["extention"] = ".bmp"; break;				case 7:	 				$this->file["extention"] = ".cdr"; break;	 			case 8:	 				$this->file["extention"] = ".tif"; break;	 			case 9:	 				$this->file["extention"] = ".tif"; break;	 			default:					$this->file["extention"] = $extention; break;	 		}		} elseif(!ereg("(\.)([a-z0-9]{3,5})$", $this->file["name"]) && !$extention) {			// Try and autmatically figure out the file type			// For more on mime-types: http://httpd.apache.org/docs/mod/mod_mime_magic.html			switch($this->file["type"]) {				case "text/plain":					$this->file["extention"] = ".txt"; break;				case "text/richtext":					$this->file["extention"] = ".txt"; break;				default:					break;			}	 	} else {			$this->file["extention"] = $extention;		}				// check to see if the file is of type specified		if($accept_type) {			if(ereg(strtolower($accept_type), strtolower($this->file["type"]))) {				$this->accepted = TRUE;			} else { 				$this->accepted = FALSE;				$this->errors[3] = "Somente arquivos com extensão " . ereg_replace("\|", " or ", $accept_type) . " podem ser enviados";			}		} else { 			$this->accepted = TRUE;		}		return $this->accepted;	}	# ----------------------------------- #	# FUNCTION: 	save_file 	# DESCRIPTION: 	Cleans up the filename, copies the file from PHP's temp location to $path, 	#				and checks the overwrite_mode	#	# ARGS:			$path			(string) File path to your upload directory	#				$overwrite_mode	(int) 	1 = overwrite existing file	#										2 = rename if filename already exists (file.txt becomes file_copy0.txt)	#										3 = do nothing if a file exists	# ----------------------------------- #	function save_file($path, $overwrite_mode="3"){		$this->path = $path;							if($this->accepted) {			// Clean up file name (only lowercase letters, numbers and underscores)			$this->file["name"] = ereg_replace("[^a-z0-9._]", "", str_replace(" ", "_", str_replace("%20", "_", strtolower($this->file["name"]))));						// Clean up text file breaks			if(ereg("text", $this->file["type"])) {				$this->cleanup_text_file($this->file["tmp_name"]);			}									// get the raw name of the file (without it's extenstion)			if(ereg("(\.)([a-z0-9]{2,5})$", $this->file["name"])) {				$pos = strrpos($this->file["name"], ".");				if(!$this->file["extention"]) { 					$this->file["extention"] = substr($this->file["name"], $pos, strlen($this->file["name"]));				}				$this->file['raw_name'] = substr($this->file["name"], 0, $pos);			} else {				$this->file['raw_name'] = $this->file["name"];				if ($this->file["extention"]) {					$this->file["name"] = $this->file["name"] . $this->file["extention"];				}			}						switch($overwrite_mode) {				case 1: // overwrite mode					$aok = copy($this->file["tmp_name"], $this->path . $this->file["name"]);					break;				case 2: // create new with incremental extention					while(file_exists($this->path . $this->file['raw_name'] . $copy . $this->file["extention"])) {						$copy = "_copy" . $n;						$n++;					}					$this->file["name"]  = $this->file['raw_name'] . $copy . $this->file["extention"];					$aok = copy($this->file["tmp_name"], $this->path . $this->file["name"]);					break;				case 3: // do nothing if exists, highest protection					if(file_exists($this->path . $this->file["name"])){						$this->errors[4] = "File &quot" . $this->path . $this->file["name"] . "&quot already exists";						$aok = null;					} else {						$aok = copy($this->file["tmp_name"], $this->path . $this->file["name"]);					}					break;				default:					break;			}						if(!$aok) { unset($this->file['tmp_name']); }			return $aok;		} else {			$this->errors[3] = "Somente arquivos com extensão " . ereg_replace("\|", " or ", $accept_type) . " podem ser enviados";			return FALSE;		}	}		# ----------------------------------- #	# FUNCTION: 	cleanup_text_file 	# DESCRIPTION: 	Convert Mac and/or PC line breaks to UNIX	#	# ARGS: 		$file	(string) Path and name of text file	# ----------------------------------- #	function cleanup_text_file($file){		// chr(13)  = CR (carridge return) = Macintosh		// chr(10)  = LF (line feed)	   = Unix		// Win line break = CRLF		$new_file  = '';		$old_file  = '';		$fcontents = file($file);		while (list ($line_num, $line) = each($fcontents)) {			$old_file .= $line;			$new_file .= str_replace(chr(13), chr(10), $line);		}		if ($old_file != $new_file) {			// Open the uploaded file, and re-write it with the new changes			$fp = fopen($file, "w");			fwrite($fp, $new_file);			fclose($fp);		}	}}/*<license>	///// fileupload.class /////	Copyright (c) 1999, 2002 David Fox, Angryrobot Productions	(http://www.angryrobot.com) All rights reserved.		Redistribution and use in source and binary forms, with or without 	modification, are permitted provided that the following conditions 	are met:	1. Redistributions of source code must retain the above copyright 	   notice, this list of conditions and the following disclaimer.	2. Redistributions in binary form must reproduce the above 	   copyright notice, this list of conditions and the following 	   disclaimer in the documentation and/or other materials provided 	   with the distribution.	3. Neither the name of author nor the names of its contributors 	   may be used to endorse or promote products derived from this 	   software without specific prior written permission.	DISCLAIMER:	THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS "AS IS" 	AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED 	TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A 	PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR 	CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 	SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 	LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF 	USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED 	AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 	LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING 	IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF 	THE POSSIBILITY OF SUCH DAMAGE.</license>*/?><?include ("config2.php");$nome_imagem = $path . file['raw_name'];$verso = $_POST[verso];$quantidade1 = $_POST[quantidade1];$verso2 = $_POST[verso2];$quantidade2 = $_POST[quantidade2];$verso3 = $_POST[verso3];$quantidade3 = $_POST[quantidade3];$sqlinsert = "INSERT INTO usuarios_padrao_envio (nome_imagem,verso,quantidade1,verso2,quantidade2,verso3,quantidade3) VALUES ('$path . file['raw_name']','$verso','$quantidade1','$verso2','$quantidade2','$verso3','$quantidade3')";mysql_query($sqlinsert) or die ("Não foi possível inserir. Problemas. Verifique novamente.");?><?$to = "imasters@imasters.com.br";$assunto = "Envio de arquivos";$msg = "Nome da imagem: $nome_imagem<br>Verso: $verso<br>Quantidade: $quantidade1<br><br><br>Verso: $verso2<br>Quantidade: $quantidade2<br><br><br>Verso: $verso3<br>Quantidade: $quantidade3";$header = "MIME-Version: 1.0\r\n";$header .= "Content-Type:text/html; charset=us-ascii";$from .= "From:$email\r\n";mail($to,$assunto,$msg,$from.$header);?><?echo "$nome_imagem";?>

Compartilhar este post


Link para o post
Compartilhar em outros sites

nossa! ja revirei esse codigo de ponta a cabeça e não sei o q fazer... nao encontro nada q ajude na internet...como eu vou incluir o nome e o caminho no banco de dados???

Compartilhar este post


Link para o post
Compartilhar em outros sites

leia um artigo a respeito de upload de imagens, você vai saber como que funciona a lógica por trás disso, um bom artigo tem aqui:

http://www.phpbrasil.com/articles/article.php/id/707

 

mas basicamente:

$_FILES["nomeInput"]["name"] é o nome que o seu arquivo físico tem.

aí vai de você montar o caminho numa variável:

$caminho = "upload/imagens_site".$_FILES["nomeInput"]["name"];

e por aí vai...

tente trazer um erro para a gente resolver, simplesmente dizer que não funciona é muito simples.

 

flws!

Compartilhar este post


Link para o post
Compartilhar em outros sites

×

Informação importante

Ao usar o fórum, você concorda com nossos Termos e condições.