Having Uploadify e-mail a link to download the file - php

Uploadify is a jQuery plugin that allows the easy integration of a multiple (or single) file uploads on your website. It requires Flash and any backend development language. An array of options allow for full customization for advanced users, but basic implementation is so easy that even coding novices can do it.
I wanted to ask if It is possible to sends out a link of a file that has just been uploaded wioth the e-mail notification of Uploadify.
Here is the code for uploadify.php :
<?php
if (!empty($_FILES)) {
$tempFile = $_FILES['Filedata']['tmp_name'];
$targetPath = $_SERVER['DOCUMENT_ROOT'] . $_REQUEST['folder'] . '/';
$targetFile = str_replace('//','/',$targetPath) . $_FILES['Filedata']['name'];
// $fileTypes = str_replace('*.','',$_REQUEST['fileext']);
// $fileTypes = str_replace(';','|',$fileTypes);
// $typesArray = split('\|',$fileTypes);
// $fileParts = pathinfo($_FILES['Filedata']['name']);
// if (in_array($fileParts['extension'],$typesArray)) {
// Uncomment the following line if you want to make the directory if it doesn't exist
// mkdir(str_replace('//','/',$targetPath), 0755, true);
move_uploaded_file($tempFile,$targetFile);
echo "1";
// } else {
// echo 'Invalid file type.';
// }
}
//define the receiver of the email
$to = 'admin#admin.com';
//define the subject of the email
$subject = 'Test email';
//define the message to be sent. Each line should be separated with \n
$message = "Hello World!\n\nThis is my first mail.";
//define the headers we want passed. Note that they are separated with \r\n
$headers = "From: webmaster#example.com\r\nReply-To: webmaster#example.com";
//send the email
$mail_sent = #mail( $to, $subject, $message, $headers );
//if the message is sent successfully print "Mail sent". Otherwise print "Mail failed"
echo $mail_sent ? "Mail sent" : "Mail failed";
?>

Your script is vulnerable to filename collisions. You're the uploaded using the original name provided by the user. If the same filename is used more than once, you'll overwrite previous versions with the new one.
As well, you're blindly using a form value to specify a location to store the upload. What happens if someone specifies "../../../../../../../../../etc" for the folder and "passwd" for the filename? Or on a Windows server "../../../../../../../../windows/system32" and "ntoskrnl.exe"? If the webserver's misconfigured as to what user ID it's running on, you've just opened the machine to a complete remote compromise. But even if they don't want to compromise the system, they'll be able to trash any file within your site's document root with ease.
Having said that, if you want to embed a link to directly download the file, you'll have to build an HTML-formatted email, or hope the mail client can auto-linkify text that looks like URLs. Building HTML mails for use with the mail() function is a serious pain. I use PHPMailer for my projects. It works nicely and allows you to build any kind of email you'd like.

Something like:
<?PHP
$fileURL = 'http://' . $_SERVER['HTTP_HOST'] . $_REQUEST['folder'] . '/' . $_FILES['Filedata']['name'];
// ...
$message = "You can download the file from: {$fileURL}";
// ...
$mail_sent = #mail( $to, $subject, $message, $headers );
//...

Related

Email not send with attatchment in ci

When I use CI to send email with attachment there is no error but send with no attachment and contents.If it send without attachment email send with contents.
$this->load->library('email');
$this->email->to('$tomail');
$this->email->cc('$cmail');
$this->email->from('noreply#******8');
$this->email->subject('Gift Voucher');
$this->email->set_mailtype('html');
$data['content'] = 'Please find the attachment.<br> Reach us on : *****';
$data['footer'] = '© ' . date("Y") . '********/ All rights reserved';
$msg = $this->load->view('includes/mail_template', $data, TRUE);
$path = base_url('assets/uploads/giftpurchase/giftvoucher_'.$payid);
$this->email->attach($path);
$this->email->message($msg);
$this->email->send();
base_url() is provide you HTTP path, you should use there Directory path for mail attachment
Change
$path = base_url('assets/uploads/giftpurchase/giftvoucher_'.$payid);
// http://www.sitename.com/assets/uploads/giftpurchase/giftvoucher_.....
to
$path = {HERE_ROOT_PATH} 'assets/uploads/giftpurchase/giftvoucher_'.$payid;
// /var/www/html/assets/uploads/giftpurchase/giftvoucher_.....
PS : getcwd() function is provide current working directory, you can use to get working dir path
$path = getcwd(). 'assets/uploads/giftpurchase/giftvoucher_'.$payid;
If You want to attach file from Your server You need to use path to file from Your filesystem, not from Your web-root
There're 2 useful constants in CodeIgniter:
FCPATH -> path to front controller (index.php at top level (above /system/))
APPPATH -> path to /application/ folder
$path = FCPATH.'assets/uploads/giftpurchase/giftvoucher_'.$payid;

