Page 1 of 1

Upload Error

Posted: Sun Jun 12, 2005 12:41 pm
by Addos
Hi,
I wonder if anybody can see what is going wrong with my script. If I use this for uploading to my server it works perfectly:

Code: Select all

<?php
//vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
//   You may change maxsize, and allowable upload file types.
//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
//Maximum file size. You may increase or decrease.
$MAX_SIZE = 10000000;
                            
//Allowable file Mime Types. Add more mime types if you want
//$FILE_MIMES = array('image/jpeg','image/jpg','image/gif','image/png','application/msword','application/zip','application/sit','application/rar','application/txt','application/rtf',);

//Allowable file ext. names. you may add more extension names.            
$FILE_EXTS  = array('.doc'); 
//,'.txt','.zip','.sit','.jpg','.jpeg','.png','.gif','.rtf','.rar'

//Allow file delete? no, if only allow upload only
$DELETABLE  = true;                               


//vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
//   Do not touch the below if you are not confident.
//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
/************************************************************
 *     Setup variables
 ************************************************************/
$site_name = $_SERVER['HTTP_HOST'];
$url_dir = "http://".$_SERVER['HTTP_HOST'].dirname($_SERVER['PHP_SELF']);
$url_this =  "http://".$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF'];

$upload_dir = "files/";
$upload_url = $url_dir."/files/";
$message ="";

/************************************************************
 *     Create Upload Directory
 ************************************************************/
if (!is_dir("files")) {
  if (!mkdir($upload_dir))
  	die ("upload_files directory doesn't exist and creation failed");
  if (!chmod($upload_dir,0755))
  	die ("change permission to 755 failed.");
}

/************************************************************
 *     Process User's Request
 ************************************************************/
if ($_REQUEST[del] && $DELETABLE)  {
  $resource = fopen("log.txt","a");
  fwrite($resource,date("Ymd h:i:s")."DELETE - $_SERVER[REMOTE_ADDR]"."$_REQUEST[del]\n");
  fclose($resource);
  $signals = $_FILES['userfile']['name'];
  

  if (strpos($_REQUEST[del],"/.")>0);                  //possible hacking
  else if (strpos($_REQUEST[del],"files/") === false); //possible hacking
  else if (substr($_REQUEST[del],0,6)=="files/") {
    unlink($_REQUEST[del]);
    print "<script>window.location.href='$url_this?message=File deletion successful.'</script>";
  }
}

else if ($_FILES['userfile']) {
  $resource = fopen("log.txt","a");
  fwrite($resource,date("Ymd h:i:s")."UPLOAD - $_SERVER[REMOTE_ADDR]"
            .$_FILES['userfile']['name']." "
            .$_FILES['userfile']['type']."\n");
  fclose($resource);

  $file_type = $_FILES['userfile']['type']; 
  $file_name = $_FILES['userfile']['name'];
  $file_ext = strtolower(substr($file_name,strrpos($file_name,".")));

  //File Size Check
  if ( $_FILES['userfile']['size'] > $MAX_SIZE) 
     $message = "The file size is over 2MB.";
  //File Type/Extension Check
  else if (!in_array($file_type, $FILE_MIMES) 
          && !in_array($file_ext, $FILE_EXTS) )
     $message = "Sorry, $file_name($file_type) is not allowed to be uploaded.";
      
  else
     $message = do_upload($upload_dir, $upload_url);
  
  print "<script>window.location.href='$url_this?message=$message'</script>";
}
else if (!$_FILES['userfile']);
else 
	$message = "Invalid File Specified.";

/************************************************************
 *     List Files
 ************************************************************/
$handle=opendir($upload_dir);
$filelist = "";
while ($file = readdir($handle)) {
   if(!is_dir($file) && !is_link($file)) {
      $filelist .= "<a href='$upload_dir$file'>".$file."</a>";
      if ($DELETABLE)
      $filelist .= " - <a href='?del=$upload_dir$file' title='delete'> Delete this file?</a>";
      $filelist .= "<sub><small><small><font color=black>  ".date("d-m H:i", filemtime($upload_dir.$file))
                   ."</font></small></small></sub>";
      $filelist .="<br>";
}
}
// Delete on this page returns a url parm of files/signal.doc
// substr() will extract from the position (counting from 0)
// WHERE wordName= %s is replaced with $filename after it has been striped of files/

