473,586 Members | 2,683 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 5446
"Dave Smithz" <SPAM FREE WORLD> wrote in
news:42******** @news1.homechoi ce.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*********@ya hoo.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*********@ya hoo.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($d irectory)
{
$files=array();
$numfiles = 0;

$handle=opendir ($directory);

while($file = readdir($handle ))
{
if($file != ".")
{
if(($directory != ".")||($fil e != ".."))
{
$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,st rrpos($file,"." ),strlen($file) );
$icon_path = "/icons/"; // Web path to icon images
$image = "generic.gi f"; // 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")||($ex t == ".php") ||($ext == ".inc"))
{
$image = "binary.gif ";
}
elseif(($ext == ".z")||($ex t == ".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.$ima ge;
}

/*
Here was a place to check authorization to the FTP
//?>
// <body bgcolor=\"#FFFF FF\" 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=$_REQUE ST['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_TRANSLATE D"];
$thisname=basen ame(__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,st rrpos($file,"." ),strlen($file) );
if($ext=="jpg")
{
header("Content-Type: picture/jpeg");
}
elseif($ext=="t xt")
{
header("Content-Type: picture/jpeg");
}
else
{
header("Content-Type: unknown");
}
print $contents;
ob_flush();
// sleep(4);
exit;

}
else
{

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

// Make a directory
if($action == "mkdir")
{
if($file!="")
{
if($cwd == ".")
{
$thedir = $file;
}
else
{
$thedir = $cwd."/".$file;
}
if(!file_exists ($thedir))
{
mkdir($thedir,0 777);
}
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(subs tr
($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_TRANSLATE D is [".$_SERVER
["PATH_TRANSLATE D"]."]<br>";

$p=strrpos($upl oad_path,"/");
if($p>0)
{
$upload_path=su bstr($upload_pa th, 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=basenam e($_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_p ath.
$target."<br>";
if(is_file($upl oad_path.$targe t))
{
unlink($upload_ path.$target);
}
copy($source,$u pload_path.$tar get);
//copy($file,$_SE RVER['DOCUMENT_ROOT'].$file);
sleep(1);
}
else
{
if($debug) print "Copying ".$source." to ".$upload_p ath.
$cwd."/".$target."<br> ";
if(is_file($upl oad_path.$cwd."/".$target))
{
unlink($upload_ path.$cwd."/".$target);
}
copy($source,$u pload_path.$cwd ."/".$target);
}

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

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

<tr>
<td align="left">

<? print "<form method=\"post\" action=\"{$this name}\">\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=\"".$dirp aths[$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=\"{$this name}\">\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">Fi lename</th>
<th align="left">Si ze</th>
<th align="left">Mo dified</th>
<th align="left">De lete</th>
</tr>

<?php
$files = get_dir_list($c wd);
$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,s trrpos($cwd,"/"));
}
else
{
$filepath = $cwd."/".$thefile;
}

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

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

print "<tr>\n";

print "<td align=\"left\"> \r\n";
print "<a href=\"{$thisna me}?cwd=".urlen code
($filepath)."&a ction=cd\">\r\n ";
print "<img src=\"".$image. "\" width=20 height=
22 border=0>".$fil ename;
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}?c wd=".urlencode
($cwd)."&action =rmdir&file=".u rlencode($filep ath)."\"><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($filep ath);
$date = date("m/d/Y",filectime($f ilepath));

print "<tr>\n";
print "<td align=\"left\"> ";
print "<a href=\"{$thisna me}?cwd=".urlen code
($cwd)."&action =get&file=".url encode($filepat h)."\">\r\n";
print "<img src=\"".$image. "\" width=20 height=
22 border=0>".$the file;
print "</a></td>\n";
print "<td align=\"left\"> ".$size."</td>\n";
print "<td align=\"left\"> ".$date."</td>\n";
print "<td align=\"left\"> <a href=\"{$thisna me}?
cwd=".urlencode ($cwd)."&action =rm&file=".urle ncode
($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=\"multi part/form-
data\" action=\"{$this name}\">\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;&nb sp;<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_f ile()
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
2668
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 updated every hour or so. How can I do this easily? I would like to use secure communication even encryption if possible. I would query and insert...
20
2468
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 the site, and then i have to select the file to upload.. i used sendkeys.. and i worked perfect.. BUT ... the computer must be locked for security (...
7
4530
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" ACTION="UploadAction.asp" METHOD="POST" enctype=multipart/form-data> <input type="file" name="fileName"> //etc ... </FORM>
1
2092
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 message 4. Upload the attachements to the filesystem 5. Write the path of the attachements to the SQL server record
0
7839
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
8202
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
0
8338
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
0
6614
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
0
3837
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
0
3865
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2345
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1449
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
1180
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

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.