PHP - NONBRE DE ARCHIVOS GENERADOS

 
Vista:

NONBRE DE ARCHIVOS GENERADOS

Publicado por Chavez (9 intervenciones) el 30/06/2008 19:05:14
quiero con este codigo 2 cosas la primera y la mas importante es generar nombres de archivos para que si ingreso una imagen con el mismo nombre no me de ningun mensaje

numero dos meter la ruta en una base de datos, esa en mas facil solo hay que identificar la variable del nombre del archivo ya generado.

<?php
$idir = "images/"; // Path To Images Directory
$tdir = "images/thumbs/"; // Path To Thumbnails Directory
$twidth = "125"; // Maximum Width For Thumbnail Images
$theight = "100"; // Maximum Height For Thumbnail Images

if (!isset($_GET['subpage'])) { // Image Upload Form Below ?>
<form method="post" action="addphoto.php?subpage=upload" enctype="multipart/form-data">
File:<br />
<input type="file" name="imagefile" class="form">
<br /><br />
<input name="submit" type="submit" value="Sumbit" class="form"> <input type="reset" value="Clear" class="form">
</form>
<?php } else if (isset($_GET['subpage']) && $_GET['subpage'] == 'upload') { // Uploading/Resizing Script
$url = $_FILES['imagefile']['name'].22; // Set $url To Equal The Filename For Later Use

if ($_FILES['imagefile']['type'] == "image/jpg" || $_FILES['imagefile']['type'] == "image/jpeg" || $_FILES['imagefile']['type'] == "image/pjpeg") {
$file_ext = strrchr($_FILES['imagefile']['name'], '.'); // Get The File Extention In The Format Of , For Instance, .jpg, .gif or .php
$copy = copy($_FILES['imagefile']['tmp_name'], "$idir" . $_FILES['imagefile']['name']); // Move Image From Temporary Location To Permanent Location
if ($copy) { // If The Script Was Able To Copy The Image To It's Permanent Location
print 'Image uploaded successfully.<br />'; // Was Able To Successfully Upload Image
$simg = imagecreatefromjpeg("$idir" . $url); // Make A New Temporary Image To Create The Thumbanil From
$currwidth = imagesx($simg); // Current Image Width
$currheight = imagesy($simg); // Current Image Height
if ($currheight > $currwidth) { // If Height Is Greater Than Width
$zoom = $twidth / $currheight; // Length Ratio For Width
$newheight = $theight; // Height Is Equal To Max Height
$newwidth = $currwidth * $zoom; // Creates The New Width
} else { // Otherwise, Assume Width Is Greater Than Height (Will Produce Same Result If Width Is Equal To Height)
$zoom = $twidth / $currwidth; // Length Ratio For Height
$newwidth = $twidth; // Width Is Equal To Max Width
$newheight = $currheight * $zoom; // Creates The New Height
}
$dimg = imagecreate($newwidth, $newheight); // Make New Image For Thumbnail
imagetruecolortopalette($simg, false, 256); // Create New Color Pallete
$palsize = ImageColorsTotal($simg);
for ($i = 0; $i < $palsize; $i++) { // Counting Colors In The Image
$colors = ImageColorsForIndex($simg, $i); // Number Of Colors Used
ImageColorAllocate($dimg, $colors['red'], $colors['green'], $colors['blue']); // Tell The Server What Colors This Image Will Use
}
imagecopyresized($dimg, $simg, 0, 0, 0, 0, $newwidth, $newheight, $currwidth, $currheight); // Copy Resized Image To The New Image (So We Can Save It)
imagejpeg($dimg, "$tdir" . $url); // Saving The Image
imagedestroy($simg); // Destroying The Temporary Image
imagedestroy($dimg); // Destroying The Other Temporary Image
print 'Image thumbnail created successfully.'; // Resize successful
} else {
print '<font color="#FF0000">ERROR: Unable to upload image.</font>'; // Error Message If Upload Failed
}
} else {
print '<font color="#FF0000">ERROR: Wrong filetype (has to be a .jpg or .jpeg. Yours is '; // Error Message If Filetype Is Wrong
print $file_ext; // Show The Invalid File's Extention
print '.</font>';
}
} ?>
Valora esta pregunta
Me gusta: Está pregunta es útil y esta claraNo me gusta: Está pregunta no esta clara o no es útil
0
Responder