$relURL = $_GET['del'];
$filename = substr($relURL, 6);

if ((isset($_GET['del'])) && ($_GET['del'] != "")) {
  $deleteSQL = sprintf("DELETE FROM word WHERE wordName='$filename'",
                       GetSQLValueString($_GET['del'], "text"));

  mysql_select_db($database_johnston, $johnston);
  $Result1 = mysql_query($deleteSQL, $johnston) or die(mysql_error());

	}
	function do_upload($upload_dir, $upload_url) {

	$temp_name = $_FILES['userfile']['tmp_name'];
	$file_name = $_FILES['userfile']['name']; 
 	$file_name = str_replace("\\","",$file_name);
  	$file_name = str_replace("'","",$file_name);
	$file_path = $upload_dir.$file_name;

	//File Name Check
  if ( $file_name =="") { 
  	$message = "Invalid File Name Specified";
  	return $message;
  }

  $result  =  move_uploaded_file($temp_name, $file_path);
  if (!chmod($file_path,0755))
   	$message = "change permission to 755 failed.";
  else
    $message = ($result)?"$file_name uploaded successfully." :
     	      "Somthing is wrong with uploading a file.";
  return $message;
}

 ?>
If I use this which has a few extra form validations added it returns the errors:

Warning: fopen(log.txt): failed to open stream: Permission denied in /home/johnston/domains/fergusjohnston.com/public_html/admin_word_update2.php on line 136

Warning: fwrite(): supplied argument is not a valid stream resource in /home/johnston/domains/fergusjohnston.com/public_html/admin_word_update2.php on line 139

Warning: fclose(): supplied argument is not a valid stream resource in /home/johnston/domains/fergusjohnston.com/public_html/admin_word_update2.php on line 140

Warning: in_array(): Wrong datatype for second argument in /home/johnston/domains/fergusjohnston.com/public_html/admin_word_update2.php on line 150

Code: Select all

//vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
//   You may change maxsize, and allowable upload file types.
//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
//Maximum file size. You may increase or decrease.
$MAX_SIZE = 10000000;
                            
//Allowable file Mime Types. Add more mime types if you want
//$FILE_MIMES = array('image/jpeg','image/jpg','image/gif','image/png','application/msword','application/zip','application/sit','application/rar','application/txt','application/rtf',);

//Allowable file ext. names. you may add more extension names.            
$FILE_EXTS  = array('.doc'); 
//,'.txt','.zip','.sit','.jpg','.jpeg','.png','.gif','.rtf','.rar'

//Allow file delete? no, if only allow upload only
$DELETABLE  = true;                               


//vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
//   Do not touch the below if you are not confident.
//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
/************************************************************
 *     Setup variables
 ************************************************************/
$site_name = $_SERVER['HTTP_HOST'];
$url_dir = "http://".$_SERVER['HTTP_HOST'].dirname($_SERVER['PHP_SELF']);
$url_this =  "http://".$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF'];

$upload_dir = "files/";
$upload_url = $url_dir."/files/";
$message ="";

/************************************************************
 *     Create Upload Directory
 ************************************************************/
if (!is_dir("files")) {
  if (!mkdir($upload_dir))
  	die ("upload_files directory doesn't exist and creation failed");
  if (!chmod($upload_dir,0755))
  	die ("change permission to 755 failed.");
}

/************************************************************
 *     Process User's Request
 ************************************************************/
if ($_REQUEST[del] && $DELETABLE)  {
  $resource = fopen("log.txt","a");
  fwrite($resource,date("Ymd h:i:s")."DELETE - $_SERVER[REMOTE_ADDR]"."$_REQUEST[del]\n");
  fclose($resource);
    

  if (strpos($_REQUEST[del],"/.")>0);                  //possible hacking
  else if (strpos($_REQUEST[del],"files/") === false); //possible hacking
  else if (substr($_REQUEST[del],0,6)=="files/") {
    unlink($_REQUEST[del]);
    print "<script>window.location.href='$url_this?message=File deletion successful.'</script>";
  }
}

