473,416 Members | 1,486 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,416 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 5420
"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: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

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.