Page 1 of 1

ftp upload via php script?

Posted: Wed May 12, 2010 4:45 pm
by deiman
Hello, i try to put ftp function on upload form for joomla. Php code is that

Code: Select all

<?php


	defined ('_VALID_MOS') or die('Direct Access to this location is not allowed.');

		# Variabili
	define( '_base_A' , $mosConfig_absolute_path . '/administrator/components/com_ftpsystem/');
	define( '_base_W' , $mosConfig_absolute_path . '/components/com_ftpsystem/');
	
	
	require_once(_base_A . "/config.ftpsystem.php");
	require_once(_base_A . "/class.ftpsystem.php");
	
	$gallerypath = $mosConfig_live_site . "/components/com_ftpsystem";
	
		# Trova il file lingua se esistente
	if (file_exists($mosConfig_absolute_path . '/components/com_ftpsystem/language/' . $mosConfig_lang . '.php')) {
		include($mosConfig_absolute_path . '/components/com_ftpsystem/language/' . $mosConfig_lang . '.php');
	} else {
		include($mosConfig_absolute_path . '/components/com_ftpsystem/language/english.php');
	}
		# definisci i permessi
	$is_editor = (strtolower($my->usertype) == 'editor' || strtolower($my->usertype) == 'administrator' || strtolower($my->usertype) == 'super administrator');
	$is_user = (strtolower($my->usertype) <> '');
	
	$uid = intval(mosGetParam($_REQUEST, "uid", 0));
	

	if ($my->id==0)
		mosRedirect(sefRelToAbs("index.php?option=com_user&view=login&Itemid=$Itemid",  ''));

	//////////////////////////////////////////////////
	#to avoid RG emulation off problems
	//////////////////////////////////////////////////
	$id 	= mosGetParam($_REQUEST,"id", '');
	$catid 	= mosGetParam($_REQUEST,"catid", ''); 
	$func 	= mosGetParam($_REQUEST,"func",'');
	$Itemid	= mosGetParam($_REQUEST,"Itemid",'');
	//////////////////////////////////////////////////
	
	switch (@$func) 
	{
		case 'ftpupload': //add;
			ftpupload_edit(0);
			$event = "'js_fnadd();'" ;
			echo "<script> window.onload=function(){js_fnadd();}</script>";
			break;
			
		case 'edit':
			ftpupload_edit($id);
			$event = "'js_fnedit();'" ;
			echo "<script> window.onload=function(){js_fnedit();}</script>";
			break;
			
		case 'delete':
			ftpupload_delete($id);
			break;
			
		case 'save':
			insertftpsystem($id);
			break;
			
		case 'download':
			$file = mosGetParam($_REQUEST,"file",'');
			download($file);
			break;
				
		case 'ftpuploadlist':
			ftpuploadlist();
			break;
			
		case 'help':
			showhelptext();
			break;
		
		default:
			ftpuploadlist();
			break;
	}
 
	function insertftpsystem($id)
	{
		global $database;
		
		//$hidIsFilePath1 = 0;
		$hidIsFilePath 	= $_REQUEST['hidIsFilePath'];
	/*	if ( $id != '' && $id !=0)
		{
			if ($hidIsFilePath ==0)
			  $hidIsFilePath1 = 1; // in edit already have file path
		}		*/
		
		$name        	= $_REQUEST['name'];
		$description 	= $_REQUEST['description'];
		
		// get current userid & username from user table. 
		$user =& JFactory::getUser();
		$userid		= $user->get('id');
		$username 	= $user->get('username');
		
		$sFileDir 	= $mosConfig_absolute_path .'uploads/'.$username ;//$mosConfig_absolute_path 

		if ($hidIsFilePath == 0)
		{
			$sFilename 	=  $_FILES["upfile1"]["name"];
			$sFileType 	=  $_FILES["upfile1"]["type"];
			$sFileSize  =  $_FILES["upfile1"]["size"];
			$sFileTempPath  =  $_FILES["upfile1"]["tmp_name"];
		
			recursive_mkdir($sFileDir);
			$sFilePath = $sFileDir .'/'.$sFilename;

			if ($sFileTempPath)
			{
				$result = copy ($sFileTempPath, $sFilePath );
				//$result1  = move_uploaded_file($sFileTempPath,$sFilePath );
			}
			$path = $username .'/'. $sFilename ;
			
			$updateFileQry = ",filepath='" . $path . "', ".
				   " size='" . $sFileSize . "'";
		}
		else
		{
			$updateFileQry='';
		}
	//	echo $id;
		if ($id == '' || $id == 0 )
		{
			$sql = "INSERT INTO #__upload " .
				   "(name,description,filepath,size,modifieddate,userid,published,ordering)" . 
				   " VALUES ('" . $name . "','" . $description . "','" . $path . "','" . $sFileSize . "',NOW(),'". $userid."','1','1')"; 
		}
		else
		{
			$sql = "UPDATE #__upload " .
				   " SET name='" . $name . "',description='" . $description . "' ".$updateFileQry." ,modifieddate=NOW(),userid='". $userid."' WHERE id=" . $id; 
		}
//echo $sql;
		$database->setQuery($sql);
		$database->query();
		mosRedirect(sefRelToAbs("index.php?option=com_ftpsystem&Itemid=$Itemid",  ''));
		
	}

	function recursive_mkdir( $folder )
	{
		$folder = preg_split( "/[\\\\\/]/" , $folder );
		
		$mkfolder = '';
		for(  $i=0 ; isset( $folder[$i] ) ; $i++ )
		{
			if(!strlen(trim($folder[$i])))continue;
			$mkfolder .= $folder[$i];
			if( !is_dir( $mkfolder ) ){
				mkdir( "$mkfolder" ,  0777);
			}
			$mkfolder .= DIRECTORY_SEPARATOR;
		}
	}
	
	function download($file)
	{
		$filepath = 'uploads/'.$file;
		if(file_exists($filepath))
		{
			set_time_limit(0);	
			output_file($filepath,$filepath, 'text/plain');
		}
		else
		{
			echo 'File not exists.';
		}
	}
	
	function ftpupload_delete($id)
	{
		global $database; 
		$sql = "DELETE FROM #__upload WHERE id=$id";
		$database->setQuery($sql);
		$database->query();
		mosRedirect(sefRelToAbs("index.php?option=com_ftpsystem&Itemid=$Itemid",  ''));
	}
	?>