else if ($_FILES['userfile']) {
  $resource = fopen("log.txt","a");
  fwrite($resource,date("Ymd h:i:s")."UPLOAD - $_SERVER[REMOTE_ADDR]"
            .$_FILES['userfile']['name']." "
            .$_FILES['userfile']['type']."\n");
  fclose($resource);

  $file_type = $_FILES['userfile']['type']; 
  $file_name = $_FILES['userfile']['name'];
  $file_ext = strtolower(substr($file_name,strrpos($file_name,".")));

  //File Size Check
  if ( $_FILES['userfile']['size'] > $MAX_SIZE) 
     $message = "The file size is over 2MB.";
  //File Type/Extension Check
  else if (!in_array($file_type, $FILE_MIMES) 
          && !in_array($file_ext, $FILE_EXTS) )
     $message = "Sorry, $file_name($file_type) is not allowed to be uploaded.";
     
  else
     $message = do_upload($upload_dir, $upload_url);
	 
    print "<script>window.location.href='$url_this?message=$message'</script>";
}
else if (!$_FILES['userfile']);
else 
	$message = "Invalid File Specified.";

/************************************************************
 *     List Files
 ************************************************************/
$handle=opendir($upload_dir);
$filelist = "";
while ($file = readdir($handle)) {
   if(!is_dir($file) && !is_link($file)) {
      $filelist .= "<a href='$upload_dir$file'>".$file."</a>";
      if ($DELETABLE)
      $filelist .= " - <a href='?del=$upload_dir$file' title='delete'> Delete this file?</a>";
      $filelist .= "<sub><small><small><font color=black>  ".date("d-m H:i", filemtime($upload_dir.$file))
                   ."</font></small></small></sub>";
      $filelist .="<br>";
}
}
// Delete on this page returns a url parm of files/signal.doc for example
// substr() will extract from the position (counting from 0) and strip files from files/signal.doc
// WHERE wordName= %s is replaced with $filename after it has been striped of files/

$relURL = $_GET['del'];
$filename = substr($relURL, 6);

if ((isset($_GET['del'])) && ($_GET['del'] != "")) {
  $deleteSQL = sprintf("DELETE FROM word WHERE wordName='$filename'",
                       GetSQLValueString($_GET['del'], "text"));

  mysql_select_db($database_johnston, $johnston);
  $Result1 = mysql_query($deleteSQL, $johnston) or die(mysql_error());

}
	function do_upload($upload_dir, $upload_url) {
	
	// If the upload form field is filled out but the wordDetails is empty, 
	// then stop a null value from the blank field being passed to the database otherwise proceed
	if (isset($_POST['wordDetails']) && !empty($_POST['wordDetails'])) {
	
	$temp_name = $_FILES['userfile']['tmp_name'];
	$file_name = $_FILES['userfile']['name']; 
 	$file_name = str_replace("\\","",$file_name);
  	$file_name = str_replace("'","",$file_name);
	$file_path = $upload_dir.$file_name;
	//$wordDetails here added by Brian
	$wordDetails= $_POST['wordDetails'];
    //proceed with insert into db once all tests are passed.
    $insertSQL = sprintf("INSERT INTO word (wordName, wordDetails) VALUES (%s, %s)",
                       GetSQLValueString($_FILES['userfile']['name'], "text"),
                       GetSQLValueString($_POST['wordDetails'], "text"));

   mysql_select_db($database_johnston, $johnston);
   $Result1 = mysql_query($insertSQL, $johnston) or die(mysql_error());
}
 
   //If wordDetails empty check
  if ( $wordDetails =="") { 
   	$message = "Programme Note title missing";
  	return $message;
	 }
	//File Name Check
  if ( $file_name =="") { 
   	$message = "Invalid File Name Specified";
  	return $message;
	 }

  $result  =  move_uploaded_file($temp_name, $file_path);
  if (!chmod($file_path,0755))
   	$message = "change permission to 755 failed.";
  else
    $message = ($result)?"$file_name uploaded successfully." :
     	      "Something is wrong with uploading a file.";
  return $message;
}
?>
What is frustrating me is that this bit of script works perfectly when testing locally but it is only when I try to run it from the live site I get these errors.
If anybody has the patience to read through and see what’s going wrong I’d be most grateful. Most of this code I have tried to adapt myself and I’m not afraid to admit that I’m drowning here in stuff that’s beyond my full understanding.
Sincere thanks for any advice
Brian