RE:NONBRE DE ARCHIVOS GENERADOS

Publicado por Diego Romero (1450 intervenciones) el 30/06/2008 19:51:37
Donde dice:

imagejpeg($dimg, "$tdir" . $url); // Saving The Image

Cámbialo por...

$c = 0;
while (is_file("$tdir" . $url . $c)) { $c++ ; }
imagejpeg($dimg, "$tdir" . $url . $c); // Saving The Image

Y ya está.
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar

RE:NONBRE DE ARCHIVOS GENERADOS

Publicado por Chavex (6 intervenciones) el 01/07/2008 16:41:21
Lo resolvi de una manera diferente USANDO TU CODIGO

$c = 0;
while (is_file("$tdir" . $c . $url)) { $c++ ; }
imagejpeg($dimg, "$tdir" . $c . $url); // Saving The Image

PORQUE EL NOMBRE DE LA IMAGES VA JUNTO CON LA EXTENSION ENTONCES SI LO COLOCO COMO SUFIJO imagen.jpg5 no me reconoceria el tipo de imagen pues lo colocaria despues de la extension.

OTRO PROBLEMITA

SOLO LO ESTA HACIENDO CON EL Thumb(miniatura) y la imagen grande no.

tambien me gustaria poder subir varia imagenes al mismo tiempo
y meter el nombre de la imagen en una DB, esto ultimo creo que lo podria hacer
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar

RE:NONBRE DE ARCHIVOS GENERADOS

Publicado por chavex (6 intervenciones) el 01/07/2008 18:56:30
Diego Ayudame en esta parte......................

me gustaria hacer que este codigo funcione.........lo que quiera es que le haga lo mismo con la imagen grande si puedes notar el escript cre dos imagenes una grande y otra pequeña solo que el codigo que me diste me funciona pero solo con una de las imagenes.
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar

RE:NONBRE DE ARCHIVOS GENERADOS

Publicado por Diego Romero (1450 intervenciones) el 01/07/2008 21:37:24
Lo que yo entiendo del código es que el usuario sube una imagen JPG y el script se encarga de crear una miniatura de ese JPG, no necesitas guardar el original porque éste ya está guardado. Concretamente en el directorio señalado por $idir

Estudia mejor el código.
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar

RE:NONBRE DE ARCHIVOS GENERADOS

Publicado por chavex (6 intervenciones) el 01/07/2008 23:21:49
Pero si lo hace y es bueno porque tengo dos imagenes una miniatura y otra proporcional al tamaño que kiera, prueba el codigo y veras

bueno tambien tenia otra idea de asignarle a la imagen la fecha hora minutos y segundos como nombre eso haria el nombre inrepetible.

pero en esta parte que te estoy pidiendo ayuda la verdad que no tengo idea como hacerlo kiero hacer ke subas mas de una imagen a la vez.

mira este codigo que uso actualmente en una aplicacion

/////////////////////////////////////////////////////////////

<?php
include('../../conect.php');
include('verifier.php');
$idactividad = $_GET['idactividad'];
if(isset($idactividad)){
$idactividad = $idactividad;
} else {
$idactividad = $_POST['idactividad'];
}

$config['max_file_size'] = '500000';
$config['num_temp_files'] = '10';


include('imgresize_files/photo_upload.php');
include('imgresize_files/functions.php');

if ($_POST['action'] == 'resize') {
include('imgresize_files/count.php');

if ($_POST['max_pixels'] == '' || !checkValidChars($_POST['max_pixels'],'0123456789')) {
$result_div .= getResultDiv('Please enter a numeric value for the maximum dimention');
}
if ($count > $config['num_temp_files']) {
$new_count = 1;
} else {
$new_count = $count+1;
}
$file = fopen('imgresize_files/count.php','w+');
$contents = '<?php $count= ' . $new_count . '; ?>';
fwrite($file,$contents);
fclose($file);
$file_array = explode('.',$_FILES['image_file']['name']);
$array_count = count($file_array);
if ($file_array[$array_count-1] != 'jpg' && $file_array[$array_count-1] != 'jpeg') {
$result_div .= getResultDiv('Sorry, this script only works for JPEG files');
}
if ($_FILES['image_file']['tmp_name'] == '') {
$result_div .= getResultDiv('Please select a file to upload');
} elseif ($_FILES['image_file']['size'] > $config['max_file_size']) {
$result_div .= getResultDiv('That file is too large. Please try a smaller file');
} else {


$fec = date("d-m-Y-H-i-s");

$photo = new PhotoUpload($_FILES['image_file']);
//copy($_FILES['image_file']['tmp_name'],'imgresize_files/images/temp' . $count . '.jpg');
$photo->uploadImage('imgresize_files/images/');
$photo->resizeImage($_POST['max_pixels'],'temp_' . $fec ,'3','');
$large_name = $photo->new_image_name;
$photo->removeOriginal();

$img = '<hr /><img src="imgresize_files/images/temp_' . $fec . '.jpg" />';
}
$form = $_GET;
}
$nombre = "temp_" . $fec .".jpg";

