Solved

Help writing filename to db

Posted on 2011-03-22
1
458 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

What is SQL Server and how does it work?

The purpose of this paper is to provide you background on SQL Server. It’s your self-study guide for learning fundamentals. It includes both the history of SQL and its technical basics. Concepts and definitions will form the solid foundation of your future DBA expertise.

Question has a verified solution.

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

Learn by example how to specify CSS selectors for Selenium WebDriver test automation software.
Get to know the ins and outs of building a web-based ERP system for your enterprise. Development timeline, technology, and costs outlined.
Viewers will get an overview of the benefits and risks of using Bitcoin to accept payments. What Bitcoin is: Legality: Risks: Benefits: Which businesses are best suited?: Other things you should know: How to get started:
Learn how to create flexible layouts using relative units in CSS.  New relative units added in CSS3 include vw(viewports width), vh(viewports height), vmin(minimum of viewports height and width), and vmax (maximum of viewports height and width).

911 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

Need Help in Real-Time?

Connect with top rated Experts

28 Experts available now in Live!

Get 1:1 Help Now