Skip to content
View in the app

A better way to browse. Learn more.

Web Designer Forum

A full-screen app on your home screen with push notifications, badges and more.

To install this app on iOS and iPadOS
  1. Tap the Share icon in Safari
  2. Scroll the menu and tap Add to Home Screen.
  3. Tap Add in the top-right corner.
To install this app on Android
  1. Tap the 3-dot menu (⋮) in the top-right corner of the browser.
  2. Tap Add to Home screen or Install app.
  3. Confirm by tapping Install.

php upload & email script

Featured Replies

I have a php script that emails the admin when someone has uploaded a file.

 

At the moment the script is redirecting to email_upload.php but my header redirect is set to index.html

 

Anyone know why it's doing this?

 

<?php
$your_email ='mail@mail.com';// <<=== update to your email address
$visitor_email = '';


if(isset($_POST['submit']))
{
 $file_name = $HTTP_POST_FILES['ufile']['name'];

 $random_digit=rand(0000,9999);

 $new_file_name=$random_digit.$file_name;

 $path= "upload/".$new_file_name;

 if($ufile !=none)
 {
  if(copy($HTTP_POST_FILES['ufile']['tmp_name'], $path))
  {
   //send the email

	$to = $your_email;
	$subject="Uploaded file";
	$from = $visitor_email;

   $body =
	 "Paypal Email: $visitor_email \n".
	 "Image Uploaded: $$new_file_name \n".

	$headers = "From: $from \r\n";
	$headers .= "Reply-To: $visitor_email \r\n";

	header("Location:index.html");
	exit;
  }
  else
  {
   $error = 'Error: File uploaded is too large or in the wrong format, please try again';
  }
 }
}
?>

PHP isn't my strongest point but maybe you have the form action set to go to email_upload.php?

  • Author

I was linking from the wrong form haha.......

 

Anyways had to change the script (as the one above uses a php4 function that doesn't work in php5) but got an issue on the new script, when I upload the files, I get a no files uploaded error but it should display a generic file size or file format error.

 

<?php
$your_email ='gillman56@googlemail.com';// <<=== update to your email address
$visitor_email = '';
$error = '';

//?heck that we have a file
if((!empty($_FILES["uploaded_file"])) && ($_FILES['uploaded_file']['error'] == 0)) {
 //Check if the file is JPEG image and it's size is less than 350Kb
 $filename = basename($_FILES['uploaded_file']['name']);
 $ext = substr($filename, strrpos($filename, '.') + 1);
 if (($ext == "jpg") && ($_FILES["uploaded_file"]["type"] == "image/jpeg") && 
   ($_FILES["uploaded_file"]["size"] < 350000)) {
   //Determine the path to which we want to save this file
     $newname = dirname(__FILE__).'/uploads/'.$filename;
     //Check if the file with the same name is already exists on the server
     if (!file_exists($newname)) {
       //Attempt to move the uploaded file to it's new place
       if ((move_uploaded_file($_FILES['uploaded_file']['tmp_name'],$newname))) {
          //send the email

	        $to = $your_email;
        	$subject="Uploaded file";
	        $from = $visitor_email;

           $body =
	         "Paypal Email: $visitor_email \n".
	         "Image Uploaded: $newname \n".

	        $headers = "From: $from \r\n";
	        $headers .= "Reply-To: $visitor_email \r\n";

	        header("Location:index.html");
	        exit;

       } else {
          $error .= "Error: A problem occurred during file upload!";
       }
     } else {
        $error .= "Error: File ".$_FILES["uploaded_file"]["name"]." already exists";
     }
 } else {
    $error .= "Error: Only .jpg images under 350Kb are accepted for upload";
 }
} else {
  $error .= "Error: No file uploaded";
}
?>

  • Author

Still nothing, I just need a simple upload image and then email the file name to the admin.

 

arghhhhh I hate php

Still nothing, I just need a simple upload image and then email the file name to the admin.

 

arghhhhh I hate php

well i'll see if i can modify it give me a min then u can see if it works :)

 

Btw before i do that do u have this set on ur upload form enctype="multipart/form-data"

Edited by webdesigner93

  • Author

well i'll see if i can modify it give me a min then u can see if it works :)

 

Btw before i do that do u have this set on ur upload form enctype="multipart/form-data"

 

<form action="<?php $_SERVER[php_SELF]; ?>" method="post" enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="file" id="file" />

<input type="submit" name="submit" value="Submit" />
</form>

<?php
$allowed_types = array("image/jpeg","image/pjpeg");
if(isset($_POST['submit'])){
if(isset($_FILES['uploaded_file']['name'])){
//Perform upload
if(!in_array($_FILES['uploaded_file']['type'],$allowed_types)){
echo "You are uploading an invalid file type";
}
elseif($_FILES['uploaded_file']['size'] > 340000){
echo "Your file size is to large";
}
else{
//SEND EMAIL CODE
if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'],'uploads/'.$_FILES['uploaded_file']
['name'])){
//SEND EMAIL AND ECTO FILE UPLOADED
echo "Your file has been uploaded";
}
}
}else{
echo "Please choose a file to upload";
}

}


