Foros del Web » Programando para Internet » PHP »

php imap no guarda los archivos 0 Kb

Estas en el tema de php imap no guarda los archivos 0 Kb en el foro de PHP en Foros del Web. Hola, estoy haciendo un script que recoja los mail y me guarde los archivos adjuntos. El problema que tengo es me guarda los archivos con ...
 
Antiguo 25/09/2016, 13:36
 
Fecha de Ingreso: febrero-2008
Mensajes: 115
Antigüedad: 18 años, 7 meses
Puntos: 4
Pregunta php imap no guarda los archivos 0 Kb

Hola, estoy haciendo un script que recoja los mail y me guarde los archivos adjuntos. El problema que tengo es me guarda los archivos con su nombre y tal, pero con 0 KB

¿Alguna sujerencia?

Mil Gracias

Funcionamiento del proceso:
- Se conecta por IMAP a la carpeta inbox
- Los mensajes marcados como nuevos los lee y si se cumplen unas condiciones lo ingresa en el SQL
-Guarda los archivos adjuntos en el directorio que toque pero aqui es donde esta el problema, no guarda el contenido pero si genera el archivo 0 KB
-Marca el mensaje procesado como leido.

Código PHP:
<?php
include("core/cfpc.php");

 
$ConsultaMySql = $mysqli->query("SELECT * from ".$prefixsql."config");
while(
$cfpc = mysqli_fetch_array($ConsultaMySql))
{
    if (
$cfpc["opcion"] == 'servidor'){$servidor = $cfpc["valor"];}
    if (
$cfpc["opcion"] == 'user'){$username = $cfpc["valor"];}
    if (
$cfpc["opcion"] == 'password'){$password = $cfpc["valor"];}
    if (
$cfpc["opcion"] == 'parmconex'){$parmconex = $cfpc["valor"];}
    if (
$cfpc["opcion"] == 'imapPath'){$imapPath = $cfpc["valor"];}
    

    
}
 
$hostname = $servidor.$parmconex;


?>


<h2>Procesamiento de correo</h2>

<?php
set_time_limit
(4000);
$rutabase = "modules/historico/files/";
 

$imapPath = '{mail.SERVIDORIMAP.es:143/imap/tls/novalidate-cert}INBOX';;
//$username = '[email protected]';
//$password = 'your_gmail_password';
 
// try to connect
$inbox = imap_open($imapPath,$username,$password) or die('Cannot connect to Gmail: ' . imap_last_error());
 
 
$emails = imap_search($inbox,'ALL');
 
$output = '';
?>
<table border="1">
<tr>
<td>ID</td>
<td>Leido</td>
<td>Asunto</td>
<td>From</td>
<td>Fecha</td>
<td>Mensaje</td>
<td>Chofer</td>
<td>Remolque</td>
<td>ID_SQL</td>



</tr>

<?php
 
