Link to home
Create AccountLog in
Avatar of LearningPHPMySQL
LearningPHPMySQL

asked on

help with modifying a PHP upload script

hello, I wonder if i could get some help modifying this upload script please.

At the moment I have it so a user can upload a document to the server.

What i need to be able to do now though is

1. The user selects a course from a dropdown list on the form, and then uploads the document. That dropdown list is populated from a table in my mysql database called leaders. the column names are ID, course , email.  

2. When a user selects a course from the dropdown list and submits the document, i would like to send an email to the address attached to course, and in the email  there will be a link to the new uploaded document on the server.

As i say the uploading of the document works at the moment but need some help modifying it with the above modifications. Could somebody help me please?.

Regards,

LPHP
<?PHP
require_once("Session.class");
$sess = new Session();
if($sess->getVariable("auth") != "yes")
{
	header("Location: ../login-OOtest.php");
	exit();
}
include('header.html');
 
echo("<center><h1>Paper Submissions</h1>");
echo("Please rename paper to delegate name. i.e joe_bloggs.pdf");
echo("<br />");
echo("<form action=\"./upload1.php\" method=\"post\" enctype=\"multipart/form-data\"/>");
echo("<label for=\"file\">Select a file:</label>
	  <input type=\"file\" name=\"userfile\" id=\"file\"/>
	  <button>Upload File</button></center>");
 
 
 include('footer.html');
?>
 
<?PHP
 
 
// Configuration - Options
// These will be the types of file that will pass the validation.
	$allowed_filetypes = array('.doc','.txt','.pdf');
// Maximum filesize in BYTES.
	$max_filesize = 2000000;
// The place the files will be uploaded to (currently /uploads/ directory).
    $upload_path = './uploads/';
// Get the name of the file (including file extension).
   	$filename = $_FILES['userfile']['name'];
// Get the extension from the filename.
   	$ext = substr($filename, strpos($filename,'.'), strlen($filename)-1);
 
// Check if the filetype is allowed, if not DIE and inform the Delegate.
   if(!in_array($ext,$allowed_filetypes))
      die('The file you attempted to upload is not allowed.');
 
// Check the filesize, if it is too large then DIE and inform the Delegate.
   if(filesize($_FILES['userfile']['tmp_name']) > $max_filesize)
      die('The file you attempted to upload is too large.');
 
// Check if we can upload to the specified path, if not DIE and inform the Delegate.
   if(!is_writable($upload_path))
      die('You cannot upload to the specified directory, please CHMOD it to 777.');
 
// Upload the file to your specified path.
   if(move_uploaded_file($_FILES['userfile']['tmp_name'],$upload_path . $filename))
         echo 'Your file upload was successful, view the file <a href="' . $upload_path . 			                 $filename . '" title="Your File">here</a>';
// It worked.
      else
// It failed :(.
         echo 'There was an error during the file upload.  Please try again.';
 
?>

Open in new window

Avatar of Bobaran98
Bobaran98
Flag of United States of America image

There are several components to getting you where you want to go.  I assume you can get into your database and generate the drop-down <select> menu.  The code below assumes you named that field "courseID"

The tricky thing here-- what I'm assuming you're mainly asking about-- is the mail component of it.  If not, let me know.  What's tricky is that it all depends on how your mail server is setup.  Are you using shared hosting?  Do you have a dedicated server?  Does your domain, in fact, have its own separate mail server?

The code below is fairly standard and may work as is.  If not, you can try:
  • removing the ini_set lines (try leaving each in by itself, or removing both)
  • try just your domain name-- www.mydomainname.com-- rather than mail
  • if you have your address setup in Outlook or another mail client, check your settings and see what your outgoing server is; that server name should work in the SMTP line
Note that this function is more likely to work if you're sending and receiving messages within the same domain.  If you have problems getting it going, try testing it in just a simple script where you do nothing but call the mail() function using constant values (in other words, remove anything else from your code that may be causing a problem.

I know that's a bit wide open.  Let me know if it helps!

<?php
 
// Upload the file to your specified path.
   if(move_uploaded_file($_FILES['userfile']['tmp_name'],$upload_path . $filename)) {
         echo 'Your file upload was successful, view the file <a href="' .
			 $upload_path . $filename . '" title="Your File">here</a>';
 
		$course_details = mysql_query("SELECT * FROM leaders WHERE ID=" .
			$_REQUEST['courseID']);
 
		$email_message = "A user has just submitted a file for the course " . 
			mysql_result($course_details,0,"course") .
			".  That file can be downloaded here: " . 
			"http://www.mydomainname.com/uploads/" . $filename
		
		$email_address = mysql_result($course_details,0,"email");
 
		// mydomainname.com is your domain and joe@mydomainname.com is your email
		ini_set ("sendmail_from","joe@mydomainname.com");
		ini_set("SMTP","mail.mydomainname.com");
		mail($email_address, "joe@mydomainname.com", "New File Upload!", $email_message);
 
// It worked.
   }  else {
// It failed :(.
         echo 'There was an error during the file upload.  Please try again.';
   }
 
 
 
 
 
?>

Open in new window

Avatar of LearningPHPMySQL
LearningPHPMySQL

ASKER

would i do this?  

bear with me please,  I'm new to all this :'(
upload.php
<?PHP
require_once("includes/account.class");
require_once("includes/database.class");
 
try {
	$db = new Database("includes/vars.inc");
	// use database "test"
	$db->useDatabase("test");
	// create new account.
	$conn = new connection($db->getConnection(), "leaders");
}
catch(Exception $e) {
	echo $e->getMessage() . "\n <br /> ";
	exit();
}
include('header.html');
 
$list = mysql_query("SELECT * FROM leaders");
 
echo("<center><h1>Paper Submissions</h1>");
echo("Please rename paper to delegate name. i.e joe_bloggs.pdf");
echo("<br />");
echo("<form action=\"./upload1.php\" method=\"post\" enctype=\"multipart/form-data\"/>");
echo("<label for=\"file\">Select a file:</label>
	  <input type=\"file\" name=\"userfile\" id=\"file\"/>
	  <select name=\"list\" size=\"10\"></select>
	  <option value=\"$list['course']\"></option>
	  <button>Upload File</button></center>");
 
 
 include('footer.html');
?>
 
upload1.php
<?PHP
/**
require_once("includes/account.class");
require_once("includes/database.class");
 
try {
	$db = new Database("includes/vars.inc");
	// use database "test"
	$db->useDatabase("test");
	// create new account.
	$conn = new connection($db->getConnection(), "leaders");
}
catch(Exception $e) {
	echo $e->getMessage() . "\n <br /> ";
	exit();
}
// Configuration - Options
// These will be the types of file that will pass the validation.
	$allowed_filetypes = array('.doc','.txt','.pdf');
// Maximum filesize in BYTES.
	$max_filesize = 2000000;
// The place the files will be uploaded to (currently /uploads/ directory).
    $upload_path = './uploads/';
// Get the name of the file (including file extension).
   	$filename = $_FILES['userfile']['name'];
// Get the extension from the filename.
   	$ext = substr($filename, strpos($filename,'.'), strlen($filename)-1);
 
// Check if the filetype is allowed, if not DIE and inform the Delegate.
   if(!in_array($ext,$allowed_filetypes))
      die('The file you attempted to upload is not allowed.');
 
// Check the filesize, if it is too large then DIE and inform the Delegate.
   if(filesize($_FILES['userfile']['tmp_name']) > $max_filesize)
      die('The file you attempted to upload is too large.');
 
// Check if we can upload to the specified path, if not DIE and inform the Delegate.
   if(!is_writable($upload_path))
      die('You cannot upload to the specified directory, please CHMOD it to 777.');
 
// Upload the file to your specified path.
if(move_uploaded_file($_FILES['userfile']['tmp_name'],$upload_path . $filename)) {
	echo 'Your file upload was successful, view the file <a href="' .
                         $upload_path . $filename . '" title="Your File">here</a>';
 
	$course_details = mysql_query("SELECT * FROM leaders WHERE ID=" .
                        $_REQUEST['courseID']);
 
	$email_message = "A user has just submitted a file for the course " .
                        mysql_result($course_details,0,"course") .
                        ".  That file can be downloaded here: " .
                        "http://www.mydomainname.com/uploads/" . $filename
    $email_address = mysql_result($course_details,0,"email");
 
// mydomainname.com is your domain and joe@mydomainname.com is your email
      ini_set ("sendmail_from","joe@mydomainname.com");
	  ini_set("SMTP","mail.mydomainname.com");
	  mail($email_address, "joe@mydomainname.com", "New File Upload!", $email_message);
// It worked.
      else
// It failed :(.
         echo 'There was an error during the file upload.  Please try again.';
 
 
?>

Open in new window

Are you asking for help with accessing your MySQL database?  In other words, are you asking about the code in lines 6 - 16?
I am reusing code from another script (my login script) to connect to the database. I have spotted the error on line 11 which should be new Account.

Now the connection is there though i need help with the form, so it populates the listbox so i can pick a course, and then upload document and click submit.  Then it runs upload1.php and hopefully when done uploads the document to a directory and also sends an email with the link to the email associated with that course.
Personally, I use a different method for connecting to and accessing the database.  With your connection method, I'm not sure if my code will work, but let's give it a shot.  If it doesn't work, let me know and I'll show you my connection method... but you'll need to know your database's address and your logon name and password.

<!-- You'll want to put this code up top, where you've
	currently got your try/catch block //-->
<?php
 
	//connect to MySQL and select database
	$db = new Database("includes/vars.inc");
	mysql_select_db("test",$db) or die("Cannot select database");
 
	if($_REQUEST['courseID']=="") {
		//generate resultset for first visit
		$courseQuery = "SELECT * FROM leaders ORDER BY course ASC";
		$courseResult = mysql_query($courseQuery) or die("Cannot execute list query");
		$numCourses = mysql_numrows($courseResult);
	} else {
		//get details for selected course
		$courseQuery = "SELECT * FROM leaders WHERE ID = " . $_REQUEST['courseID'];
		$courseDetails = mysql_query($courseQuery) or die("Cannot execute details query");
	}
 
?>
 
 
<!-- Add this code wherever you want your listbox to appear //-->
<?php
 
	//print dropdown select box of courses
	echo "<select name='courseID'>";
	for($i=0;$i<$numCourses;$i++) {
		echo "<option value='" . 
			mysql_result($courseResult,$i,"ID") . "'>";
		echo mysql_result($courseResult,$i,"course");
		echo "</option>";
	}
	echo "</select>";
 
?>
 
 
<!-- The following is an adapted version of the first code block
	I posted in response to your question; my same notes and suggestions
	from my first post apply //-->
<?php
 
// Upload the file to your specified path.
   if(move_uploaded_file($_FILES['userfile']['tmp_name'],$upload_path . $filename)) {
         echo 'Your file upload was successful, view the file <a href="' .
                         $upload_path . $filename . '" title="Your File">here</a>';
 
                $email_message = "A user has just submitted a file for the course " . 
                        mysql_result($courseDetails,0,"course") .
                        ".  That file can be downloaded here: " . 
                        "http://www.mydomainname.com/uploads/" . $filename
                
                $email_address = mysql_result($courseDetails,0,"email");
 
                // mydomainname.com is your domain and joe@mydomainname.com is your email
                ini_set ("sendmail_from","joe@mydomainname.com");
                ini_set("SMTP","mail.mydomainname.com");
                mail($email_address, "joe@mydomainname.com", "New File Upload!", $email_message);
 
// It worked.
   }  else {
// It failed :(.
         echo 'There was an error during the file upload.  Please try again.';
   }
 
?>

Open in new window

thank you, I will try have a go at this now. Thank you for helping me , I need it :o
It's my pleasure.  I love this stuff! :-)
have i got the first page correct .. upload.php?

and in the 2nd page upload1.php  phpedit is showing an error on this line

$email_address = mysql_result($courseDetails,0,"email"); saying unexpectid T variable ??
<?PHP
 
try {
	//connect to MySQL and select database
	$db = new Database("includes/vars.inc");
	mysql_select_db("test",$db) or die("Cannot select database");
 
	if($_REQUEST['courseID']=="") {
		//generate resultset for first visit
		$courseQuery = "SELECT * FROM leaders ORDER BY course ASC";
		$courseResult = mysql_query($courseQuery) or die("Cannot execute list query");
		$numCourses = mysql_numrows($courseResult);
	} else {
		//get details for selected course
		$courseQuery = "SELECT * FROM leaders WHERE ID = " . $_REQUEST['courseID'];
		$courseDetails = mysql_query($courseQuery) or die("Cannot execute details query");
	}
 
}
catch(Exception $e) {
	echo $e->getMessage() . "\n <br /> ";
	exit();
}
include('header.html');
 
 
echo("<center><h1>Paper Submissions</h1>");
echo("Please rename paper to delegate name. i.e joe_bloggs.pdf");
echo("<br />");
echo("<form action=\"./upload1.php\" method=\"post\" enctype=\"multipart/form-data\"/>");
echo("<label for=\"file\">Select a file:</label>");
echo("<input type=\"file\" name=\"userfile\" id=\"file\"/>");
	//print dropdown select box of courses
echo("<select name='courseID'>");
	for($i=0;$i<$numCourses;$i++) {
echo("<option value='" . mysql_result($courseResult,$i,"ID") . "'>");
echo mysql_result($courseResult,$i,"course");
echo("</option>");
	}
echo ("</select>");
echo ("<button>Upload File</button></center>");
 
 
include('footer.html');
?>
 
<?PHP
 
// Configuration - Options
// These will be the types of file that will pass the validation.
	$allowed_filetypes = array('.doc','.txt','.pdf');
// Maximum filesize in BYTES.
	$max_filesize = 2000000;
// The place the files will be uploaded to (currently /uploads/ directory).
    $upload_path = './uploads/';
// Get the name of the file (including file extension).
   	$filename = $_FILES['userfile']['name'];
// Get the extension from the filename.
   	$ext = substr($filename, strpos($filename,'.'), strlen($filename)-1);
 
// Check if the filetype is allowed, if not DIE and inform the Delegate.
   if(!in_array($ext,$allowed_filetypes))
      die('The file you attempted to upload is not allowed.');
 
// Check the filesize, if it is too large then DIE and inform the Delegate.
   if(filesize($_FILES['userfile']['tmp_name']) > $max_filesize)
      die('The file you attempted to upload is too large.');
 
// Check if we can upload to the specified path, if not DIE and inform the Delegate.
   if(!is_writable($upload_path))
      die('You cannot upload to the specified directory, please CHMOD it to 777.');
 
// Upload the file to your specified path.
if(move_uploaded_file($_FILES['userfile']['tmp_name'],$upload_path . $filename)) {
	echo 'Your file upload was successful, view the file <a href="' .
	                $upload_path . $filename . '" title="Your File">here</a>';
 
	$email_message = "A user has just submitted a file for the course " .
	               mysql_result($courseDetails,0,"course") .
	               ".  That file can be downloaded here: " .
	               "http://www.mydomainname.com/uploads/" . $filename
                
	       $email_address = mysql_result($courseDetails,0,"email");
 
	// mydomainname.com is your domain and joe@mydomainname.com is your email
	ini_set ("sendmail_from","joe@mydomainname.com");
	ini_set("SMTP","mail.mydomainname.com");
	mail($email_address, "joe@mydomainname.com", "New File Upload!", $email_message);
 
	// It worked.
}  else {
	// It failed :(.
	echo 'There was an error during the file upload.  Please try again.';
}
 
?>

Open in new window

Sorry, I wasn't looking very closely, and I assumed all the code was in one page.  Your code for the first page looks ok... because you're not doing everything in one page, though, you can remove that conditional at the top and just stick with:

try {
     //connect to MySQL and select database
      $db = new Database("includes/vars.inc");
      mysql_select_db("test",$db) or die("Cannot select database");
 
            //generate resultset for first visit
            $courseQuery = "SELECT * FROM leaders ORDER BY course ASC";
            $courseResult = mysql_query($courseQuery) or die("Cannot execute list query");
            $numCourses = mysql_numrows($courseResult);
}
When you load it up, does the list populate ok?

As for your second page, you need to access your database again.  Use the following code at the beginning of the file, just like you do in the first page.  The way you've got it above, it shouldn't work.  However, if after you update it as below, you still get that "unexpected T variable" error, check to make sure your field name is correct (i.e. are you sure the field is called "email"?).

About editing your previous post to remove your name... I don't have the foggiest.  Sorry!

<?php
 
try {
	//connect to MySQL and select database
	$db = new Database("includes/vars.inc");
	mysql_select_db("test",$db) or die("Cannot select database");
 
	//get details for selected course
	$courseQuery = "SELECT * FROM leaders WHERE ID = " . $_REQUEST['courseID'];
	$courseDetails = mysql_query($courseQuery) or die("Cannot execute details query");
}
 
catch(Exception $e) {
	echo $e->getMessage() . "\n <br /> ";
	exit();
}
 
?>

Open in new window

I am still getting the unexpected T variable" error on phpedit.

after $filename and before $email_address is their suppost to be a semi-colon or something ?

The first script is loading fine and populating the box,  so looks like i just need to fix this error and then i will beable to test.
"http://www.mydomainname.com/uploads/" . $filename
                
 $email_address = mysql_result($courseDetails,0,"email");
 

Open in new window

You're right-- we're missing a semicolon there.  Haha, listen to me saying "we."  Yes, I left out that semicolon.  Add that in after $filename, and you should be good.  I'm an idiot for not looking right there when you told me you had a parse error.
Ok I am getting somwhere i think. I have got rid of that error, and now the file is being uploaded correctly but error messages are appearing also.

Notice: Undefined variable: courseDetails in /var/www/vhosts/numyspace.co.uk/web_users/home/~unn_r031923/public_html/Testing/upload1TEST.php on line 47

Warning: mysql_result(): supplied argument is not a valid MySQL result resource in /var/www/vhosts/numyspace.co.uk/web_users/home/~unn_r031923/public_html/Testing/upload1TEST.php on line 47

Notice: Undefined variable: courseDetails in /var/www/vhosts/numyspace.co.uk/web_users/home/~unn_r031923/public_html/Testing/upload1TEST.php on line 51

Warning: mysql_result(): supplied argument is not a valid MySQL result resource in /var/www/vhosts/numyspace.co.uk/web_users/home/~unn_r031923/public_html/Testing/upload1TEST.php on line 51

my table is definitely leaders and the 3 columns are
 "courseID"       
"course"
"email"

My list box is populating ok, then i search for the document and submit and then it shows a link on the page saying the the document was uploaded successfully, but with those 3 errors underneath.
<?PHP
 
 
 
try {
	//connect to MySQL and select database
	// Connects to your Database
	mysql_connect("localhost", "xx", "xx") or die(mysql_error());
	mysql_select_db("test") or die(mysql_error());
 
	//generate resultset for first visit
	$courseQuery = "SELECT * FROM leaders ORDER BY course ASC";
	$courseResult = mysql_query($courseQuery) or die("Cannot execute list query");
	$numCourses = mysql_numrows($courseResult);
}
catch(Exception $e) {
	echo $e->getMessage() . "\n <br /> ";
	exit();
}
include('header.html');
 
 
echo("<center><h1>Paper Submissions</h1>");
echo("Please rename paper to delegate name. i.e joe_bloggs.pdf");
echo("<br />");
echo("<form action=\"./upload1TEST.php\" method=\"post\" enctype=\"multipart/form-data\"/>");
echo("<label for=\"file\">Select a file:</label>");
echo("<input type=\"file\" name=\"userfile\" id=\"file\"/>");
	//print dropdown select box of courses
echo("<select name='courseID'>");
	for($i=0;$i<$numCourses;$i++) {
echo("<option value='" . mysql_result($courseResult,$i,"ID") . "'>");
echo mysql_result($courseResult,$i,"course");
echo("</option>");
	}
echo ("</select>");
echo ("<button>Upload File</button></center>");
 
 
include('footer.html');
?>

Open in new window


<?PHP
try {
	//connect to MySQL and select database
	// Connects to your Database
	mysql_connect("localhost", "xxx", "xxx") or die(mysql_error());
	mysql_select_db("test") or die(mysql_error());
 
}
catch(Exception $e) {
	echo $e->getMessage() . "\n <br /> ";
	exit();
}
// Configuration - Options
// These will be the types of file that will pass the validation.
	$allowed_filetypes = array('.doc','.txt','.pdf');
// Maximum filesize in BYTES.
	$max_filesize = 2000000;
// The place the files will be uploaded to (currently /uploads/ directory).
    $upload_path = './uploads/';
// Get the name of the file (including file extension).
   	$filename = $_FILES['userfile']['name'];
// Get the extension from the filename.
   	$ext = substr($filename, strpos($filename,'.'), strlen($filename)-1);
 
// Check if the filetype is allowed, if not DIE and inform the Delegate.
   if(!in_array($ext,$allowed_filetypes))
      die('The file you attempted to upload is not allowed.');
 
// Check the filesize, if it is too large then DIE and inform the Delegate.
   if(filesize($_FILES['userfile']['tmp_name']) > $max_filesize)
      die('The file you attempted to upload is too large.');
 
// Check if we can upload to the specified path, if not DIE and inform the Delegate.
   if(!is_writable($upload_path))
      die('You cannot upload to the specified directory, please CHMOD it to 777.');
 
// Upload the file to your specified path.
if(move_uploaded_file($_FILES['userfile']['tmp_name'],$upload_path . $filename)) {
	echo 'Your file upload was successful, view the file <a href="' .
	                $upload_path . $filename . '" title="Your File">here</a>';
 
	$email_message = "A user has just submitted a file for the course " .
	               mysql_result($courseDetails,0,"course") .
	               ".  That file can be downloaded here: " .
	               "http://www.mydomainname.com/uploads/" . $filename;
                
	       $email_address = mysql_result($courseDetails,0,"email");
 
	// mydomainname.com is your domain and joe@mydomainname.com is your email
	ini_set ("sendmail_from","joe@mydomainname.com");
	ini_set("SMTP","mail.mydomainname.com");
	mail($email_address, "joe@mydomainname.com", "New File Upload!", $email_message);
 
	// It worked.
}  else {
	// It failed :(.
	echo 'There was an error during the file upload.  Please try again.';
}
 
?>

Open in new window

Okay, you're missing the code from that last block of code I posted.  Instead of what you put in your last post, it needs to be as below.  Do you see where $courseDetails is assigned a recordset result?  That's what's missing above.

<?PHP<?php
 
try {
	//connect to MySQL and select database
	$db = new Database("includes/vars.inc");
	mysql_select_db("test",$db) or die("Cannot select database");
 
	//get details for selected course
	$courseQuery = "SELECT * FROM leaders WHERE ID = " . $_REQUEST['courseID'];
	$courseDetails = mysql_query($courseQuery) or die("Cannot execute details query");
}
 
catch(Exception $e) {
	echo $e->getMessage() . "\n <br /> ";
	exit();
}
 
?>
 
// Configuration - Options
// These will be the types of file that will pass the validation.
	$allowed_filetypes = array('.doc','.txt','.pdf');
// Maximum filesize in BYTES.
	$max_filesize = 2000000;
// The place the files will be uploaded to (currently /uploads/ directory).
    $upload_path = './uploads/';
// Get the name of the file (including file extension).
   	$filename = $_FILES['userfile']['name'];
// Get the extension from the filename.
   	$ext = substr($filename, strpos($filename,'.'), strlen($filename)-1);
 
// Check if the filetype is allowed, if not DIE and inform the Delegate.
   if(!in_array($ext,$allowed_filetypes))
      die('The file you attempted to upload is not allowed.');
 
// Check the filesize, if it is too large then DIE and inform the Delegate.
   if(filesize($_FILES['userfile']['tmp_name']) > $max_filesize)
      die('The file you attempted to upload is too large.');
 
// Check if we can upload to the specified path, if not DIE and inform the Delegate.
   if(!is_writable($upload_path))
      die('You cannot upload to the specified directory, please CHMOD it to 777.');
 
// Upload the file to your specified path.
if(move_uploaded_file($_FILES['userfile']['tmp_name'],$upload_path . $filename)) {
	echo 'Your file upload was successful, view the file <a href="' .
	                $upload_path . $filename . '" title="Your File">here</a>';
 
	$email_message = "A user has just submitted a file for the course " .
	               mysql_result($courseDetails,0,"course") .
	               ".  That file can be downloaded here: " .
	               "http://www.mydomainname.com/uploads/" . $filename;
                
	       $email_address = mysql_result($courseDetails,0,"email");
 
	// mydomainname.com is your domain and joe@mydomainname.com is your email
	ini_set ("sendmail_from","joe@mydomainname.com");
	ini_set("SMTP","mail.mydomainname.com");
	mail($email_address, "joe@mydomainname.com", "New File Upload!", $email_message);
 
	// It worked.
}  else {
	// It failed :(.
	echo 'There was an error during the file upload.  Please try again.';
}
 
?>

Open in new window

Grrr... See below.  Sorry, typo in last.

<?PHP
 
try {
	//connect to MySQL and select database
	$db = new Database("includes/vars.inc");
	mysql_select_db("test",$db) or die("Cannot select database");
 
	//get details for selected course
	$courseQuery = "SELECT * FROM leaders WHERE ID = " . $_REQUEST['courseID'];
	$courseDetails = mysql_query($courseQuery) or die("Cannot execute details query");
}
 
catch(Exception $e) {
	echo $e->getMessage() . "\n <br /> ";
	exit();
}
 
// Configuration - Options
// These will be the types of file that will pass the validation.
	$allowed_filetypes = array('.doc','.txt','.pdf');
// Maximum filesize in BYTES.
	$max_filesize = 2000000;
// The place the files will be uploaded to (currently /uploads/ directory).
    $upload_path = './uploads/';
// Get the name of the file (including file extension).
   	$filename = $_FILES['userfile']['name'];
// Get the extension from the filename.
   	$ext = substr($filename, strpos($filename,'.'), strlen($filename)-1);
 
// Check if the filetype is allowed, if not DIE and inform the Delegate.
   if(!in_array($ext,$allowed_filetypes))
      die('The file you attempted to upload is not allowed.');
 
// Check the filesize, if it is too large then DIE and inform the Delegate.
   if(filesize($_FILES['userfile']['tmp_name']) > $max_filesize)
      die('The file you attempted to upload is too large.');
 
// Check if we can upload to the specified path, if not DIE and inform the Delegate.
   if(!is_writable($upload_path))
      die('You cannot upload to the specified directory, please CHMOD it to 777.');
 
// Upload the file to your specified path.
if(move_uploaded_file($_FILES['userfile']['tmp_name'],$upload_path . $filename)) {
	echo 'Your file upload was successful, view the file <a href="' .
	                $upload_path . $filename . '" title="Your File">here</a>';
 
	$email_message = "A user has just submitted a file for the course " .
	               mysql_result($courseDetails,0,"course") .
	               ".  That file can be downloaded here: " .
	               "http://www.mydomainname.com/uploads/" . $filename;
                
	       $email_address = mysql_result($courseDetails,0,"email");
 
	// mydomainname.com is your domain and joe@mydomainname.com is your email
	ini_set ("sendmail_from","joe@mydomainname.com");
	ini_set("SMTP","mail.mydomainname.com");
	mail($email_address, "joe@mydomainname.com", "New File Upload!", $email_message);
 
	// It worked.
}  else {
	// It failed :(.
	echo 'There was an error during the file upload.  Please try again.';
}
 
?>

Open in new window

I have changed my code now,  and it is the same as yours other than i am using this for connection below.

Now i am getting the following error

Cannot execute details query

Which is something to do with the SQL query ?


try {
	//connect to MySQL and select database
	// Connects to your Database
	mysql_connect("localhost", "xxx", "xxx") or die(mysql_error());
	mysql_select_db("test") or die(mysql_error());
 
	//get details for selected course
	$courseQuery = "SELECT * FROM leaders WHERE ID = " . $_REQUEST['courseID'];
	$courseDetails = mysql_query($courseQuery) or die("Cannot execute details query");
}

Open in new window

With the code you just posted, add in an echo statement so we can see if there's something wrong with the SQL you're trying to execute.  Let's make sure we're getting good data from that courseID.

try {
	//connect to MySQL and select database
	// Connects to your Database
	mysql_connect("localhost", "xxx", "xxx") or die(mysql_error());
	mysql_select_db("test") or die(mysql_error());
 
	//get details for selected course
	$courseQuery = "SELECT * FROM leaders WHERE ID = " . $_REQUEST['courseID'];
	echo "<p>" . $courseQuery ."<p>";
	$courseDetails = mysql_query($courseQuery) or die("Cannot execute details query");
}

Open in new window

SELECT * FROM leaders WHERE ID =

Cannot execute details query
Yep, you're not getting any data from that drop down menu (listbox).  First thing, load up your initial page and right click to show the source.  Make sure that when your list is populating, it's actually getting values (i.e. make sure each <option> tag has a value in the value attribute).  If it does, run through your entire process, making sure to pick a course that you know the value for.  See what your error message says then.

I've not dealt much with file upload forms, so I'm actually not sure if other form fields (like this courseID listbox) get submitted when the file itself uploads.  You may need to separate that out into a separate step.

<form action="./upload1TEST.php" method="post" enctype="multipart/form-data"/><label for="file">Select a file:</label><input type="file" name="userfile" id="file"/><select name='courseID'><br />
<b>Warning</b>:  mysql_result() [<a href='function.mysql-result'>function.mysql-result</a>]: ID not found in MySQL result index 3 in <b>/public_html/Test/uploadTEST.php</b> on line <b>40</b><br />
 
<option value=''>Paper_Topic_1</option><br />
<b>Warning</b>:  mysql_result() [<a href='function.mysql-result'>function.mysql-result</a>]: ID not found in MySQL result index 3 in <b>/var/www/vhosts/numyspace.co.uk/web_users/home/~unn_r031923/public_html/Testing/uploadTEST.php</b> on line <b>40</b><br />
<option value=''>Paper_Topic_2</option></select><button>Upload File</button>

Open in new window

working now,  ID should be courseID on both pages : )  YaY!

Just need last query on the email.

the line

ini_set("SMTP","mail.mydomainname.com");  

what is this ?    is that like jondoh@hotmail.com ?
Can you post for me all of your code from your initial page?  I think I see the problem, but I don't want to muddy the waters any further! :-)
ASKER CERTIFIED SOLUTION
Avatar of Bobaran98
Bobaran98
Flag of United States of America image

Link to home
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.
See answer
It is now looks like it is working now ID has changed to courseID.

Not sending the email though, I not sure how to configure it though

// mydomainname.com is your domain and joe@mydomainname.com is your email
      ini_set ("sendmail_from","jonblabla@hotmail.com");
      ini_set("SMTP","mail.mydomainname.com");
      mail($email_address, "New Paper Submission", "New File Upload!", $email_message);
<?PHP
 
try {
	//connect to MySQL and select database
	// Connects to your Database
	mysql_connect("localhost", "xxx", "xxx") or die(mysql_error());
	mysql_select_db("test") or die(mysql_error());
 
	//generate resultset for first visit
	$courseQuery = "SELECT * FROM leaders ORDER BY course ASC";
	$courseResult = mysql_query($courseQuery) or die("Cannot execute list query");
	$numCourses = mysql_numrows($courseResult);
}
catch(Exception $e) {
	echo $e->getMessage() . "\n <br /> ";
	exit();
}
include('header.html');
 
 
echo("<center><h1>Paper Submissions</h1>");
echo("Please rename paper to delegate name. i.e joe_bloggs.pdf");
echo("<br />");
echo("<form action=\"./upload1TEST.php\" method=\"post\" enctype=\"multipart/form-data\"/>");
echo("<label for=\"file\">Select a file:</label>");
echo("<input type=\"file\" name=\"userfile\" id=\"file\"/>");
	//print dropdown select box of courses
echo("<select name='courseID'>");
	for($i=0;$i<$numCourses;$i++) {
echo("<option value='" . mysql_result($courseResult,$i,"courseID") . "'>");
echo mysql_result($courseResult,$i,"course");
echo("</option>");
	}
echo ("</select>");
echo ("<button>Upload File</button></center>");
 
 
include('footer.html');
?>

Open in new window

sorry : )  Only just saw your new message.  I will try your suggestions now   Thank You
ini_set("SMTP","smtp.uk.aol.com");   that is my server address  but it is not working
Yeah, there's probably no chance you would be able to send mail from either a hotmail or an aol address.  But try removing both ini_set lines and just using the mail() function with your email address.  It may work, who knows?  Just depends how your server's setup.  If not, try that ini_set("SMTP","localhost");
I have tried all sorts here but cannot send the mail.

I have tried the ini_set("SMTP", "localhost");

Tried it with just the mail() function,

I have echo'd  $email_address  and it is picking out the correct address  just somehow will not send the email.  This is frustrating,  I want to bury my head in the sand : (
May I ask how your website is hosted?  Is it a shared hosting deal-- an account you have with a company where you get X mb of space on their machine?  Or is it on a dedicated server you have direct access to?

Unfortunately, this mailing issue is especially tricky because of all the variables involved, especially now that the web community is cracking down so hard on spammers.
its a university account  http://www.numyspace.co.uk/   I think they pay these for the web hosting ? but i am not sure.