?>

<form action="<?php $_SERVER[php_SELF]; ?>" method="post" enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="file" id="file" />

<input type="submit" name="submit" value="Submit" />
</form>

 

mmmm this <input type="file" name="file" id="file" /> should be <input type="file" name="uploaded_file" id="file" />, where it says

 

!empty($_FILES["uploaded_file"]["name"])) uploaded_file is the name of your field so if the name of your field is file then you need to replace uploaded_file with the name file

Edited by webdesigner93

  • Author

mmmm this <input type="file" name="file" id="file" /> should be <input type="file" name="uploaded_file" id="file" />, where it says

 

!empty($_FILES["uploaded_file"]["name"])) uploaded_file is the name of your field so if the name of your field is file then you need to replace uploaded_file with the name file

 

Thanks for the code, unfortunately it redirects to the page after the upload but no file is uploaded into the file folder (http://www.garethgillman.co.uk/clients/bespoke/uploads/) and the email isn't sent.

 

If I upload a PNG image, it does say I have uploaded a wrong file type, so is working.

 

Thanks for your help so far.

 

<?php
$your_email ='gillman56@googlemail.com';// <<=== update to your email address
$visitor_email = '';
$error = '';

$allowed_types = array("image/jpeg","image/pjpeg");
if(isset($_POST['submit'])){
 if(isset($_FILES['uploaded_file']['name'])){
  //Perform upload
  if(!in_array($_FILES['uploaded_file']['type'],$allowed_types)){
   echo "You are uploading an invalid file type";
  }
  elseif($_FILES['uploaded_file']['size'] > 340000){
   echo "Your file size is to large";
  }
  else{
   //SEND EMAIL CODE
   $to = $your_email;
   $subject="Uploaded file";
	 $from = $visitor_email;

    $body =
    "Paypal Email: $visitor_email \n".
	  "Image Uploaded: $newname \n".

	 $headers = "From: $from \r\n";
	 $headers .= "Reply-To: $visitor_email \r\n";

	 header("Location:index.html");
	 exit;

   if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'],'uploads/'.$_FILES[ 'uploaded_file'] ['name'])){
    //SEND EMAIL AND ECTO FILE UPLOADED
    echo "Your file has been uploaded";
   }
  } 
 }else{
  echo "Please choose a file to upload";
 }
}

?>

Have you got your file permissions set so it is allowed to upload the file?

  • Author

Have you got your file permissions set so it is allowed to upload the file?

 

755 currently

755 currently

 

Change it to 777, you will need to be able to write to the destination.

  • Author

Change it to 777, you will need to be able to write to the destination.

 

Tried and get a internal server error on 777 & 757,

  • Author

are u setting in the format of 0755 ect..

 

Yeah, am using cpanel which shows the permissions as 0755

I just tried the code on my hosting and it doesn't work at all with the header. If you take the header out, it uploads the image to the ftp but no email is sent.

permissions from cpanel...

 

what else could be affecting the script?

found ur prob exit; ur calling that before the upload so its not calling the move_uploaded_file bit and ur redirecting before the move_uploaded_file bit

 

<?php
$your_email ='gillman56@googlemail.com';// <<=== update to your email address
$visitor_email = '';
$error = '';

$allowed_types = array("image/jpeg","image/pjpeg");
if(isset($_POST['submit'])){
 if(isset($_FILES['uploaded_file']['name'])){
  //Perform upload
  if(!in_array($_FILES['uploaded_file']['type'],$allowed_types)){
   echo "You are uploading an invalid file type";
  }
  elseif($_FILES['uploaded_file']['size'] > 340000){
   echo "Your file size is to large";
  }
  else{
   //SEND EMAIL CODE
   $to = $your_email;
          $subject="Uploaded file";
                $from = $visitor_email;

    $body =
           "Paypal Email: $visitor_email \n".
                 "Image Uploaded: $newname \n".

                $headers = "From: $from \r\n";
                $headers .= "Reply-To: $visitor_email \r\n";



   if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'],'uploads/'.$_FILES[ 'uploaded_file'] ['name'])){
    //SEND EMAIL AND ECTO FILE UPLOADED
    echo "Your file has been uploaded";
   }
 header("Location:index.html");
                exit;
  } 
 }else{
  echo "Please choose a file to upload";
 }
}

?>

 

Try that btw idk if u noticed but ur not calling the mail function to even send the email

Edited by webdesigner93

if(!headers_sent()) {
   header("Location: /index.html");
} else {
   echo "<p>Redirecting...</p><script>window.location='/index.html';</script>";
}

 

You have a serious security problem using $_FILES['uploaded_file']['type'], its supplied by the browser. So I could upload a malicious php script and tell your server it was a image/jpeg and your server would accept it.

  • Author

if(!headers_sent()) {
   header("Location: /index.html");
} else {
   echo "<p>Redirecting...</p><script>window.location='/index.html';</script>";
}

 