This is my Form just in case it’s relevant.

Code: Select all

&lt;form name=&quote;upload&quote; id=&quote;upload&quote; ENCTYPE=&quote;multipart/form-data&quote; method=&quote;post&quote;action=&quote;&lt;?php echo $editFormAction; ?&gt;&quote;&gt;
  &lt;p&gt;&lt;strong&gt;Your Uploaded Files so far are: &lt;/strong&gt;&lt;/p&gt;
   &lt;?=$filelist?&gt;
          &lt;p&gt;&amp;nbsp;&lt;/p&gt;
          &lt;table align=&quote;center&quote;&gt;
	    &lt;tr valign=&quote;baseline&quote;&gt;
          &lt;td nowrap align=&quote;right&quote;&gt;Upload Word file: &lt;/td&gt;
          &lt;td&gt;&lt;input type=&quote;file&quote; id=&quote;userfile&quote; name=&quote;userfile&quote; &gt;&lt;/td&gt;
        &lt;/tr&gt;
        &lt;tr valign=&quote;baseline&quote;&gt;
          &lt;td nowrap align=&quote;right&quote;&gt;Programme Note title:
		  &lt;/td&gt;
          &lt;td&gt;&lt;input type=&quote;text&quote; name=&quote;wordDetails&quote; id =&quote;wordDetails&quote; value=&quote;&quote; size=&quote;32&quote; &gt;&lt;/td&gt;
        &lt;/tr&gt;
      
        &lt;tr valign=&quote;baseline&quote;&gt;
          &lt;td nowrap align=&quote;right&quote;&gt;&amp;nbsp;&lt;/td&gt;
          &lt;td&gt;&lt;input type=&quote;submit&quote; name=&quote;upload&quote; value=&quote;Insert record&quote;&gt;&lt;/td&gt;
        &lt;/tr&gt;
      &lt;/table&gt;
      &lt;input type=&quote;hidden&quote; name=&quote;upload&quote; value=&quote;form1&quote;&gt;
  &lt;/form&gt;

Posted: Sun Jun 12, 2005 12:51 pm
by andylyon87
not to sound patronising but is the chmod of the file correct, cos I always forget to chmod and it always ends up being that.

Posted: Sun Jun 12, 2005 1:13 pm
by Addos
Hi,
Thanks for your quick response. I can assure you, you can patronise me all you need as I’m really really grateful for any help.
I have to say that I really don’t understand the chmod thingy (yet) and I haven’t changed it in the second bit of code from the first bit I posted which worked perfectly. But! You gave me the idea to set this in my PHP page to the same one I had to set on the server (777) and now it works a treat. Maybe this is something standard that I should have known i.e. that both should match but as I say I’m struggling to keep up with this but hopefully you have given me the next bit of the jigsaw!
Should I have set these two to match?
Thanks a mil
Brian
:wink:

Posted: Sun Jun 12, 2005 1:37 pm
by Addos
Opps! I just realised that I was testing this from the wrong form page and in fact this problem is still there sorry. :cry:

I thought that this problem was sorted but I still get the same error as posted even though I changed the chmod setting on my PHP page to match that on the server.
Any further ideas would be really welcome.
Thanks again
Brian

Posted: Mon Jun 13, 2005 2:43 am
by ol4pr0
Something i use to upload files. haven't had any problems jet.

Code: Select all

