Solved

Help writing filename to db

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

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

Why do we like using grid based layouts in website design? Let's look at the live examples of websites and compare them to grid based WordPress themes.
"In order to have an organized way for empathy mapping, we rely on a psychological model and trying to model it in a simple way, so we will split the board to three section for each persona and a scenario and try to see what those personas would Do,…
Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…

758 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

20 Experts available now in Live!

Get 1:1 Help Now