• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 469
  • Last Modified:

Help writing filename to db

Hi Guys,

I've got the flowing code that takes an uploaded pdf and places it in one directory while taking a screenshot of the frontpage and placing that in another directory (ignore the mess!):

<?php
$myFileName;

/**
 * Handle file uploads via XMLHttpRequest
 */
class qqUploadedFileXhr {
    /**
     * Save the file to the specified path
     * @return boolean TRUE on success
     */
    function save($path) {    
        $input = fopen("php://input", "r");
        $temp = tmpfile();
        $realSize = stream_copy_to_stream($input, $temp);
        fclose($input);
        
        if ($realSize != $this->getSize()){            
            return false;
        }
        
        $target = fopen($path, "w");        
        fseek($temp, 0, SEEK_SET);
        stream_copy_to_stream($temp, $target);
        fclose($target);
        
        return true;
    }
    function getName() {
        return $_GET['qqfile'];
    }
    function getSize() {
        if (isset($_SERVER["CONTENT_LENGTH"])){
            return (int)$_SERVER["CONTENT_LENGTH"];            
        } else {
            throw new Exception('Getting content length is not supported.');
        }      
    }   
}
$pathinfo['filename'];

class qqFileUploader {
    private $allowedExtensions = array();
    private $sizeLimit = 10485760;
    private $file;

    function __construct(array $allowedExtensions = array(), $sizeLimit = 10485760){        
        $allowedExtensions = array_map("strtolower", $allowedExtensions);
            
        $this->allowedExtensions = $allowedExtensions;        
        $this->sizeLimit = $sizeLimit;
        
        $this->checkServerSettings();       

        if (isset($_GET['qqfile'])) {
            $this->file = new qqUploadedFileXhr();
        } elseif (isset($_FILES['qqfile'])) {
            $this->file = new qqUploadedFileForm();
        } else {
            $this->file = false; 
        }
    }
    
    private function checkServerSettings(){        
        $postSize = $this->toBytes(ini_get('post_max_size'));
        $uploadSize = $this->toBytes(ini_get('upload_max_filesize'));        
        
        if ($postSize < $this->sizeLimit || $uploadSize < $this->sizeLimit){
            $size = max(1, $this->sizeLimit / 1024 / 1024) . 'M';             
            die("{'error':'increase post_max_size and upload_max_filesize to $size'}");    
        }        
    }
    
    private function toBytes($str){
        $val = trim($str);
        $last = strtolower($str[strlen($str)-1]);
        switch($last) {
            case 'g': $val *= 1024;
            case 'm': $val *= 1024;
            case 'k': $val *= 1024;        
        }
        return $val;
    }
    
    /**
     * Returns array('success'=>true) or array('error'=>'error message')
     */
    function handleUpload($uploadDirectory, &$str, $replaceOldFile = FALSE){

	//exec("convert /var/www/current/server/test.pdf[0]  /var/www/current/server/uploads/preview/test.jpg"); 

        if (!is_writable($uploadDirectory)){

            return array('error' => "Server error. Upload directory isn't writable.");
        }
        
        if (!$this->file){
            return array('error' => 'No files were uploaded.');
        }
        
        $size = $this->file->getSize();
        
        if ($size == 0) {
            return array('error' => 'File is empty');
        }
        
        if ($size > $this->sizeLimit) {
            return array('error' => 'File is too large');
        }
        
        $pathinfo = pathinfo($this->file->getName());
        $filename = $pathinfo['filename'];
	$pathinfo = pathinfo($this->file->getName());
        $filename2 = (string)$pathinfo['filename'];
        //$filename = md5(uniqid());
        $ext = $pathinfo['extension'];

        if($this->allowedExtensions && !in_array(strtolower($ext), $this->allowedExtensions)){
            $these = implode(', ', $this->allowedExtensions);
            return array('error' => 'File has an invalid extension, ProPaGate only accepts .'. $these . '');
        }
        
        if(!$replaceOldFile){
            /// don't overwrite previous files that were uploaded
            while (file_exists($uploadDirectory . $filename . '.' . $ext)) {
                $filename .= date('(d-m-Y H:i)');
            }
        }
        
        if ($this->file->save($uploadDirectory . $filename . '.' . $ext)){

		$str = $filename . '.' . $ext;
            return array('success'=>true);
        } else {
            return array('error'=> 'Could not save uploaded file.' .
                'The upload was cancelled, or server error encountered');
        }
	
        
    }    
}

