Reputation: 309
I'm trying to make a "send email" form which uploads files to a folder before the email is sent. The path to the files are then shown in the email, but if the files DO exist i don't want them to be overwritten, but i want to have a number added.
I have composed this tiny code, but it doesn't work!
The error says:
Parse error: syntax error, unexpected '$name_of_uploaded_file' (T_VARIABLE) in /customers/8/5/6/HOMEPAGE/httpd.www/php/mailtest2.php on line 49
The script below now upload a file if the file does not exist. If the file does exist nothing happens. The script ends at it should.
The script have been modified to what caused it not to ad "_1" to filename and save file in folder. Now it saves the file in folder and comes up with error: Error while copying the uploaded file
Can someone please explain to me what i do wrong?
Now all code is shown to debug this:
<?php
//Uploaded file 1
//Settings
$max_allowed_file_size = 2000; // size in KB
$allowed_extensions = array("jpg", "jpeg", "gif", "bmp", "pdf");
error_reporting(E_ALL);
//Upload folder
//name also used later on mail
$name = $_POST['name'];
$d = date('d.m.y');
$varfoldername = "../receivedfiles/$name$d/";
if(!is_dir($varfoldername)) {
mkdir($varfoldername , 0777 , true);
}
$upload_folder = $varfoldername;
//Get the uploaded file information
$name_of_uploaded_file =
basename($_FILES['uploaded_file']['name']);
//Validations
//----- Check if files exists and adds _X to it -----
$original_name_of_file = pathinfo($name_of_uploaded_file, PATHINFO_FILENAME);
$extension = pathinfo($name_of_uploaded_file, PATHINFO_EXTENSION);
$FileCounter = 0;
while (file_exists($varfoldername.$name_of_uploaded_file)) {
$FileCounter++;
$name_of_uploaded_file = $original_name_of_file . '_' . $FileCounter . '.' . $extension;
}
//copy the temp. uploaded file to uploads folder
$path_of_uploaded_file = $upload_folder . $name_of_uploaded_file;
$tmp_path = $_FILES["uploaded_file"]["tmp_name"];
if(is_uploaded_file($tmp_path))
{
if(move_uploaded_file ( $tmp_path,$path_of_uploaded_file ))
{
die("Error while copying the uploaded file");
}
}
//Validate size requirements
$size_of_uploaded_file =
$_FILES["uploaded_file"]["size"]/1024;//size in KBs
if($size_of_uploaded_file > $max_allowed_file_size )
{
die("Fejl: Filen er for stor");
}
//------ Validate the file extension -----
//get the file extension of the file
$type_of_uploaded_file =
substr($name_of_uploaded_file,
strrpos($name_of_uploaded_file, '.') + 1);
$allowed_ext = false;
for($i=0; $i<sizeof($allowed_extensions); $i++)
{
if(strcasecmp($allowed_extensions[$i],$type_of_uploaded_file) == 0)
{
$allowed_ext = true;
}
}
if(!$allowed_ext)
{
die("The uploaded file is not supported file type. \n Send venligst filer af følgende type: .implode(',',$allowed_extensions)");
}
$email = $_POST['email'];
$phone = $_POST['phone'];
$call = $_POST['call'];
$company = $_POST['company'];
$type = $_POST['type'];
$adress = $_POST['adress'];
$hesteid = $_POST['hesteid'];
$hestenavn = $_POST['hestenavn'];
$message = $_POST['message'];
$areacode = $_POST['areacode'];
$land = $_POST['land'];
$formcontent=" Fra: $company \n Navn: $name \n Adresse: $adress , $areacode \n Land: $land \n Telefon: $phone \n Ringes op: $call \n Type: $type \n Hoppens navn og ID: $hestenavn , $hesteid \n Besked: \n $message \n Vedhæftede filer: \n $path_of_uploaded_file";
$recipient = "[email protected]";
$subject = "Besked fra hjemmesiden";
$mailheader = "Fra: $email \r\n";
mail($recipient, $subject, $formcontent, $mailheader) or die("Error!");
header('Location: thank_you.shtml');
?>
Upvotes: 0
Views: 2465
Reputation: 22760
You need to use the .
character to concatenate (stick together) different PHP variables, so:
while (file_exists($varfoldername$name_of_uploaded_file ))
will return you a parse error, because you need to tell PHP you want to string the two variables together, so instead use the .
and write:
while (file_exists($varfoldername.$name_of_uploaded_file))
You may also need to add a /
directory seperator between the two variables, but that's an issue not directly related to your current problem. But it's useful to print $varfoldername.$name_of_uploaded_file
and see if it is the correct filepath layout (has all the /
etc. )
Hi again I just modified the question. Found two stupid bugs. Now the script runs without error but doesn't add "_1" to the filename. – Simon Jensen
Rearrange your code as such:
$FileCounter = 0;
$original_name_of_file = $name_of_uploaded_file;
while (file_exists($varfoldername.$name_of_uploaded_file)) {
$FileCounter++;
$name_of_uploaded_file = $original_name_of_file . '_' . $FileCounter . '.' . $extension;
}
What happened here:
PHP in the while loop is overwriting the $name_of_uploaded_file
so that if you have a file_1.txt
then the next file name in the loop will be file_1.txt_2.txt
and you can see this overwrite is far from perfect, instead you need to save the Original file, and then overwrite the original concatenated with the increment value and then the .txt .
Your original value of $name_of_uploaded_file
is not defined.
$FileCounter
for clarity is incremented before being written into the string.
Your code of $FileCounter++
will not work because you have defined $FileCounter
as a string
by setting it in quote marks. I have removed the quotes so it is now identified by PHP as an integer.
Your file_exists
call should not be in quotes as this is causing PHP extra, and needless work, and also will often confuse you as well as your IDE. The quotes in effect do:
PHP Logic: I found a quote, I will start a string structure, oh, this part looks like a variable, I will stop the string structure, then concatenate this variable value into the string strucuture, then continue the string, oh, another variable, I will stop the string structure, and then concatenate the second variable into this string, then continue. I found another quote so string finished.
Which is a far larger load of work than clearly and concisely defining two variables concatenated with a .
.
$name = $_POST['name'];
$d = date('d.m.y');
/***
Ideally folders should NEVER be relative, always base them from the PHP server
root such as (example only), using $_SERVER['DOCUMENT_ROOT']:
$varfoldername = $_SERVER['DOCUMENT_ROOT']."/data/uploads/receivedfiles/".$name.$d."/";
***/
$varfoldername = "../receivedfiles/".$name.$d."/";
$upload_folder = $varfoldername;
$name_of_uploaded_file = basename($_FILES['uploaded_file']['name']);
$original_name_of_file = pathinfo($name_of_uploaded_file, PATHINFO_FILENAME);
$extension = pathinfo($name_of_uploaded_file, PATHINFO_EXTENSION);
$FileCounter = 0;
while (file_exists($varfoldername.$name_of_uploaded_file)) {
$FileCounter++;
$name_of_uploaded_file = $original_name_of_file . '_' . $FileCounter . '.' . $extension;
}
/***
Now $name_of_uploaded_file will have the numerical appendage as needed.
***/
if(move_uploaded_file( $tmp_path , $varfoldername.$name_of_uploaded_file )){
print "file uploaded!";
}
IMPORTANT
Do not use copy
, instead use PHP Move_upload_file :
if(!copy($tmp_path,$path_of_uploaded_file)){ ...
Becomes
if(move_uploaded_file ( $tmp_path , $path_of_uploaded_file )){ ...
Upvotes: 1
Reputation: 6693
There is not much need for using this long method when you could make a re-usable object out of it.
interface FileUploaderInterface
{
public function upload($path);
}
class FileUploader implements FileUploaderInterface
{
protected $File;
public function __construct($file)
{
$this->File = $file;
return $this;
}
public function upload($path)
{
if(file_exists($path.$this->File['name']))
{
$this->File["tmp_name"] = $this->File["name"] . '-' . time();
move_uploaded_file($this->File, $path . $this->File["name"]);
return false;
}
else
{
move_uploaded_file($this->File, $path . $this->File["name"]);
return true;
}
}
}
Can be used simply by using the require_once()
and then this code:
$obj = new FileUploader($_FILES["fileToUpload"]);
if(!$obj->upload(dirname(__FILE__) . '/example/path/ect')) {
echo "File existed, we added the time onto the name";
}
Upvotes: 1
Reputation: 3264
PHP documentation says:
while (file_exists($varfoldername . $name_of_uploaded_file ))
Maybe you need a $varfoldername . '/' . $name_of_uploaded_file
- best is if you could give us a var_dump of these two variables.
Upvotes: 0