if (isset($_FILES['!!NAME']['name'])) $file_name = $_FILES['!!NAME']['name'];
		else $file_name = "";
	if (isset($_FILES['!!NAME']['size'])) $file_size = $_FILES['!!NAME'];
		else $file_size = "";
	if (isset($_FILES['!!NAME']['tmp_name'])) $file_tmp = $_FILES['!!NAME']['tmp_name'];
		else $file_tmp = "";
    function getextension($filename)
    {
    $filename 	= strtolower($filename);
	$extension 	= split("[/\\.]", $filename);
	$n 		= count($extension)-1;
	$extension 	= $extension[$n];
	return $extension;
    }

	$file_type 	= getextension($file_name);

   	if( $file_type!="doc"){
	echo 'Extención .doc)';
    die;
	}
    $MaxSize1000 = $MaxSize*1000;

	if($file_size > $MaxSize1000)
	{
	echo 'Tamaño '.$MaxSize*1000;
    die;
	}
	$time = time();
	$dir = date("mY", $time);
	if (!is_dir($int_path.'/!! DIRECTORY/'.$dir))
	{
	umask(0);
	mkdir ("!! DIRECTORY/".$dir, 0777);
	}
	$fileb = date("dHis", $time);
	$filee = trim(rand(0, 999));
	$fn = trim($fileb."-".$filee);
	$doc = trim("/!! DIRECTORY!!/".$dir."/".$fn.".doc");
	$intdoc = trim($dir."/".$fn.".doc");


	if (is_uploaded_file($_FILES['!!NAME']['tmp_name']))
	{
	copy($_FILES['!!NAME']['tmp_name'], $int_path."/!! DIRECTORY !!/"$intdoc);
#or use move_uploaded
	}
Ofcourse this creates a new dir foreach new month so you might want to change that, also the files are being renamed. Above example is used to have the location stored in a DB.

For example this will create the follwing if the upload dir = files.
/www/files/062005/+FILENAME.doc

This works on UNIX and WINDOWS

Posted: Tue Jun 14, 2005 1:05 pm
by Addos
Hi,
As a real beginner I’m really stuck with a problem and I’ve been at this for days trying to get this sorted but I just have to recall for more help.
Basically I have a form where I can upload .doc’s only to the server. I have a good few conditional statements on the page and they all work fine when checking for any incorrect uploads such as images or anything that is not a .doc. The problem arises when in fact the correct file passes all the validation and goes on to upload and here is where I get the following errors.


Warning: fopen(log.txt): failed to open stream: Permission denied in /home/johnston/domains/fergusjohnston.com/public_html/admin_word_update5.php on line 93
Warning: fwrite(): supplied argument is not a valid stream resource in /home/johnston/domains/fergusjohnston.com/public_html/admin_word_update5.php on line 96
Warning: fclose(): supplied argument is not a valid stream resource in /home/johnston/domains/fergusjohnston.com/public_html/admin_word_update5.php on line 97
Warning: in_array(): Wrong datatype for second argument in /home/johnston/domains/fergusjohnston.com/public_html/admin_word_update5.php on line 107
Warning: mysql_select_db(): supplied argument is not a valid MySQL-Link resource in /home/johnston/domains/fergusjohnston.com/public_html/admin_word_update5.php on line 168
Warning: mysql_query(): supplied argument is not a valid MySQL-Link resource in /home/johnston/domains/fergusjohnston.com/public_html/admin_word_update5.php on line 169


If I remove the validation including the insert function from this:

Code: Select all

if (isset($_POST['wordDetails']) && !empty($_POST['wordDetails'])) { 
    $temp_name = $_FILES['userfile']['tmp_name']; 
    $file_name = $_FILES['userfile']['name']; 
    $file_name = str_replace("\\","",$file_name); 
    $file_name = str_replace("'","",$file_name); 
    $file_path = $upload_dir.$file_name; 
    //$wordDetails here added by Brian 
   
    //proceed with insert into db once all tests are passed. 
    $insertSQL = sprintf("INSERT INTO word (wordName, wordDetails) VALUES (%s, %s)", 
                       GetSQLValueString($_FILES['userfile']['name'], "text"), 
                       GetSQLValueString($_POST['wordDetails'], "text")); 
  
   mysql_select_db($database_johnston, $johnston); 
   $Result1 = mysql_query($insertSQL, $johnston) or die(mysql_error()); 
}
To this:

Code: Select all

