472,354 Members | 2,192 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 472,354 software developers and data experts.

Email with file attachements - How to upload file to server from browser?

Hi There,

I have a PHP script that sends an email with attachment and works great when
provided the path to the file to send.

However this file needs to be on the same server as the script.

I want to develop a webpage where people can send attachments that are
stored on their local PC.

I know I can use the <input type="file" > HTML to generate a file box that
allows the user to navigate to a file on their PC and product a file path,
but how do I then upload this file onto file server to email out with my PHP
email script?

Is there an easy way to do this?

Or can I approach this problem from a completely different angle.

Kind regards

Dave
Jul 17 '05 #1
5 5261
"Dave Smithz" <SPAM FREE WORLD> wrote in
news:42********@news1.homechoice.co.uk:

I want to develop a webpage where people can send attachments that are
stored on their local PC.

I know I can use the <input type="file" > HTML to generate a file box
that allows the user to navigate to a file on their PC and product a
file path, but how do I then upload this file onto file server to
email out with my PHP email script?


http://www.php.net/manual/en/features.file-upload.php

--
Dave Patton
Canadian Coordinator, Degree Confluence Project
http://www.confluence.org/
My website: http://members.shaw.ca/davepatton/
Jul 17 '05 #2
Dave
Try this. It allows a visitor to upload to your site as FTP over
HTML. It is a very powerful tool as the visitor also has the
power to delete files; but they can only upload to the directory
you place this text in.
There is a size limit set by the php.ini file that you need to
check and increase or decrease depending on your requirments; I
would also restrict the access to the page (to protect
yourself!)
I take no credit for the file, see comments for the originator
Copy from here and paste into a php file:

<?php
// --------------------------------------------------
// Virtual FTP Program for PHP4 +
// By Mathew Eis <ki*********@yahoo.com>
// --------------------------------------------------
// Modified for Win32 Apache by Mark Shaw - 2004
// Added: rudimentary exploit protection
// PUT parse correctly for DOS folder x:/whatever
// PUT correct relative paths
// Extra checks for operations
// Add @ prefix to avoid error warnings
// Change dates to UK date format
// Colour scheme change
// Smaller font for filename table
// Standard Apache32 icon set
// --------------------------------------------------
// TODO:
// Probably several security holes via cmd-line
// Add authentication for user
// Add more security protection against root traverse
// Add extra checks for R/O operations suchy as RMDIR
// --------------------------------------------------
// BUGS:
// View .txt file with PHP code whizzes past file and
// loads /.$newurl.
// --------------------------------------------------
// By Mathew Eis <ki*********@yahoo.com>
// I originally made this program when I was
// running through a bunch of free webhosters
// I got tired of relearning their interface
// so I made this one. I now have a 'real'
// website, and no longer need 'virtual' FTP.
// I couldn't bear to just dump it, so here it
// is. Now I'll probably have to make a bunch
// of new versions ;)

// There is also an online web editor that I
// made to go with it... I'll add it in a few weeks

// Function to get the listing of a directory
// Syntax: get_dir_list("/usr/local/bin");
// Gets:
// Path to directory
// Trailing slash shouldn't matter
// Returns:
// Array of files & folders in the directory
// --------------------------------------------------
ob_start(); //Start delayed flush to web page
function get_dir_list($directory)
{
$files=array();
$numfiles = 0;

$handle=opendir($directory);

while($file = readdir($handle))
{
if($file != ".")
{
if(($directory != ".")||($file != ".."))
{
$files[$numfiles] = $file;
$numfiles++;
}
}
}

reset($files);

return $files;
}

// This function was used to decide which icon to show for a
file.
// I used Apache's default icons...

function get_icon($file, $filename)
{
@$ext = substr($file,strrpos($file,"."),strlen($file));
$icon_path = "/icons/"; // Web path to icon images
$image = "generic.gif"; // This is the icon if we don't know
what to use

if($filename == "..")
{
$image = "back.gif";
}
elseif(is_dir($file))
{
$image = "dir.gif";
}
elseif(($ext == ".jpg")||($ext == ".jpeg")||($ext == ".gif")||
($ext == ".png")||($ext == ".bmp")||($ext == ".tiff"))
{
$image = "image2.gif";
}
elseif(($ext == ".txt")||($ext == ".text"))
{
$image = "text.gif";
}
elseif(($ext == ".c")||($ext == ".php") ||($ext == ".inc"))
{
$image = "binary.gif";
}
elseif(($ext == ".z")||($ext == ".gz") ||($ext == ".zip") ||
($ext == ".7z"))
{
$image = "compressed.gif";
}

elseif(($ext == ".html")||($ext == ".htm")||($ext == ".shtml")
||($ext == ".php")||($ext == ".php3"))
{
$image = "layout.gif";
}

return $icon_path.$image;
}