Replace uploaded document on confirm not working

My Requirement is as follows:
When user uploads a file i should check for "File already Exists", if file exists i must show confirm box if 'OK' i have to replace and if cancel the reverse.
This is my following code
if (file_exists($path . $documentName)) {
$msg = $documentName . " already exists. ";
?>
<script type="text/javascript">
var res = confirm('File already exists Do you want to replace?');
if (res == false) {
<?php
$msg = 'File Upload cancelled';
?>
} else {
<?php
if (move_uploaded_file($_FILES["document"]["tmp_name"], $path . $documentName)) {
$msg = $documentName . " File Replaced Successfully";
$successURL = $document_path . $documentName;
}
else
$msg = $documentName . "Upload Failed";
?>
}
</script>";
<?
}
My problem is even if i give cancel the file is getting replaced.
just let me know where I'm wrong or Is there any other approach?
Please help me to close this issue
Note:jquery Not allowed.
Your problem is that you mix javascript and PHP. The PHP-Code will be run on the server and generates the HTML-document. At this point, the file gets replaced already.
Then, this document (with the javascript-code inside) will then be send to the user and there the javascript-code is run. And in that moment, the user gets to see the confirmaion-dialog, even though the file already was replaced!
Take a look at the source-code that your php-code is generating and you will see what I mean.
A solution would be to add a checkbox to confirm overwriting files. Then after hitting the upload-/submit-button, your php-script would check if this box was checked and either replace the file or not.
#Gogul, honestly, this is not the right way to go. Better that you handle the file submission with an AJAX request which receives a response back from your server (either uploaded successfully, or file exists) which you handle appropriately. If presenting the user an option to replace the file, again handle that action with AJAX.
You can do AJAX request in raw JavaScript (jQuery not required) - see here: http://www.w3schools.com/ajax/ajax_xmlhttprequest_send.asp
You are mixing server side code with client side javascript. The solving of your problem is more complicated if you don't want the user to reupload the document:
Store the file in a temporary location under random filename. Output a yes/no form to the user, including the random filename and original filename.
If the user answers yes, move from temporary location to $path, else remove the file from temporary location.
Guys i came with with this following solution
upload
uploaddocument.php
$documentName = preg_replace('/[^a-zA-Z0-9.]/s', '_', $_FILES["document"]["name"]);
if (file_exists($path . $documentName)) {
move_uploaded_file($_FILES["document"]["tmp_name"], "F:\\Content\\enews_files\\temp\\" . $documentName);
$msg = $documentName . " already exists. <a href='confirm.php?confirm=1&filename=" . $documentName . "&language=" . $lang . "'>Replace</a>||<a href='confirm.php?confirm=0&filename=" . $documentName . "'>Cancel</a>";
} else {
if (move_uploaded_file($_FILES["document"]["tmp_name"], $path . $documentName)) {
$msg = $documentName . " Upload Success";
$successURL = $document_path . $lang . '/' . $documentName;
}
else
$msg = $documentName . " Upload Failed";
}
confirm.php
include("config_enews.php");
$lang = $_GET['language'];
$path = "F:\\Content\\enews_files\\" . $lang . "\\";
//$path = "D:\\test\\test\\" . $lang . "\\";
$documentName = preg_replace('/[^a-zA-Z0-9.]/s', '_', $_GET["filename"]);
if ($_GET['confirm'] == 1) {
//echo sys_get_temp_dir();die;
if (copy("F:\\Content\\enews_files\\temp\\" . $_GET["filename"], $path . $documentName)) {
unlink("F:\\Content\\enews_files\\temp\\" . $_GET["filename"]);
header("Location: uploaddocument.php?message=success&fname=$documentName&lang=$lang");
} else {
echo $res = move_uploaded_file($_GET["tempname"], $path . $documentName);
echo $msg = $documentName . " Upload Failed";
header("Location: uploaddocument.php?message=failed&fname=$documentName");
}
} else {
unlink("F:\\Content\\enews_files\\temp\\" . $_GET["filename"]);
header("Location: uploaddocument.php?message=cancelled&fname=$documentName");
}
I got this spark from #Marek. If any one has better solution kindly provide.
I don't have enough reputations to vote your answers sorry.
Thank you so much for all your support.

