Solved

Help writing filename to db

Posted on 2011-03-22
1
461 Views
Last Modified: 2012-05-11
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
Comment
Question by:the_con
1 Comment
 
LVL 5

Accepted Solution

by:
tsmgeek earned 500 total points
ID: 35194697
<?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

NFR key for Veeam Backup for Microsoft Office 365

Veeam is happy to provide a free NFR license (for 1 year, up to 10 users). This license allows for the non‑production use of Veeam Backup for Microsoft Office 365 in your home lab without any feature limitations.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Because your company can’t afford for you to make SEO mistakes, you’ll want to ensure you’re taking the right steps each and every time you post a new piece of content. This list of optimization do’s and don’ts can help you become an SEO wizard.
Today, the web development industry is booming, and many people consider it to be their vocation. The question you may be asking yourself is – how do I become a web developer?
The viewer will learn how to dynamically set the form action using jQuery.
The viewer will get a basic understanding of what section 508 compliance can entail, learn about skip navigation links, alt text, transcripts, and font size controls.

828 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question