foreach($emails as $mail) {
    
    
$headerInfo = imap_headerinfo($inbox,$mail);
    
    if (
$headerInfo->Unseen == 'U'){$mensajeleido = 'NO';}else{$mensajeleido = 'SI';}
    
    if (
$mensajeleido == 'NO')
    {
    
    echo 
'<tr>';
    echo 
'<td>'.$headerInfo->Msgno.'</td>';
     
    echo 
'<td>'.$mensajeleido.'</td>';
    
$asuntomsg = $headerInfo->subject;
    echo 
'<td>'.$asuntomsg.'</td>';
    
    echo 
'<td>';
    
    
    
$from = $headerInfo->from;
    foreach (
$from as $id => $object) {
        
        
$fromaddress = $object->mailbox . "@" . $object->host;
    }
    echo 
$fromaddress;
    
    echo 
'</td>';
    
    
    
$date = date_create($headerInfo->date);
    
$fechaemail = date_format($date, 'Y-m-d H:i:s');
    
    echo 
'<td>'.$fechaemail.'</td>';
    
    
    
//$textomensaje = imap_qprint(imap_body($inbox, $mail)); 
    
$textomensaje = imap_fetchbody($inbox,$mail,1);
    
    echo 
'<td></td>';
    
    
    
// Buscamos en la cadena si aparece alguna variable como chofer
    // ------------------- INICIO buscar chofer ------------------------
    
    
$asunto = $headerInfo->subject;
    
$idchofer = '';
    
$schofer = '';
    
    
$ConsultaMySql= $mysqli->query("SELECT * from ".$prefixsql."chofer");
    while(
$columna = mysqli_fetch_array($ConsultaMySql))
    {
        
$cadenabuscar = $columna["display"];
        
$resultado = strpos($asunto, $cadenabuscar);
         
        if(
$resultado !== FALSE){ $idchofer = $columna["id"]; $schofer = $columna["display"];}
    }
    
    
$idremolque = '';
    
$sremolque = '';
    
    
$ConsultaMySql= $mysqli->query("SELECT * from ".$prefixsql."remolques");
    while(
$columna = mysqli_fetch_array($ConsultaMySql))
    {
        
$cadenabuscar = $columna["remolque"];
        
$resultado = strpos($asunto, $cadenabuscar);
         
        if(
$resultado !== FALSE){ $idremolque = $columna["id"]; $sremolque = $columna["remolque"];}
    }
    

    
    
// ------------------- FIN buscar chofer ------------------------
    
    
echo '<td>'.$idchofer.' - '.$schofer.'</td>';
    echo 
'<td>'.$idremolque.' - '.$sremolque.'</td>';
    
    if (
$idchofer > '0' && $idremolque > '0')
    {
    
$sqlmail = $mysqli->query("insert into ".$prefixsql."mails (fecha, asunto, mensaje, idchofer, idremolque) VALUES ('".$fechaemail."', '".$asuntomsg."', '', '".$idchofer."', '".$idremolque."')");

    
$sqlmail = $mysqli->query("SELECT max( id ) AS codigo FROM ".$prefixsql."mails");
    
$rowuid = mysqli_fetch_assoc($sqlmail);
    
$ultimoid = $rowuid["codigo"];
    echo 
'<td>'.$ultimoid.'</td>';
    
$rutafotos = $rutabase.$ultimoid;
    
    
mkdir($rutafotos, 0777);
    
    
    echo 
'</tr>';
    
// ------------------ INICIO ADJUNTOS -----------------
    
    /* get mail structure */
        
$structure = imap_fetchstructure($inbox, $mail);
 
        
$attachments = array();
 
        
/* if any attachments found... */
        
if(isset($structure->parts) && count($structure->parts)) 
        {
            for(
$i = 0; $i < count($structure->parts); $i++) 
            {
                
$attachments[$i] = array(
                    
'is_attachment' => false,
                    
'filename' => '',
                    
'name' => '',
                    
'attachment' => ''
                
);
 
                if(
$structure->parts[$i]->ifdparameters) 
                {
                    foreach(
$structure->parts[$i]->dparameters as $object) 
                    {
                        if(
strtolower($object->attribute) == 'filename') 
                        {
                            
$attachments[$i]['is_attachment'] = true;
                            
$attachments[$i]['filename'] = $object->value;
                        }
                    }
                }
 
                if(
$structure->parts[$i]->ifparameters) 
                {
                    foreach(
$structure->parts[$i]->parameters as $object) 
                    {
                        if(
strtolower($object->attribute) == 'name') 
                        {
                            
$attachments[$i]['is_attachment'] = true;
                            
$attachments[$i]['name'] = $object->value;
                        }
                    }
                }
 
                if(
$attachments[$i]['is_attachment']) 
                {
                    
$attachments[$i]['attachment'] = imap_fetchbody($inbox, $email_number, $i+1);
 
                    
/* 4 = QUOTED-PRINTABLE encoding */
                    
if($structure->parts[$i]->encoding == 3) 
                    { 
                        
$attachments[$i]['attachment'] = base64_decode($attachments[$i]['attachment']);
                    }
                    
/* 3 = BASE64 encoding */
                    
elseif($structure->parts[$i]->encoding == 4) 
                    { 
                        
$attachments[$i]['attachment'] = quoted_printable_decode($attachments[$i]['attachment']);
                    }
                }
            }
        }
 
        
/* iterate through each attachment and save it */
        
foreach($attachments as $attachment)
        {
            if(
$attachment['is_attachment'] == 1)
            {
                
$filename = $attachment['name'];
                if(empty(
$filename)) $filename = $attachment['filename'];
 
                if(empty(
$filename)) $filename = time() . ".dat";
 
                
/* prefix the email number to the filename in case two emails
                 * have the attachment with the same file name.
                 * AQUI ESCRIBE O GUARDA EL ARCHIVO EN EL DIRECTORIO
                 */
                
$rutaadjunto = $rutafotos.'/'.$filename;
                
$fp = fopen($rutaadjunto, "w+");
                
fwrite($fp, $attachment['attachment']);
                
fclose($fp);
            }
 
        }
    
    
    
// ---------------FIN ADJUNTOS------------------
        
        
        
        
$emailStructure = imap_fetchstructure($inbox,$mail);
        
        if(!isset(
$emailStructure->parts)) {
             
$output .= imap_body($inbox, $mail, FT_PEEK);
        } else {
            
//    
        
}
    }else
    {
        
//Marcamos mensaje como NO leido, puesto que no contiene ni Id chofer ni ID remolque
        
imap_clearflag_full($inbox, trim($headerInfo->Msgno), "\\Seen");
    }
    }
}
echo 
'</table>';

// colse the connection
imap_expunge($inbox);
imap_close($inbox);

?>

Etiquetas: adjuntos, imap
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Respuesta



La zona horaria es GMT -6. Ahora son las 00:14.