HTML/php Parser error

I was running through the tutorial on http://net.tutsplus.com/tutorials/php/online-file-storage-with-php/comment-page-2/#comments
and it was working fine until:
if(strlen($message) > 0)
{
$message = '<p class="error">' . $message . '</p>';
}
This line of php is found in index.php. When I few the page in firefox, it looks like the php parser stops at the greater than. Can I escape the character? Do I need to?
EDIT: All the php code:
<?php
//Load the settings
require_once("settings.php");
$message = "";
//Has the user uploaded something?
if(isset($_FILES['file']))
{
$target_path = Settings::$uploadFolder;
$target_path = $target_path . time() . '_' . basename( $_FILES['file']['name']);
//Check the password to verify legal upload
if($_POST['password'] != Settings::$password)
{
$message = "Invalid Password!";
}
else
{
//Try to move the uploaded file into the designated folder
if(move_uploaded_file($_FILES['file']['tmp_name'], $target_path)) {
$message = "The file ". basename( $_FILES['file']['name']).
" has been uploaded";
} else{
$message = "There was an error uploading the file, please try again!";
}
}
//Clear the array
unset($_FILES['file']);
}
if(strlen($message) > 0)
{
$message = '<p class="error">' . $message . '</p>';
}
?>
<html> ... </html> //my html code
The > won't cause the PHP parser to stop.
Without seeing the HTML output by the server, it is hard to say for sure, but since the > is the first > in the file it seems likely that the PHP parser never starts and the browser treats everything between the <?php at the start of the file and the strlen($message) > as a tag.
You need to access the PHP through a web server with PHP installed and configured to process that file (which is typically done by giving it a .php file extension).
What about this?
if(!empty($message)){
$message = '<p class="error">'.$message.'</p>';
}
But why don't you directly assign the paragraph tags to the error message instead of first assigning the error message to $message and then the paragraph tags?
there is not any error in the if condition its working fine
the possible problem in the
if(isset($_FILES['file']))
if($_POST['password'] != Settings::$password)
if(move_uploaded_file($_FILES['file']['tmp_name'], $target_path))
if you are not getting in the if body it mean the problem in
if(isset($_FILES['file']))
because if it fase than $message = "";
Always use Yoda Conditions and write such statements in (the) reverse(d) order (you're normally used to:
if ( 0 !== strlen( $message ) )
{
$message = 'Hello World!';
}
Anyway, you could also simply check for ! empty( $message )

Why do I keep getting "directory does not exist?"

I cannot figure out what I am doing wrong here. The permissions for the directory I have for the file being created have write permissions all across the board. I keep getting "directory does not exist" Thanks for the help!
<?
//creates variables and calls the information from the server
$Name = $_POST['name'];
$desc = $_POST['desc'];
$website =$_POST['web'];
$email =$_POST['email'];
$cname =$_POST['cname'];
echo "your registered name is: ". $Name . ".<br/>";
echo "your registered description is: " . $desc . ".<br/>";
echo "your website address is: " . $website . ".<br/>";
echo "your Confirmation email has been sent to: " . $email . ".<br/>";
echo "your information has been stored, thank you! ";
$cname = trim($cname);
$filename = "data/clubinfo/$cname.txt";
$fp = fopen($filename,'a');
fwrite($fp,$Name);
fwrite($fp,"\n");
fwrite($fp,$email);
fwrite($fp,"\n");
fwrite($fp,$desc);
fwrite($fp,"\n");
fwrite($fp, $website);
fwrite($fp, "\n");
fwrite($fp,"__");
fwrite($fp, "\n");
fclose($fp);
?>
Most likely the script is assuming a different working directory to what you're presuming since you're using a relative path.
You'd be better off specifying the path absolutely or at least in relation to $_SERVER['DOCUMENT_ROOT'] even if you do:
$filename = $_SERVER['DOCUMENT_ROOT'] . "../data/clubinfo/$cname.txt";
The advantage of that is that it's outside your document root so it won't be served directly by your Web server. It will also work no matter the location of your script and will work no matter under what directory you install your Webapp, which can be an issue with dev vs prod deployments.
The data/clubinfo folder does not exist in the current directory.
You need to create it first. (By hand or in PHP)
Alternatively, the current directory might not be what you think it is.
Try using file_put_contents() like this:
file_put_contents("data/clubinfo/$cname.txt", implode("\n", $_POST));
If you want to this value by value you should also use the FILE_APPEND flag.
looks like you have not given the path off the root and the server is looking from the current location. try giving the path off the root.

How to get email and their attachments from PHP

I'm writing a photo gallery webapp for a friend's wedding and they want a photo gallery for guests to submit the digital photos they take on the day.
After evaluating all the options, I've decided the easiest thing for users would be to let them use a familiar interface (their email) and just have them send in the pictures as attachments.
I've created an mailbox but now I need to connect and retrieve these attachments for automated processing for adding to the gallery system. But how? Are there any tutorials or prefab classes you've seen for doing this?
I used to do a lot of this before, but I can't find the code, here's a scaled down version I found. It should put you on the correct path. I used to run this type of script from a cronjob. Sorry I can't find the final version. ;(
// Open pop mailbox
if (!$mbox = imap_open ("{localhost:110/pop3/notls}INBOX", "user", "tester")) {
die ('Cannot connect/check pop mail! Exiting');
}
if ($hdr = imap_check($mbox)) {
$msgCount = $hdr->Nmsgs;
} else {
echo "Failed to get mail";
exit;
}
$MN=$msgCount;
$overview=imap_fetch_overview($mbox,"1:$MN",0);
for ($X = 1; $X <= $MN; $X++) {
$file = imap_fetchbody($mbox, $X, 1);
imap_delete($mbox, $X);
}
imap_expunge($mbox);
imap_close($mbox);
Good luck!
Have you considered using Google's Picasa Web Albums?
You can set up an email address to send photos to and share them online.
You can then get an RSS feed of these photos, which most programmers are
more familiar with than MTAs.
If you're creating a dedicated mailbox for this purpose, using a filtering mechanism is almost definitely not what you want. Instead, you want to have the mailbox be a pipe to the application, and have the application simply read in the message from stdin, parse out the body, and MIME parse the body to get the attachments.
Having a mailbox be a pipe is supported by all the popular unix-based MTAs that I know of, such as sendmail, postfix, and qmail. Generally you define it in your aliases file, like so:
# sendmail or postfix syntax
msgsubmit: "| /usr/bin/php ~path/to/example.php"
Then mails to msgsubmit# get routed to a php program for delivery.
This has the advantage of not relying on an IMAP server or any other server beyond the MTA being alive, and it works fine as long as you have control over the MTA of the destination host. Filtering is what you'd want if you wanted all messages on a system to be inspected by the script, which I'm guessing is not the case.
If you want a copy kept in a mailbox somewhere (not a bad idea) simply define the alias to go to multiple addresses, like so:
msgsubmit: "| /usr/bin/php ~path/to/example.php", msgsubmit-box
Or postfix virtual format:
msgsubmit
"| /usr/bin/php ~path/to/example.php"
msgsubmit-box
What MTA are you using? If you use postfix + maildrop you can create a filtering rule that pipes certain messages through a PHP script that then handles the incoming mails. (google for maildrop and xfilter).
I think you want a MIME message parser.
I've used this one before and it seems to work fine, although I haven't tested it on really big attachments (i.e. 2-3MB files you might get from digital cameras).
Have you already got a system for reading POP3 / IMAP mailboxes? There is another class on the same site which also works on POP3 (I believe there is also an IMAP one) - however if you will be downloading a fair volume maybe you'll want to investigate a few C-based solutions as I believe that one is pure PHP.
Majordomo, could be an alternative to handle emails, but there are some limitations on file attachment handling.
<?php
//make sure that submit button name is 'Submit'
if(isset($_POST['Submit'])){
$name = $_POST['visitorname'];
$email = $_POST['visitoremail'];
$message = $_POST['visitormessage'];
$to="youremail#yourdomain.com";
$subject="From ".$name;
$from = $email;
// generate a random string to be used as the boundary marker
$mime_boundary="==Multipart_Boundary_x".md5(mt_rand())."x";
// now we'll build the message headers
$headers = "From: $from\r\n" .
"MIME-Version: 1.0\r\n" .
"Content-Type: multipart/mixed;\r\n" .
" boundary=\"{$mime_boundary}\"";
// next, we'll build the invisible portion of the message body
// note that we insert two dashes in front of the MIME boundary
// when we use it
$message = "This is a multi-part message in MIME format.\n\n" .
"--{$mime_boundary}\n" .
"Content-Type: text/plain; charset=\"iso-8859-1\"\n" .
"Content-Transfer-Encoding: 7bit\n\n" .
$message . "\n\n";
foreach($_FILES as $userfile)
{
// store the file information to variables for easier access
$tmp_name = $userfile['tmp_name'];
$type = $userfile['type'];
$name = $userfile['name'];
$size = $userfile['size'];
// if the upload succeded, the file will exist
if (file_exists($tmp_name))
{
// check to make sure that it is an uploaded file and not a system file
if(is_uploaded_file($tmp_name))
{
// open the file for a binary read
$file = fopen($tmp_name,'rb');
// read the file content into a variable
$data = fread($file,filesize($tmp_name));
// close the file
fclose($file);
// now we encode it and split it into acceptable length lines
$data = chunk_split(base64_encode($data));
}
// now we'll insert a boundary to indicate we're starting the attachment
// we have to specify the content type, file name, and disposition as
// an attachment, then add the file content.
// NOTE: we don't set another boundary to indicate that the end of the
// file has been reached here. we only want one boundary between each file
// we'll add the final one after the loop finishes.
$message .= "--{$mime_boundary}\n" .
"Content-Type: {$type};\n" .
" name=\"{$name}\"\n" .
"Content-Disposition: attachment;\n" .
" filename=\"{$fileatt_name}\"\n" .
"Content-Transfer-Encoding: base64\n\n" .
$data . "\n\n";
}
}
$ok = #mail($to, $subject, $message , $headers);
if ($ok) {
if (($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/pjpeg")
&& ($_FILES["file"]["size"] < 20000))
{
if ($_FILES["file"]["error"] > 0)
{
echo "Return Code: " . $_FILES["file"]["error"] . "<br />";
}
else
{
if (file_exists("upload/" . $_FILES["file"]["name"]))
{
echo $_FILES["file"]["name"] . " already exists. ";
}
else
{
move_uploaded_file($_FILES["file"]["tmp_name"],
"upload/" . $_FILES["file"]["name"]);
}
}
}
else
{
}
echo "<span class='red'>E-mail has been sent successfully from $mail_name to $to</span>"; }
else{
echo "<span class='red'>Failed to send the E-mail from $from to $to</span>";
}
}
?>
p/s:I used this code.hope its work and assist you.just copy and paste.make sure your textfield name is same as in this page.its work for all types of files.for further questions,just email me at shah#mc-oren.com.anyway,i also in learning process.=).thanks.

Categories