$temp_name = $_FILES['userfile']['tmp_name']; 
    $file_name = $_FILES['userfile']['name']; 
    $file_name = str_replace("\\","",$file_name); 
    $file_name = str_replace("'","",$file_name); 
    $file_path = $upload_dir.$file_name;
It will upload ok but obviously the validation has gone out the window!

Now what’s really frustrating me to death is that if I test this locally and that’s including all the validation it works perfectly with no errors at all but it’s only when I upload this to the server it throws a wobbly.

I have tried moving my conditional statement and tried re scripting the validation to other places and I’ll refrain from posting any more code at this time to show my many attempts but if anybody can tell me why the errors are happening on the live server and not locally and more importantly how to resolve it, I’d be most thankful.

This is the entire page that throws these errors on the server but not as I say locally. Roughly from line 150 below is where I think my problem starts.
Thanks very much for any help at all.
Brian

Code: Select all

<?PHP
 function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "") 
{
  $theValue = (!get_magic_quotes_gpc()) ? addslashes($theValue) : $theValue;

  switch ($theType) {
    case "text":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;    
    case "long":
    case "int":
      $theValue = ($theValue != "") ? intval($theValue) : "NULL";
      break;
    case "double":
      $theValue = ($theValue != "") ? "'" . doubleval($theValue) . "'" : "NULL";
      break;
    case "date":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;
    case "defined":
      $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;
      break;
  }
  return $theValue;
}

$editFormAction = $_SERVER['PHP_SELF'];
if (isset($_SERVER['QUERY_STRING'])) {
  $editFormAction .= "?" . htmlentities($_SERVER['QUERY_STRING']);
}
	
//vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv 
//   You may change maxsize, and allowable upload file types. 
//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 
//Maximum file size. You may increase or decrease. 
$MAX_SIZE = 10000000; 
                            
//Allowable file Mime Types. Add more mime types if you want 
//$FILE_MIMES = array('image/jpeg','image/jpg','image/gif','image/png','application/msword','application/zip','application/sit','application/rar','application/txt','application/rtf',); 
  
//Allowable file ext. names. you may add more extension names.            
$FILE_EXTS  = array('.doc'); 
//,'.txt','.zip','.sit','.jpg','.jpeg','.png','.gif','.rtf','.rar' 
  
//Allow file delete? no, if only allow upload only 
$DELETABLE  = true;                                
  
  
//vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv 
//   Do not touch the below if you are not confident. 
//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 
/************************************************************ 
 *     Setup variables 
 ************************************************************/ 
$site_name = $_SERVER['HTTP_HOST']; 
$url_dir = "http://".$_SERVER['HTTP_HOST'].dirname($_SERVER['PHP_SELF']); 
$url_this =  "http://".$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF']; 
  
$upload_dir = "files/"; 
$upload_url = $url_dir."/files/"; 
$message =""; 
  
/************************************************************ 
 *     Create Upload Directory 
 ************************************************************/ 
if (!is_dir("files")) { 
  if (!mkdir($upload_dir)) 
      die ("upload_files directory doesn't exist and creation failed"); 
  if (!chmod($upload_dir,0755)) 
      die ("change permission to 755 failed."); 
} 
  
/************************************************************ 
 *     Process User's Request 
 ************************************************************/ 
if ($_REQUEST[del] && $DELETABLE)  { 
  $resource = fopen("log.txt","a"); 
  fwrite($resource,date("Ymd h:i:s")."DELETE - $_SERVER[REMOTE_ADDR]"."$_REQUEST[del]\n"); 
  fclose($resource); 
    
  
  if (strpos($_REQUEST[del],"/.")>0);                  //possible hacking 
  else if (strpos($_REQUEST[del],"files/") === false); //possible hacking 
  else if (substr($_REQUEST[del],0,6)=="files/") { 
    unlink($_REQUEST[del]); 
    print "<script>window.location.href='$url_this?message=File deletion successful.'</script>"; 
  } 
} 
  