/*
Here was a place to check authorization to the FTP
//?>
// <body bgcolor=\"#FFFFFF\" text=\"#000000\">
//<?

if(!$hasaccess)
{
print "You do not have access";
}
else
{
*/
global $debug;
global $action;
global $cwd;
global $file;
global $upload_path;
global $source;
global $target;
global $thisname;

$debug=False; //NOTE: If debug is ON then
debug output will ALSO go to ANY viewed file!!
$action=$_REQUEST['action']; //Needed if set to safe mode
$cwd=$_REQUEST['cwd']; //Needed if set to safe mode
$file=$_REQUEST['file']; //Needed if set to safe mode
$upload_path=$_SERVER["PATH_TRANSLATED"];
$thisname=basename(__FILE__); //

if ($debug)
{
print "DEBUG: Action=[".$action."] ";
print "CWD=[".$cwd."] ";
print "file=[".$file."]<br> ";
}

// Check the cwd...
$cwd = (isset($cwd) ? $cwd : ".");
$cwd = ($cwd == "" ? "." : $cwd);

$action = (isset($action) ? $action : "");

// We want to get a file
if($action == "get")
{
$size = filesize($file);
$handle = fopen($file,"r");
$contents = fread($handle,$size);
fclose($handle);

// Mime types needed work... I didn't have the time for it.

@$ext = substr($file,strrpos($file,"."),strlen($file));
if($ext=="jpg")
{
header("Content-Type: picture/jpeg");
}
elseif($ext=="txt")
{
header("Content-Type: picture/jpeg");
}
else
{
header("Content-Type: unknown");
}
print $contents;
ob_flush();
// sleep(4);
exit;

}
else
{

// Print your header file here
// include("ftpheader.inc");

// Make a directory
if($action == "mkdir")
{
if($file!="")
{
if($cwd == ".")
{
$thedir = $file;
}
else
{
$thedir = $cwd."/".$file;
}
if(!file_exists($thedir))
{
mkdir($thedir,0777);
}
else
{
print "Directory ".$thedir." already exists";
}
}
}

// Remove a file
if($action == "rm")
{
if(substr($file,0,2)=="..")
{
print "Deleting above root level is not allowed for file
".$file;
sleep(5);
exit;
}
else
{
if($debug) print "Removing [".$file."]";
if(file_exists($file))
{
@unlink($file);
}
}
}

// Remove a directory
if($action == "rmdir") //Path held in $file is already
corrected to be root-relative
{
// if($cwd==".")
if(substr($file,0,2)=="..") // || strtoupper(substr
($file,0,3))=="%2E")
{
print "Deleting above root level is not allowed for
directory ".$file;
sleep(5);
exit;
}
else
{
if($debug) print "Removing directory [".$file."]";
@rmdir($file);
}

// else
// {
//print "Removing [".$cwd."/".$file."]";
// rmdir($cwd."/".$file);
// }
}

if($action == "cd")
{
if($cwd!="..")
{
if($debug) print "Changing dir to ".$file;
chdir($file);
}
}
// --------------------------------------------------------
// Upload a file
// On slow servers, the file is not copied fast enough
// to be stat' in the next list command. It shows up in
// The listing, but you can't get the size. There must
// be a workaround, but I didn't put that much time into
// it. It worked, that was enough.
// --------------------------------------------------------

if($action == "put")
{
if($debug) print "PUT detected - Uploading [".$file."]<br>";
if($debug) print "PHP_SELF is [".$_SERVER["PHP_SELF"]."]<br>";
if($debug) print "PATH_TRANSLATED is [".$_SERVER
["PATH_TRANSLATED"]."]<br>";

$p=strrpos($upload_path,"/");
if($p>0)
{
$upload_path=substr($upload_path, 0, $p+1);
if($debug) print "Upload path is [".$upload_path."]";
}

if ($_SERVER['REQUEST_METHOD']=='POST') //Uploading (PUT) a file
{
//$file=$_FILES["file"]["name"]; //name=media type=file
$target=basename($_FILES["file"]["name"]); //name=media
type=file
$source=$_FILES["file"]["tmp_name"];
}
// if(is_uploaded_file($file)) //if this was the file
uploaded by the POST event
{
if($cwd == ".")
{
if($debug) print "Copying ".$source." to ".$upload_path.
$target."<br>";
if(is_file($upload_path.$target))
{
unlink($upload_path.$target);
}
copy($source,$upload_path.$target);
//copy($file,$_SERVER['DOCUMENT_ROOT'].$file);
sleep(1);
}
else
{
if($debug) print "Copying ".$source." to ".$upload_path.
$cwd."/".$target."<br>";
if(is_file($upload_path.$cwd."/".$target))
{
unlink($upload_path.$cwd."/".$target);
}
copy($source,$upload_path.$cwd."/".$target);
}

//chmod($cwd."/".$file_name,0777);
}
}
?>
<body bgcolor="#000000" text="#000000">
<center>
<table cellpadding=5 cellspacing=0 border=1 width=600
bgcolor="#ffffff">