// list of valid extensions, ex. array("jpeg", "xml", "bmp")
$allowedExtensions = array('pdf');
// max file size in bytes
$sizeLimit = 10 * 1024 * 1024;
$uploader = new qqFileUploader($allowedExtensions, $sizeLimit);  
$result = $uploader->handleUpload('uploads/files/', $myFileName);

$com2 = getcwd().'/convert /var/www/current/server/uploads/files/"'.$myFileName.'[0]" /var/www/current/server/uploads/preview/"'.$myFileName.'.jpg"';

exec($com2);
// to pass data through iframe you will need to encode all html tags
echo htmlspecialchars(json_encode($result), ENT_NOQUOTES);

Open in new window


I also need to enter $myFileName into a table in my database
Here is the relevent code:

$con = mysql_connect( "localhost" , "root" , "Mounta1n" );

if (!$con)

  {
  die('Could not connect: ' . mysql_error());
  }

mysql_select_db('propagate' , $con);

$sql_query = ("INSERT INTO storage (ID, name) VALUES ('NULL', '$myFileName')");
mysql_query($sql_query);

mysql_close($con);

Open in new window



Could somebody put the two together so that the filename will be sent to the database? I've tryed a few ways but i'm having no luck.

Thanks in advance!!!
0
the_con
Asked:
the_con
1 Solution
 
tsmgeekCommented:
<?php

/**
 * Handle file uploads via XMLHttpRequest
 */
class qqUploadedFileXhr {
    /**
     * Save the file to the specified path
     * @return boolean TRUE on success
     */
    function save($path) {    
        $input = fopen("php://input", "r");
        $temp = tmpfile();
        $realSize = stream_copy_to_stream($input, $temp);
        fclose($input);
        
        if ($realSize != $this->getSize()){            
            return false;
        }
        
        $target = fopen($path, "w");        
        fseek($temp, 0, SEEK_SET);
        stream_copy_to_stream($temp, $target);
        fclose($target);
        
        return true;
    }
    function getName() {
        return $_GET['qqfile'];
    }
    function getSize() {
        if (isset($_SERVER["CONTENT_LENGTH"])){
            return (int)$_SERVER["CONTENT_LENGTH"];            
        } else {
            throw new Exception('Getting content length is not supported.');
        }      
    }   
}

class qqFileUploader {
    private $allowedExtensions = array();
    private $sizeLimit = 10485760;
    private $file;

    function __construct(array $allowedExtensions = array(), $sizeLimit = 10485760){        
        $allowedExtensions = array_map("strtolower", $allowedExtensions);
            
        $this->allowedExtensions = $allowedExtensions;        
        $this->sizeLimit = $sizeLimit;
        
        $this->checkServerSettings();       

        if (isset($_GET['qqfile'])) {
            $this->file = new qqUploadedFileXhr();
#        } elseif (isset($_FILES['qqfile'])) {
#            $this->file = new qqUploadedFileForm();
        } else {
            $this->file = false; 
        }
    }
    
    private function checkServerSettings(){        
        $postSize = $this->toBytes(ini_get('post_max_size'));
        $uploadSize = $this->toBytes(ini_get('upload_max_filesize'));        
        
        if ($postSize < $this->sizeLimit || $uploadSize < $this->sizeLimit){
            $size = max(1, $this->sizeLimit / 1024 / 1024) . 'M';             
            die("{'error':'increase post_max_size and upload_max_filesize to $size'}");    
        }        
    }
    
    private function toBytes($str){
        $val = trim($str);
        $last = strtolower($str[strlen($str)-1]);
        switch($last) {
            case 'g': $val *= 1024;
            case 'm': $val *= 1024;
            case 'k': $val *= 1024;        
        }
        return $val;
    }
    