You have a serious security problem using $_FILES['uploaded_file']['type'], its supplied by the browser. So I could upload a malicious php script and tell your server it was a image/jpeg and your server would accept it.

 

What do you recommend instead? The site is only a basic image upload for a client who sells photo montages...

  • Author

Also get this error on the amendments by Webdesigner93

 

Warning: Cannot modify header information - headers already sent by (output started at /home/garethgi/public_html/clients/bespoke/custom-montage.php:33) in /home/garethgi/public_html/clients/bespoke/custom-montage.php on line 35

Also get this error on the amendments by Webdesigner93

Put ob_start(); right after the opening php tag should fix it :)

 

btw u can also use jocks code to fix this which checks if the headers are sent or not, if there not it uses the php way otherwise it uses a javascript solution

Edited by webdesigner93

  • Author

Made a few amendments and now is working, thanks for the help guys.

 

Jock I am interested in learning how to secure the uploading if you got time.

Assuming you have PHP 5 and FileInfo...

 

<?php
class Upload extends SplFileInfo 
{
   private $allowed_types = array("image/jpeg", "image/pjpeg");

   public function getMime() 
   {   
       $filename = $this->getRealPath();

       $finfo = finfo_open(FILEINFO_MIME);
       $mimestring = finfo_file($finfo, $filename);
       finfo_close($finfo);

       $mimetype = explode(';', $mimestring);

       return trim($mimetype[0]);
   }

   public function isValid()
   {
       return in_array($this->getMime(), $this->allowed_types);
   }
}

$your_email ='gillman56@googlemail.com';// <<=== update to your email address
$visitor_email = '';
$error = '';

if(isset($_POST['submit'])) {
   if(isset($_FILES['uploaded_file']['tmp_name'])) {

       $upload = new Upload($_FILES['uploaded_file']['tmp_name']);

      //Perform upload
       if(!$upload->isValid()) {
           echo "You are uploading an invalid file type";
       } elseif($upload->getSize() > 340000){
           echo "Your file size is to large";
       } else {
           //SEND EMAIL CODE
           $to = $your_email;
                  $subject="Uploaded file";
                        $from = $visitor_email;

            $body =
                   "Paypal Email: $visitor_email \n".
                         "Image Uploaded: $newname \n".

                        $headers = "From: $from \r\n";
                        $headers .= "Reply-To: $visitor_email \r\n";

           if(move_uploaded_file($upload->getRealPath(), 'uploads/'.$_FILES['uploaded_file']['name'])) {
               echo "Your file has been uploaded";

               //mail here?

               if(!headers_sent()) {
                   header("Location: /index.html");
               } else {
                   echo "<p>Redirecting...</p><script>window.location='/index.html';</script>";
               }
           } 
       }
   } else {
      echo "Please choose a file to upload";
   }
}

?>
<form action="<?=$_SERVER[php_SELF]; ?>" method="post" enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="uploaded_file" id="file" />

<input type="submit" name="submit" value="Submit" />
</form>

  • Author

I get an error "all to undefined function finfo_open()" so means I don't have fileinfo installed?

 

Is there a way to check if it's installed on my clients server?

  • Author

Okay clients server doesn't have it either, what's the next best way to make this script without the fileinfo support?

Is it a unix based server? try this...

 

class Upload extends SplFileInfo 
{
   private $allowed_types = array("image/jpeg", "image/pjpeg");

   public function getMime() 
   {   
       $filename = $this->getRealPath();

       $mimestring = shell_exec('file -bi '.$filename);
       $mimetype = explode(';', $mimestring);

       return trim($mimetype[0]);
   }

   public function isValid()
   {
       return in_array($this->getMime(), $this->allowed_types);
   }
}

  • Author

Is it a unix based server? try this...

 

class Upload extends SplFileInfo 
{
   private $allowed_types = array("image/jpeg", "image/pjpeg");

   public function getMime() 
   {   
       $filename = $this->getRealPath();

       $mimestring = shell_exec('file -bi '.$filename);
       $mimetype = explode(';', $mimestring);

       return trim($mimetype[0]);
   }

   public function isValid()
   {
       return in_array($this->getMime(), $this->allowed_types);
   }
}

 

Warning: shell_exec() has been disabled for security reasons in .........

 

The client is on a linux server, php 5.2.14

 

God I hate PHP...

  • Author

useless server.

 

Is there any other way around this, or shall I just leave it open.

 

The form will be hid behind a paypal form so they will have to make a payment first before getting to the form.

I guess so, just go back to using $_FILES['uploaded_file']['type'] its probably better than nothing. I guess if anything bad does happen you can refer them back to this thread to prove you made it as secure as possible given the environment restrictions.

Create an account or sign in to comment

Account

Navigation

Search

Search

Configure browser push notifications

Chrome (Android)
  1. Tap the lock icon next to the address bar.
  2. Tap Permissions → Notifications.
  3. Adjust your preference.
Chrome (Desktop)
  1. Click the padlock icon in the address bar.
  2. Select Site settings.
  3. Find Notifications and adjust your preference.