if (isset($count)) {
$comando_sql = "INSERT INTO images (idactividad, nombre) VALUES ('$idactividad', '$nombre')";

mysql_query($comando_sql) or die("ERROR, No es posible guardar la información en la Base de Datos.");
}


?>
<HEAD>
<script language="JavaScript">
<!--
function refreshParent() {
window.opener.location.href = window.opener.location.href;

if (window.opener.progressWindow)

{
window.opener.progressWindow.close()
}
window.close();
}
//-->
</script>

<?php $fecha = date(d."-".m."-".Y); ?><style type="text/css">
<!--
body {
margin-left: 7px;
margin-top: 0px;
margin-right: 0px;
margin-bottom: 0px;
}
.style1 {font-family: Verdana, Arial, Helvetica, sans-serif}
-->
</style>
<HEAD>
<BODY BGCOLOR=#FFFFFF onunload="window.opener.location.reload()">
<form action="<?php echo $_SERVER['PHP_SELF'];?>?subpage=upload" method="POST" enctype="multipart/form-data" id="">


<img src="images/subir_imagen.gif" alt="" width="402" height="67" />



<table width="403" border="0" cellpadding="0" cellspacing="0">
<!--DWLayoutTable-->
<tr>
<td height="22" colspan="2" valign="top"><strong><br />
</strong><span class="style1">
<?php


$datos = "SELECT * FROM actividades WHERE id =".$idactividad;

$resultados = mysql_query($datos);
while($fila = mysql_fetch_array($resultados)){
echo $fila['titulo'];
};

?>
</span></td>
</tr>
<tr>
<td width="55" height="18"></td>
<td width="348"></td>
</tr>
<tr>
<td height="24"></td>
<td valign="bottom"><input type="file" class="LV_valid" name="image_file" value="<?php echo $form['image_file']; ?>" size="30" />
<input name="max_pixels" type="hidden" id="max_pixels" value="<?php echo $form['copy_text']; ?>500" />
<input type="hidden" name="MAX_FILE_SIZE" value="<?php echo $config['max_file_size']; ?>" />
<input type="hidden" name="action" value="resize" />
 
<input name="idactividad2" type="hidden" id="idactividad2" value="<?php echo $idactividad ?>" /></td>
</tr>
<tr>
<td height="39"></td>
<td valign="middle"><input type="submit" value="Cargar Imagen >>" />
<input name="idactividad" type="hidden" id="idactividad" value="<?php echo $idactividad ?>" /></td>
</tr>
<tr>
<td height="19" colspan="2" valign="top" bgcolor="#333333"><label></label></td>
</tr>
<tr>
<td height="95" colspan="2" valign="top"><table width="100%" border="0" cellpadding="10" cellspacing="0">
<!--DWLayoutTable-->
<tr>
<td width="383" height="115" align="left" valign="top" bordercolor="10" bgcolor="#333333" class="galeria">
<label>

<?php $datos2 = "SELECT * FROM images WHERE idactividad =".$idactividad." ORDER BY idactividad DESC";

$resultados2 = mysql_query($datos2);
while($fila2 = mysql_fetch_array($resultados2)){
?>

<img src="http://mixonanetwork.com/~micolegi/admin/imgresize_files/images/<?php echo $fila2['nombre'] ?>" alt="" height="86" style="border: 3px white solid;" />
<?php }; ?>
</label></td>
</tr>
</table>
</td>
</tr>
</table>

</form>
</body>
</html>
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar