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

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Dave Smithz

    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


  • Dave Patton

    #2
    Re: Email with file attachements - How to upload file to server from browser?

    "Dave Smithz" <SPAM FREE WORLD> wrote in
    news:42097b07$1 @news1.homechoi ce.co.uk:

    [color=blue]
    > 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?[/color]



    --
    Dave Patton
    Canadian Coordinator, Degree Confluence Project
    The Degree Confluence Project contains photographs of the intersections of integer latitude and longitude degree lines.

    My website: http://members.shaw.ca/davepatton/

    Comment

    • Luddite88

      #3
      Re: Email with file attachements - How to upload file to server from browser?

      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 <king_ro_bot@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 <king_ro_bot@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
      ----------------------------------------------

      Comment

      • llbbl

        #4
        Re: Email with file attachements - How to upload file to server from browser?

        Did you get that code from this site?



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

        Comment

        • Joe Estock

          #5
          Re: Email with file attachements - How to upload file to server frombrowser?

          llbbl wrote:[color=blue]
          > 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.
          >[/color]
          Typically you would use input type="file" name="blah" then use
          move_uploaded_f ile()

          Comment

          • llbbl

            #6
            Re: Email with file attachements - How to upload file to server from browser?

            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.

            Comment

            Working...