    /**
     * Returns array('success'=>true) or array('error'=>'error message')
     */
    function handleUpload($uploadDirectory, &$str, $replaceOldFile = FALSE){

        if (!is_writable($uploadDirectory)){

            return array('error' => "Server error. Upload directory isn't writable.");
        }
        
        if (!$this->file){
            return array('error' => 'No files were uploaded.');
        }
        
        $size = $this->file->getSize();
        
        if ($size == 0) {
            return array('error' => 'File is empty');
        }
        
        if ($size > $this->sizeLimit) {
            return array('error' => 'File is too large');
        }
        
        $pathinfo = pathinfo($this->file->getName());
        $filename = $pathinfo['filename'];
		$pathinfo = pathinfo($this->file->getName());
        $filename2 = (string)$pathinfo['filename'];
        //$filename = md5(uniqid());
        $ext = $pathinfo['extension'];

        if($this->allowedExtensions && !in_array(strtolower($ext), $this->allowedExtensions)){
            $these = implode(', ', $this->allowedExtensions);
            return array('error' => 'File has an invalid extension, ProPaGate only accepts .'. $these . '');
        }
        
        if(!$replaceOldFile){
            /// don't overwrite previous files that were uploaded
            while (file_exists($uploadDirectory . $filename . '.' . $ext)) {
                $filename .= date('(d-m-Y H:i)');
            }
        }
        
        if ($this->file->save($uploadDirectory . $filename . '.' . $ext)){
			$str = $filename . '.' . $ext;
            return array('success'=>true);
        } else {
            return array('error'=> 'Could not save uploaded file.' .
                'The upload was cancelled, or server error encountered');
        }
	
        
    }    
}

class qqPDF2DB extends qqFileUploader {


	function processUpload($uploadDirectory){
		$result1=$uploader->handleUpload($uploadDirectory, $myFileName);
		if(isset($result1['success'])){
			$result2=$this->createThumbnail($myFileName);
			if(isset($result2['success']) && $result2['success']==true){
				$result3=$this->updateDBThumbFN($result2['myThumbFileName']);
				if(isset($result3['success']) && $result3['success']==true){
					return $result3;
				}
			}else{
				return $result2;
			}
		}else{
			return $result1;
		}
	}
	
	function createThumbnail($inFile){
		$pathinfo = pathinfo($inFile);
		$outFile=$pathinfo['filename'];
		$convert = '/usr/local/bin/convert "/var/www/current/server/uploads/files/'.$inFile.'"[0] "/var/www/current/server/uploads/preview/'.$outFile.'.jpg"';
		$retval=exec($convert);
		if($retval==0){$status=true;}else{$status=false;}
		return array('success'=>$status,'myThumbFileName'=>$outFile);
	}
	
	function updateDBThumbFN($myFileName){
	
		$con = mysql_connect( "localhost" , "root" , "Mounta1n" );

		if (!$con)
		  {
		  die('Could not connect: ' . mysql_error());
		  }

		mysql_select_db('propagate' , $con);

		$sql_query = sprintf("INSERT INTO storage (ID, name) VALUES ('NULL', '%s')",
							mysql_real_escape_string($myFileName)
							);
		$result = mysql_query($sql_query);
		if(!$result){$status=false;}else{$status=true;}
		return array('success'=>$status);
	}
}
// list of valid extensions, ex. array("jpeg", "xml", "bmp")
$allowedExtensions = array('pdf');
// max file size in bytes
$sizeLimit = 10 * 1024 * 1024;
$PDF2DB = new qqPDF2DB($allowedExtensions, $sizeLimit);  
$result = $PDF2DB->processUpload('uploads/files/');

// to pass data through iframe you will need to encode all html tags
echo htmlspecialchars(json_encode($result), ENT_NOQUOTES); 

Open in new window


have a look at the above, change whats needed for your system, seem you are missing the class qqUploadedFileForm so ive hashed that out in the construct
0

Featured Post

The new generation of project management tools

With monday.com’s project management tool, you can see what everyone on your team is working in a single glance. Its intuitive dashboards are customizable, so you can create systems that work for you.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now