<tr><th align="left"><font size="+1">Virtual FTP Program
</font></td></tr>
<tr>
<td>
<table border=0 cellpadding=0 cellspacing=0>

<tr>
<td align="left">

<? print "<form method=\"post\" action=\"{$thisname}\">\r
\n"; ?>
<input type="hidden" name="action" value="cd">
Current Directory:
<br>
<select name="cwd">

<?php
$dirpath = split("/",$cwd);
$numpaths = sizeof($dirpath);
$dirpaths = array();
$textpaths = array();

for($cpath = 0; $cpath < $numpaths; $cpath++)
{
if($cpath == 0)
{
$dirpaths[$numpaths-$cpath-1] = $dirpath[$cpath];
}
else
{
$dirpaths[$numpaths-$cpath-1] = $dirpaths[$numpaths-
$cpath-2]."/".$dirpath[$cpath];
}
if($dirpath[$cpath] != ".")
{
$textpaths[$numpaths-$cpath-1] = $dirpath[$cpath];
}
else
{
$textpaths[$numpaths-$cpath-1] = "/";
}
}

for($cpath = 0; $cpath < $numpaths; $cpath++)
{
print "<option value=\"".$dirpaths[$cpath]."\">".
$textpaths[$cpath]."</option>\n";
}
if($cwd != ".")
{
print "<option value=".">/</option>\n";
}
?>

</select>
<input type="submit" value="Change Directory">
</form>
</td>
<td align="left">
<? print "<form method=\"post\" action=\"{$thisname}\">\r
\n"; ?>
<input type="hidden" name="action" value="mkdir">

<?php
print "<input type=\"hidden\" name=\"cwd\" value=\"".
$cwd."\">\n";
?>

Create Directory:
<br>
<input type="text" name="file" size=15>
<input type="submit" value="Create (mkdir)">
</form>
</td>
</tr>
</table>
</td>
</tr>

<tr>
<td>
<table cellpadding=2 cellspacing=0 border="1"
width="100%">
<tr>
<th align="left">Filename</th>
<th align="left">Size</th>
<th align="left">Modified</th>
<th align="left">Delete</th>
</tr>

<?php
$files = get_dir_list($cwd);
$numfiles = sizeof($files);

sort($files);

for($fileat = 0; $fileat < $numfiles; $fileat++)
{
$thefile = $files[$fileat];
$filename = $thefile;
if($cwd == ".")
{
$filepath = $thefile;
}
elseif($thefile == "..")
{
$filepath = substr($cwd,0,strrpos($cwd,"/"));
}
else
{
$filepath = $cwd."/".$thefile;
}

$image = get_icon($filepath,$filename);
print "<font size=\"8\">";

if(($filename == "..")||(is_dir($filepath)))
{
if($filename != "..")
{
$date = date("d/m/Y",filectime($filepath));
}
else
{
$date ="&nbsp;";
}

print "<tr>\n";

print "<td align=\"left\">\r\n";
print "<a href=\"{$thisname}?cwd=".urlencode
($filepath)."&action=cd\">\r\n";
print "<img src=\"".$image."\" width=20 height=
22 border=0>".$filename;
print "</a></td>\n";
print "<td align=\"left\">&nbsp;</td>\n";
print "<td align=\"left\">".$date."</td>\n";

if($filename != "..")
{
print "<td align=\"left\"><a href=
\"{$thisname}?cwd=".urlencode
($cwd)."&action=rmdir&file=".urlencode($filepath). "\"><img src=
\"/icons/alert.red.gif\" width=20 height=20 border=0></a></td>\r
\n";
}
else
{
print "<td>&nbsp;</td>";
}
print "</font>";
print "</tr>\n";
}
else
{
$size = filesize($filepath);
$date = date("m/d/Y",filectime($filepath));

print "<tr>\n";
print "<td align=\"left\">";
print "<a href=\"{$thisname}?cwd=".urlencode
($cwd)."&action=get&file=".urlencode($filepath)."\ ">\r\n";
print "<img src=\"".$image."\" width=20 height=
22 border=0>".$thefile;
print "</a></td>\n";
print "<td align=\"left\">".$size."</td>\n";
print "<td align=\"left\">".$date."</td>\n";
print "<td align=\"left\"><a href=\"{$thisname}?
cwd=".urlencode($cwd)."&action=rm&file=".urlencode
($filepath)."\"><img src=\"/icons/alert.red.gif\" width=20
height=20 border=0></a></td>\n";
print "</font>";
print "</tr>\n";
}

}
?>
</table>
</td>
</tr>