<?php 

////Super Administrator
	function ftpuploadlist()
	{
		global $database;
?>
  

<tr>
 <td height="40" align="left" valign="middle"><span style="font-family:Arial, Helvetica, sans-serif;font-size:20PX; color:#135BAD">Файлът е качен успешно.До няколко часа ще бъде публикуван</span></td
  </tr>
      
              <?php
			  
			  // get current userid & username from user table. 
				$cur_user =& JFactory::getUser();
				$current_userid		= $cur_user->get('id');
				$current_username 	= $cur_user->get('username');
				$current_usertype 	= $cur_user->usertype;//Super Administrator
			//-- end Current User Getting 
		
		
			  	// get type (upload user type ) from fileuploadtype table
				$database->setQuery( "SELECT type FROM #__fileuploadtype" );
				$sType = $database->loadResult();
		
				$query1 = " SELECT fu.id, fu.name, fu.description, DATE_FORMAT(fu.modifieddate,'%d-%m-%Y' ) as modDate, " . 
						  " fu.filepath, fu.size,u.id as userid,u.username,u.usertype ".
						  " FROM #__upload fu  " .
						  " LEFT JOIN #__users u ON u.id = fu.userid WHERE published='1' ";
				if ($sType == 1 )//&& $current_usertype != 'Super Administrator' )
					$query1 = $query1. " AND fu.userid = '".$current_userid ."'";
				
				$database->setQuery($query1);
				$rows = $database->Query();
				$num_rows = mysql_num_rows($rows) ;
				$k = 0;
	
			if ($num_rows) {
				for ($row_count = 0; $row_count < $num_rows; $row_count++) 
				{
					$k = 1 - $k;
					$id 			= mysql_result($rows,$row_count,'id');
					$name 			= mysql_result($rows,$row_count,'name');
					$description 	= mysql_result($rows,$row_count,'description');
					$date 			= mysql_result($rows,$row_count,'modDate');
					$size 			= mysql_result($rows,$row_count,'size');
					$filepath		= mysql_result($rows,$row_count,'filepath');
					$uploaded_username		= mysql_result($rows,$row_count,'username');
					$uploaded_usertype		= mysql_result($rows,$row_count,'usertype');
					$uploaded_userid		= mysql_result($rows,$row_count,'userid');
					
					$IsEdit = 0;
					if ($sType == 2)
					{
						if ( $uploaded_userid == $current_userid || $current_usertype == 'Super Administrator' )
						{
							$IsEdit = 1;
						}
					}
					else
					{
						$IsEdit = 1;
					}
				if($row_count >0){
				?>
				<tr><td colspan="6" height="1" bgcolor="#EFEFEF"></td></tr>
				<?PHP } ?>
				  <tr class="row<?php echo $k; ?>">
					>
					
					<?php if ( $IsEdit == 1) { ?>
					<a href="<?php echo sefRelToAbs("index.php?option=com_ftpsystem&func=edit&id=$id&Itemid=$Itemid");?>"><img src="components/com_ftpsystem/images/edit.gif" border="0" alt="Edit" /></a><?php }; ?>&nbsp;</td>
					
              <?PHP 
				}
	
		   }
		   else
		   {
		   		
		   }
			?>
          
<?php
}
?>

