homepage Welcome to WebmasterWorld Guest from 54.226.168.96
register, free tools, login, search, subscribe, help, library, announcements, recent posts, open posts,
Subscribe to WebmasterWorld
Home / Forums Index / Code, Content, and Presentation / PHP Server Side Scripting
Forum Library, Charter, Moderators: coopster & jatar k

PHP Server Side Scripting Forum

    
stuck with a php ajax image uploader - need to record info in database
hozyali




msg:4348866
 10:03 pm on Aug 7, 2011 (gmt 0)

Hi,

I am using this script [bit.ly...]

I have also attached 2 php files. anyone willing to help can download the code from the above link and try.

The code itself works perfect, and uploads the images fine but I need to add little function to record each uploaded image's name, a session variable a couple of IDs in a mysql db. I am stuck at this point, but I am not good with OOP based programming. and this isn't working for me.

It is now sending records to the db but doesn't call any upload file values nor the sessions variables etc.

I have pasted 2 files. One is the actual sample file which is provided by the above guy (php.php) and the other is upload_event_photos.php which is created using the sample (php.php) file and added my own function of record info to db from line 156 to 160 and then calling it on line number 170.

Will really appreciate any help on this. Please advise.

Thanks (below are the codes of 2 files)

upload_event_photos.php
<?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.');
}
}
}

/**
* Handle file uploads via regular form post (uses the $_FILES array)
*/
class qqUploadedFileForm {
/**
* Save the file to the specified path
* @return boolean TRUE on success
*/
function save($path) {
if(!move_uploaded_file($_FILES['qqfile']['tmp_name'], $path)){
return false;
}
return true;
}
function getName() {
return $_FILES['qqfile']['name'];
}
function getSize() {
return $_FILES['qqfile']['size'];
}
}

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, $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'];
//$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, it should be one of '. $these . '.');
}

if(!$replaceOldFile){
/// don't overwrite previous files that were uploaded
while (file_exists($uploadDirectory . $filename . '.' . $ext)) {
$filename .= rand(10, 99);
}
}

if ($this->file->save($uploadDirectory . $filename . '.' . $ext)){
return array('success'=>true);

} else {
return array('error'=> 'Could not save uploaded file.' .
'The upload was cancelled, or server error encountered');
}
ExecuteSql();
}
function ExecuteSql($fnm) {
global $filename;
include 'includes/db_config.php';
mysql_query("INSERT INTO x_tbl_photos (img_filename) VALUES('$filename') ");
}
}

// list of valid extensions, ex. array("jpeg", "xml", "bmp")
$allowedExtensions = array();
// max file size in bytes
$sizeLimit = 10 * 1024 * 1024;

$uploader = new qqFileUploader($allowedExtensions, $sizeLimit);
$result = $uploader->handleUpload('event_photos/');
$sqlresult = $uploader->ExecuteSql($_SESSION['EvPicID']);
// to pass data through iframe you will need to encode all html tags
echo htmlspecialchars(json_encode($result), ENT_NOQUOTES);
?>


php.php
<?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.');
}
}
}

/**
* Handle file uploads via regular form post (uses the $_FILES array)
*/
class qqUploadedFileForm {
/**
* Save the file to the specified path
* @return boolean TRUE on success
*/
function save($path) {
if(!move_uploaded_file($_FILES['qqfile']['tmp_name'], $path)){
return false;
}
return true;
}
function getName() {
return $_FILES['qqfile']['name'];
}
function getSize() {
return $_FILES['qqfile']['size'];
}
}

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, $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'];
//$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, it should be one of '. $these . '.');
}

if(!$replaceOldFile){
/// don't overwrite previous files that were uploaded
while (file_exists($uploadDirectory . $filename . '.' . $ext)) {
$filename .= rand(10, 99);
}
}

if ($this->file->save($uploadDirectory . $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();
// max file size in bytes
$sizeLimit = 10 * 1024 * 1024;

$uploader = new qqFileUploader($allowedExtensions, $sizeLimit);
$result = $uploader->handleUpload('uploads/');
// to pass data through iframe you will need to encode all html tags
echo htmlspecialchars(json_encode($result), ENT_NOQUOTES);

 

hozyali




msg:4349624
 6:43 pm on Aug 9, 2011 (gmt 0)

Hi, Can anyone just tell me how do I call a variable returned from another function inside the same class?

Thank you

coopster




msg:4351002
 10:41 pm on Aug 12, 2011 (gmt 0)

If the variable is being returned from another method (function) in the same class you can assign it to your own variable name within the method you are currently operating. The scope will be within that method only. Otherwise you can make a variable public in the class definition.

If this isn't making sense please feel free to post a simple example and we can go from there. The code dump above is just way too much for most members to want to sift through.

hozyali




msg:4351091
 7:46 am on Aug 13, 2011 (gmt 0)

actually the above code, there is a function for handleUpload() inside the class, that uploads the files and the result array has the data. I am really not sure how can I get the file name from this function in my other function in the same class. and that is all I want.

Thanks again for your help.

coopster




msg:4353049
 12:34 pm on Aug 18, 2011 (gmt 0)

You could create a public (or protected or private) property (variable) in the class and assign the file name to it. It would then be available in the other method (function) within the same class. If you want to access it outside the class you need to define it as public. You could go protected, but you would need to extend the class, etc. which is more advanced.

Another option would be to return the file name from the upload method rather than boolean true.

hozyali




msg:4353090
 1:53 pm on Aug 18, 2011 (gmt 0)

can you provide example?

coopster




msg:4354301
 7:07 pm on Aug 22, 2011 (gmt 0)

Well I don't really know how this class works or where you are calling it from but the latter part of my response meant you could do something like ...

if ($this->file->save($uploadDirectory . $filename . '.' . $ext)){
return array('success'=>true, 'filename' => $filename);
} else {
...

... but you will need to determine that based on your application and how this class is implemented. Meaning, if modifying that return array is going to botch something else you will need to go with a different method like I mentioned using a public variable.

Global Options:
 top home search open messages active posts  
 

Home / Forums Index / Code, Content, and Presentation / PHP Server Side Scripting
rss feed

All trademarks and copyrights held by respective owners. Member comments are owned by the poster.
Terms of Service ¦ Privacy Policy ¦ Report Problem ¦ About
© Webmaster World 1996-2014 all rights reserved