<tr>
<td>
Upload a file into this directory:
<br>
<? print "<form method=\"post\" enctype=\"multipart/form-
data\" action=\"{$thisname}\">\r\n"; ?>
<input type="hidden" name="action" value="put">

<?php
print "<input type=\"hidden\" name=\"cwd\" value=\"".
$cwd."\">\n";
?>

<input type="file" name="file" size=20>&nbsp;&nbsp;
&nbsp;&nbsp;&nbsp;<input type="submit" value="Upload File
(put)">
</form>
</td>
</tr>
</small>
</table>
</center>

<?php
ob_flush();
// } Other end of access block
}
?>

----------------------------------------------
Posted with NewsLeecher v1.0 beta 30 (RC1)
* Binary Usenet Leeching Made Easy
* http://www.newsleecher.com/?usenet
----------------------------------------------

Jul 17 '05 #3
Did you get that code from this site?

http://www.maaking.com/index.php?loadpage=scripts

That might been easier to give him a link,. but I guess now the code is
preserved for all of posteriority.

Jul 17 '05 #4
llbbl wrote:
Did you get that code from this site?

http://www.maaking.com/index.php?loadpage=scripts

That might been easier to give him a link,. but I guess now the code is
preserved for all of posteriority.

Typically you would use input type="file" name="blah" then use
move_uploaded_file()
Jul 17 '05 #5
He does some error checking for file sizes. It is pretty easy to
customize his code to something that you can use for your own site. It
is also good for people who haven't implemented their own version of
the upload function as you have.

Jul 17 '05 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

7
by: Dan V. | last post by:
Situation: I have to connect with my Windows 2000 server using VS.NET 2003 and C# and connect to a remote Linux server at another company's office and query their XML file. Their file may be...
20
by: CHIN | last post by:
Hi all.. here s my problem ( maybe some of you saw me on other groups, but i cant find the solution !! ) I have to upload a file to an external site, so, i made a .vbs file , that logins to...
7
by: Joe | last post by:
I have an upload file operation in the web application. UploadForm.asp is the form, and UploadAction.asp is the form processing. //UploadForm.asp <FORM NAME="InputForm"...
1
by: hanan_cohen | last post by:
Shalom, I am looking for a system that will: 1. Read a message from a POP3 mailbox 2. Parse the message into its parts 3. Create a record in an SQL server table with selected fields of the...
0
by: Naresh1 | last post by:
What is WebLogic Admin Training? WebLogic Admin Training is a specialized program designed to equip individuals with the skills and knowledge required to effectively administer and manage Oracle...
0
by: AndyPSV | last post by:
HOW CAN I CREATE AN AI with an .executable file that would suck all files in the folder and on my computerHOW CAN I CREATE AN AI with an .executable file that would suck all files in the folder and...
0
by: Arjunsri | last post by:
I have a Redshift database that I need to use as an import data source. I have configured the DSN connection using the server, port, database, and credentials and received a successful connection...
0
hi
by: WisdomUfot | last post by:
It's an interesting question you've got about how Gmail hides the HTTP referrer when a link in an email is clicked. While I don't have the specific technical details, Gmail likely implements measures...
1
by: Matthew3360 | last post by:
Hi, I have been trying to connect to a local host using php curl. But I am finding it hard to do this. I am doing the curl get request from my web server and have made sure to enable curl. I get a...
0
Oralloy
by: Oralloy | last post by:
Hello Folks, I am trying to hook up a CPU which I designed using SystemC to I/O pins on an FPGA. My problem (spelled failure) is with the synthesis of my design into a bitstream, not the C++...
0
by: Carina712 | last post by:
Setting background colors for Excel documents can help to improve the visual appeal of the document and make it easier to read and understand. Background colors can be used to highlight important...
0
BLUEPANDA
by: BLUEPANDA | last post by:
At BluePanda Dev, we're passionate about building high-quality software and sharing our knowledge with the community. That's why we've created a SaaS starter kit that's not only easy to use but also...
0
by: Ricardo de Mila | last post by:
Dear people, good afternoon... I have a form in msAccess with lots of controls and a specific routine must be triggered if the mouse_down event happens in any control. Than I need to discover what...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.