<?php 
	function ftpupload_edit($uploadid)
	{
		global $database;
		
	//	echo $uploadid;
		$hidIsFilePath = 0;
		if ($uploadid !='' && $uploadid != 0)
		{
			$query1 = "SELECT * FROM #__upload WHERE id=".$uploadid;
			//echo $query1;
			$database->setQuery($query1);
			//$rows   = $database->loadObjectList();
			$rows = $database->Query();
			$row_count=0;
			$num_rows = mysql_num_rows($rows) ;
			
			$name = '';
			$description = '';
			$filepath = '';
			
			if ($num_rows) 
			{
				$id 			= mysql_result($rows,$row_count,'id');
				$name 			= mysql_result($rows,$row_count,'name');
				$description 	= mysql_result($rows,$row_count,'description');
				$filepath 		= mysql_result($rows,$row_count,'filepath');
			}
			$hidIsFilePath =1;			
		}
?>
<?php
/**
 * FTP upload script using PHP's FTP functions
 *
 * @package tpc_tutorials
 * @version 0.1 20090312T202200-05:00
 * @author  Chris Strosser
 * @link    http://dev.thatspoppycock.com/index.php/Uploading_Files_Using_PHP%27s_FTP_Functions
 */
 
// FTP server details
$ftp_server   = '127.0.0.1';
$ftp_user     = 'deiman';
$ftp_password = '123456';
 
// Connect to FTP server
$ftp = ftp_connect($ftp_server);
 
// Login and open an FTP session
$ftp_result = ftp_login($ftp, $ftp_user, $ftp_password);
 
// Check FTP connection and login status
if ((!$ftp) || (!$ftp_result)) {
    exit("Error connecting to <em>$ftp_server</em> as <em>$ftp_user</em>.");
} else {
    echo "Connected to $ftp_servern";
}
 
// Enable passive mode
ftp_pasv($ftp, true);
 
// Upload a binary file (images, programs, etc.)
if (ftp_put($ftp, $remote_file, $local_file, FTP_BINARY)) {
    echo "Successfully uploaded $local_filen";
} else {
    echo "Error uploading $local_filen";
}
 
// Upload a plain text file
if (ftp_put($ftp, $remote_file, $local_file, FTP_ASCII)) {
    echo "Successfully uploaded $local_filen";
} else {
    echo "Error uploading $local_filen";
}
 
// Close connection
ftp_close($ftp);
?>


<form action="<?php echo sefRelToAbs("index.php?option=com_ftpsystem&func=save&id=$uploadid&Itemid=$Itemid");?>" enctype="multipart/form-data" method="post">
<table  border="0"  cellspacing="0" cellpadding="0">
<tr>
    <td height="40" align="left" valign="middle"><span style="font-family:Arial, Helvetica, sans-serif;font-size:20PX; color:#135BAD">Качи урок</span></td>
  </tr>
      <tr>
        <td height="50" class="main3"><a href="<?php echo sefRelToAbs("index.php?option=com_ftpsystem&func=ftpuploadlist&Itemid=$Itemid");?>" id=""</a>&nbsp;|&nbsp;<a style="color:#000000;font-weight:bold;" href="<?php echo sefRelToAbs("index.php?option=com_ftpsystem&func=ftpupload&Itemid=$Itemid&id=0");?>">Качване на урок</a>&nbsp;|&nbsp;<a href="<?php echo sefRelToAbs("index.php?option=com_ftpsystem&func=help&Itemid=$Itemid");?>" class="atext" >Условия за качване</a> </td>
      </tr>
      <tr>
        <td>
		<table width="720" border="0" align="center"  cellpadding="0" cellspacing="0" >
          <tr>
            <td><table width="100%">
              <tr>
                <td>Име на урока :</td>
                <td><input name="name" type="text" id="name" value="<?php echo $name; ?>" style="width:250px" /></td>
              </tr>
              <tr>
                <td>Описание на урока :</td>
                <td><textarea name="description" rows="6" id="description" style="width:250px" value="<?php echo $description; ?>"><?php echo $description; ?></textarea></td>
              </tr>
              <tr id='trfile1' >
                <td>Файл (за предпочитане не-конвертиран) :</td>
                <td><input type="file" name="upfile1" id="upfile1" style="width:250px"/>
                  <a id="cancel" href="#";  onclick="js_fncancel();" 
              </tr>
              <tr id='trfile2' >
               
                <td><table  border="0">
                    <tr >
                      <td ><?php echo $filepath; ?></td>

                      <td><a href="<?php echo sefRelToAbs("index.php?option=com_ftpsystem&func=download&Itemid=$Itemid&file=$filepath");?>" #"; 
                    </tr>
                </table></td>
              </tr>
              <tr>
                <td height="26" colspan="2"><input type="hidden" id="hidIsFilePath" name="hidIsFilePath" value="<?php echo $hidIsFilePath; ?>"/>
                  <input type="submit" name="upload" id="upload" value="Качи" onclick="return validation();" />Благодарим ви!</td>
				  
                </tr>
            </table></td>
          </tr>
        </table></td>
      </tr>
  </table>

  

<script type="text/javascript" language="javascript">
<!--

	function validation()
	{
		var name 			= document.getElementById('name');
		var description1 	= document.forms[0].description;
		var upfile1 		= document.getElementById('upfile1');
		var hidIsFilePathVal = document.getElementById('hidIsFilePath').value;
		
		if (name.value == '')
		{
			alert('Моля въведете името на файла.');
			name.focus();
			return false;
		}
		//if (description1.value == '')
		{
		  //alert('Моля въведете описание на файла.');
			//description1.focus();
			//return false;
		}
		if (hidIsFilePathVal == 0 || hidIsFilePathVal == '')
		{
			if ( upfile1.value == '')
			{
				alert('Моля изберете файл.');
				upfile1.focus();
				return false;
			}
		}
		return true;
	}
	
	function js_fncancel()
	{
		js_fnedit();
		document.getElementById('hidIsFilePath').value = 1;
		//alert(document.getElementById('hidIsFilePath').value );
	}
	
	function js_fnchange()
	{
		js_fnadd();
		document.getElementById('cancel').style.display = 'inline';
		document.getElementById('hidIsFilePath').value = 0;
		//alert(document.getElementById('hidIsFilePath').value );
	}
	function js_fnadd()
	{
		var trfile1 = document.getElementById('trfile1');
		var trfile2 = document.getElementById('trfile2');
		trfile1.style.display = '';
		trfile2.style.display = 'none';
		document.getElementById('cancel').style.display = 'none';
	}
	function js_fnedit()
	{
		var trfile1 = document.getElementById('trfile1');
		var trfile2 = document.getElementById('trfile2');
		trfile1.style.display = 'none';
		trfile2.style.display = '';
	}
//end PhotoColor

	function onVisible()
	{
		var trfile1 = document.getElementById('trfile1');
		var trfile2 = document.getElementById('trfile2');
		trfile1.style.display = 'none';
		trfile2.style.display = '';
	}
	window.online = function () {onVisible()};
//-->
</script>
</form>
<?php
}
	
	function fsize_unit_convert($bytes)
	{
		$units = array('b', 'kb', 'mb', 'gb');
		$converted = $bytes . ' ' . $units[0];
		for ($i = 0; $i < count($units); $i++)
		{
			if (($bytes/pow(1024, $i)) >= 1)
			{$converted = round($bytes/pow(1024, $i), 2) . ' ' . $units[$i];}
		}
		return $converted;
	}
	
	function output_file($file, $name, $mime_type='')
	{
		/*
		This function takes a path to a file to output ($file), 
		the filename that the browser will see ($name) and 
		the MIME type of the file ($mime_type, optional).
		 
		If you want to do something on download abort/finish,
		register_shutdown_function('function_name');
		*/
		if(!is_readable($file)) die('File not found or inaccessible!');
		 
		$size = filesize($file);
		$name = rawurldecode($name);
		 
		/* Figure out the MIME type (if not specified) */
		$known_mime_types=array(
		"pdf" => "application/pdf",
		"txt" => "text/plain",
		"html" => "text/html",
		"htm" => "text/html",
		"exe" => "application/octet-stream",
		"zip" => "application/zip",
		"doc" => "application/msword",
		"xls" => "application/vnd.ms-excel",
		"ppt" => "application/vnd.ms-powerpoint",
		"gif" => "image/gif",
		"png" => "image/png",
		"jpeg"=> "image/jpg",
		"jpg" =>  "image/jpg",
		"php" => "text/plain"
		);
		 
		if($mime_type==''){
		$file_extension = strtolower(substr(strrchr($file,"."),1));
		if(array_key_exists($file_extension, $known_mime_types)){
		$mime_type=$known_mime_types[$file_extension];
		} else {
		$mime_type="application/force-download";
		};
		};
		 
		@ob_end_clean(); //turn off output buffering to decrease cpu usage
		 
		// required for IE, otherwise Content-Disposition may be ignored
		if(ini_get('zlib.output_compression'))
		ini_set('zlib.output_compression', 'Off');
		 
		header('Content-Type: ' . $mime_type);
		header('Content-Disposition: attachment; filename="'.$name.'"');
		header("Content-Transfer-Encoding: binary");
		header('Accept-Ranges: bytes');
		 
		/* The three lines below basically make the 
		download non-cacheable */
		header("Cache-control: private");
		header('Pragma: private');
		header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
		 
		// multipart-download and download resuming support
		if(isset($_SERVER['HTTP_RANGE']))
		{
		list($a, $range) = explode("=",$_SERVER['HTTP_RANGE'],2);
		list($range) = explode(",",$range,2);
		list($range, $range_end) = explode("-", $range);
		$range=intval($range);
		if(!$range_end) {
		$range_end=$size-1;
		} else {
		$range_end=intval($range_end);
		}
		 
		$new_length = $range_end-$range+1;
		header("HTTP/1.1 206 Partial Content");
		header("Content-Length: $new_length");
		header("Content-Range: bytes $range-$range_end/$size");
		} else {
		$new_length=$size;
		header("Content-Length: ".$size);
		}
		 
		/* output the file itself */
		$chunksize = 1*(1024*1024); //you may want to change this
		$bytes_send = 0;
		if ($file = fopen($file, 'r'))
		{
		if(isset($_SERVER['HTTP_RANGE']))
		fseek($file, $range);
		 
		while(!feof($file) && 
		(!connection_aborted()) && 
		($bytes_send<$new_length)
		)
		{
		$buffer = fread($file, $chunksize);
		print($buffer); //echo($buffer); // is also possible
		flush();
		$bytes_send += strlen($buffer);
		}
		fclose($file);
		} else die('Error - can not open file.');
		 
		die();
	}	
