2010-05-21 14 views

Respuesta

51

Suponiendo que está en el servidor:

readfile() - genera un archivo

Ejemplo de http://php.net/manual/en/function.readfile.php

+1

Funciona en firefox pero no en IE –

+0

Funciona para mí en IE8/Vista. ¿Obtiene un error o simplemente carga una página en blanco? – Adirael

+23

El ejemplo contiene mucha basura. Content-Description no existe en HTTP. Content-Type debe establecerse en el tipo de medio real, o ninguno en absoluto. El código para Content-Disposition generará encabezados incorrectos para muchos nombres de archivo. Content-Transfer-Encoding no existe en HTTP. Consulte también http://blogs.msdn.com/b/ieinternals/archive/2012/05/16/do-not-pollute-your-pages-with-mssmarttagspreventparsing-galleryimg-imagetoolbar-pre-check-post-check. aspx con respecto a Cache-Control. –

1

Ok, no soy experto en PHP, solo me puedo atribuir el mérito de haber recopilado algunos otros fragmentos de PHP para lograr lo que necesitaba, y pensé que sería mejor publicarlo esta solución en algunos foros que hicieron la misma pregunta pero no pude llegar a trabajar yo mismo. No parecía haber una solución en ningún lado, así que aquí está. Funciona para mí ... Ok, primero quise crear el formulario PDF y agregué un botón que luego envía el formulario. En las acciones de este formulario de envío, le dije a PDF el documento completo. Luego le di un enlace URL a una página php, como mail_my_form.php Luego creé un formulario php, y lo nombré igual que el anterior ... mail_my_form.php Una última cosa es crear una carpeta llamada pdfs en la raíz de donde irá este código php. (Entonces, si coloca el php en una carpeta llamada correo electrónico, dentro de la carpeta de correo electrónico, necesita otra carpeta llamada pdfs) Ahora lo que hace este script es: Guarda el PDF con el nombre de archivo pdfs. Luego adjunta el archivo a un correo electrónico y lo envía. Luego borra el archivo de la carpeta pdfs para ahorrar espacio. (Se podía sacar la función de borrado para guardar los formularios en su FTP también si se quería.
Aquí está.

<?php 
$fileatt = date("d-m-Y-His") . ".pdf"; // Creates unique PDF name from the date 
copy('php://input',"pdfs/".$fileatt); // Copies the pdf form data to a folder named pdfs 
$fileatt = "pdfs/".$fileatt; // Path to the file gives the pdfs folder plus the unique file name we just assigned 
$fileatt_type = "application/pdf"; // File Type 
$fileatt_name = "Application Form_".$fileatt.".pdf"; // Filename that will be used for the file as the attachment when it is sent 

$email_from = "mywebsite"; // Who the email is from 
$email_subject = "Completed online Applications"; // The Subject of the email 
$email_message = "Please find a recent online application attached. 
"; 
$email_message .= "Any problems please email me... 
"; // Message that the email has in it 

$email_to = "[email protected]"; // Who the email is to 

$headers = "From: ".$email_from; 

//no need to change anything else under this point 

$file = fopen($fileatt,'rb'); 
$data = fread($file,filesize($fileatt)); 
fclose($file); 

$semi_rand = md5(time()); 
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x"; 

$headers .= "\nMIME-Version: 1.0\n" . 
"Content-Type: multipart/mixed;\n" . 
" boundary=\"{$mime_boundary}\""; 

$email_message .= "This is a multi-part message in MIME format.\n\n" . 
"--{$mime_boundary}\n" . 
"Content-Type:text/html; charset=\"iso-8859-1\"\n" . 
"Content-Transfer-Encoding: 7bit\n\n" . 
$email_message .= "\n\n"; 

$data = chunk_split(base64_encode($data)); 

$email_message .= "--{$mime_boundary}\n" . 
"Content-Type: {$fileatt_type};\n" . 
" name=\"{$fileatt_name}\"\n" . 
//"Content-Disposition: attachment;\n" . 
//" filename=\"{$fileatt_name}\"\n" . 
"Content-Transfer-Encoding: base64\n\n" . 
$data .= "\n\n" . 
"--{$mime_boundary}--\n"; 

$ok = @mail($email_to, $email_subject, $email_message, $headers); 

if($ok) { 
unlink($fileatt); //NOW WE DELETE THE FILE FROM THE FOLDER pdfs 
Header("Location: nextpage.php"); //where do we go once the form has been submitted. 

} else { 
die("Sorry but the email could not be sent. Please go back and try again!"); 
} 
?> 

Espero que esto ayude a algunos de ustedes.

Richard Williams

24

Aquí es lo que necesita para enviar un archivo con PHP:

$filename = "whatever.jpg"; 

if(file_exists($filename)){ 

    //Get file type and set it as Content Type 
    $finfo = finfo_open(FILEINFO_MIME_TYPE); 
    header('Content-Type: ' . finfo_file($finfo, $filename)); 
    finfo_close($finfo); 

    //Use Content-Disposition: attachment to specify the filename 
    header('Content-Disposition: attachment; filename='.basename($filename)); 

    //No cache 
    header('Expires: 0'); 
    header('Cache-Control: must-revalidate'); 
    header('Pragma: public'); 

    //Define file size 
    header('Content-Length: ' . filesize($filename)); 

    ob_clean(); 
    flush(); 
    readfile($filename); 
    exit; 
} 

Como se comentó Julian Reschke, la respuesta validado podría funcionar, pero es está lleno de encabezados inútiles. El tipo de contenido debe establecerse en el tipo real del archivo, o algunos navegadores (especialmente los navegadores móviles) pueden no descargarlo correctamente.

+0

Lo busqué para siempre, gracias un millón. –

+0

Gracias, especialmente por 'ob_clean(); flush(); ' – GHosT

+1

¿podría agregar comentarios a los bits' ob_clean' y 'flush'? ¿Qué problemas potenciales resuelven? – YakovL

Cuestiones relacionadas