else if ($_FILES['userfile']) { 
  $resource = fopen("log.txt","a"); 
  fwrite($resource,date("Ymd h:i:s")."UPLOAD - $_SERVER[REMOTE_ADDR]" 
            .$_FILES['userfile']['name']." " 
            .$_FILES['userfile']['type']."\n"); 
  fclose($resource); 
  
  $file_type = $_FILES['userfile']['type']; 
  $file_name = $_FILES['userfile']['name']; 
  $file_ext = strtolower(substr($file_name,strrpos($file_name,"."))); 
  
  //File Size Check 
  if ( $_FILES['userfile']['size'] > $MAX_SIZE) 
     $message = "The file size is over 2MB."; 
  //File Type/Extension Check 
  else if (!in_array($file_type, $FILE_MIMES) 
          && !in_array($file_ext, $FILE_EXTS) ) 
     $message = "Sorry, $file_name($file_type) is not allowed to be uploaded."; 
      
  else 
     $message = do_upload($upload_dir, $upload_url); 
      
    print "<script>window.location.href='$url_this?message=$message'</script>"; 
} 
else if (!$_FILES['userfile']); 
else 
    $message = "Invalid File Specified."; 
  
/************************************************************ 
 *     List Files 
 ************************************************************/ 
$handle=opendir($upload_dir); 
$filelist = ""; 
while ($file = readdir($handle)) { 
   if(!is_dir($file) && !is_link($file)) { 
      $filelist .= "<a href='$upload_dir$file'>".$file."</a>"; 
      if ($DELETABLE) 
      $filelist .= " - <a href='?del=$upload_dir$file' title='delete'> Delete this file?</a>"; 
      $filelist .= "<sub><small><small><font color=black>  ".date("d-m H:i", filemtime($upload_dir.$file)) 
                   ."</font></small></small></sub>"; 
      $filelist .="<br>"; 
} 
} 
// Delete on this page returns a url parm of files/signal.doc for example 
// substr() will extract from the position (counting from 0) and strip files from files/signal.doc 
// WHERE wordName= %s is replaced with $filename after it has been striped of files/ 
  
$relURL = $_GET['del']; 
$filename = substr($relURL, 6); 
  
if ((isset($_GET['del'])) && ($_GET['del'] != "")) { 
  $deleteSQL = sprintf("DELETE FROM word WHERE wordName='$filename'", 
                       GetSQLValueString($_GET['del'], "text")); 
  
  mysql_select_db($database_johnston, $johnston); 
  $Result1 = mysql_query($deleteSQL, $johnston) or die(mysql_error()); 
  
} 
    function do_upload($upload_dir, $upload_url) { 
    
    // If the upload form field is filled out but the wordDetails is empty, 
    // then stop a null value from the blank field being passed to the database otherwise proceed 
    //if (isset($_POST['wordDetails']) && !empty($_POST['wordDetails'])) { 
    $temp_name = $_FILES['userfile']['tmp_name']; 
    $file_name = $_FILES['userfile']['name']; 
    $file_name = str_replace("\\","",$file_name); 
    $file_name = str_replace("'","",$file_name); 
    $file_path = $upload_dir.$file_name; 
    //$wordDetails here added by Brian 
   
    //proceed with insert into db once all tests are passed. 
    $insertSQL = sprintf("INSERT INTO word (wordName, wordDetails) VALUES (%s, %s)", 
                       GetSQLValueString($_FILES['userfile']['name'], "text"), 
                       GetSQLValueString($_POST['wordDetails'], "text")); 
  
   mysql_select_db($database_johnston, $johnston); 
   $Result1 = mysql_query($insertSQL, $johnston) or die(mysql_error()); 
//} 
   $wordDetails= $_POST['wordDetails']; 
   //If wordDetails empty check 
  if ( $wordDetails =="") { 
       $message = "Programme Note title missing"; 
      return $message; 
     } 
    //File Name Check 
  if ( $file_name =="") { 
       $message = "Invalid File Name Specified"; 
      return $message; 
     } 
  
  $result  =  move_uploaded_file($temp_name, $file_path); 
  if (!chmod($file_path,0755)) 
       $message = "change permission to 755 failed."; 
  else 
    $message = ($result)?"$file_name uploaded successfully." : 
               "Something is wrong with uploading a file."; 
  return $message; 
} 
?>