?>
<?php 
	function showhelptext()
	{
		global $database;
		
		$database->setQuery( "SELECT type,helptext FROM #__fileuploadtype" );
		$rows = $database->Query();
		
		$row_count=0;
		$num_rows = mysql_num_rows($rows) ;
		
		if ($num_rows) 
		{
			$type 			= mysql_result($rows,$row_count,'type');
			$helptext		= mysql_result($rows,$row_count,'helptext');
		}
  ?>
  <table  border="0"  cellspacing="0" cellpadding="0">
<tr>
    <td height="40" align="left" valign="middle"><span style="font-family:Arial, Helvetica, sans-serif;font-size:20PX; color:#135BAD">Качване на урок</span></td>
  </tr>
      <tr>
        <td height="50" class="main3"><a href="<?php echo sefRelToAbs("index.php?option=com_ftpsystem&func=ftpuploadlist&Itemid=$Itemid");?>" id=""/a><a  href="<?php echo sefRelToAbs("index.php?option=com_ftpsystem&func=ftpupload&Itemid=$Itemid&id=0");?>">Качи урок</a>&nbsp;|&nbsp;<a href="#"  style="color:#000000;font-weight:bold;">Условия за качване</a></td>
      </tr>
      <tr>
        <td>
		<table width="720" border="0" align="center"  cellpadding="0" cellspacing="0" >
          <tr>
            <td><table width="100%">
              <tr>
                <td align="center">  <h1><?php echo 'Type '. $type;?></h1></td>
              </tr>
              <tr>
                <td>  <p style="font-family:verdana;font-size:8pt;"><?php echo  $helptext;?></p></td>
              </tr>
            </table></td>
          </tr>
        </table></td>
      </tr>
  </table>

<?php 
	}
?>
Where and what code to put to upload files via ftp server? Thanks advanced!

Re: ftp upload via php script?

Posted: Thu May 13, 2010 1:43 am
by Christopher
You don't need a script for FTP. It is a separate protocol like HTTP that should have it own server on you host. Check with your hosting company on how to setup FTP accounts.