Jump to content

File upload not working?


Ninjakreborn

Recommended Posts

I can't seem to get this file system to upload.  It's returning an error about directory not writable. I have also verified it's 777 on the server, so I know permissions are right.

 

File Class

<?php 
/**
* Uploader is a file transfer class. it can upload files and images.
* It also can resize and crop images.
* Works on PHP 5
* @author Alaa Al-Hussein
* @link http://www.freelancer-id.com/projects
* @version 1.0
* 
*/
class uploader{
/**
 * Array, The file object as $_FILES['element'].
 * String, file location.
 */
public $source;
/**
 * Destination file location as folder.
 */
public $destDir;
/**
 * Directory for Resized images.
 */
public $resizeDir;
/**
 * Directory for Cropped images.
 */
public $cropDir;
/**
 * stores information for uploading file
 */
private $info = '';
/**
 * Enabling autoName will generate an auto file name for the uploaded file.
 */
public $generateAutoName = true;
/**
 * Handles the error when it occurs.
 */
private $errorMsg = '';
/**
 * new width for resizing and cropping.
 */
public $newWidth;
/**
 * new height for resizing and cropping.
 */
public $newHeight;
/**
 * TOP postion to cropping image.
 */
public $top = 0;
/**
 * LEFT position for cropping image.
 */
public $left = 0;
/**
 * JPG quality (0 - 100). used for image resizing or cropping.
 */
public $quality = 60;

public function __construct(){
	//nothing
}
/**
 * Uploads the file to the server.
 * @param Array $_FILES[]
 */
public function upload($source){		
	if($source != ""){
		$this->source = $source;
	}
	if(is_array($this->source)){
		if($this->fileExists()){
			return false;
		}
		// Check for auto-name generation. If it's set then generate the name automatically.
		if ($this->generateAutoName == true) {
			$this->autoName();				
		}
		return $this->copyFile();
	} else {
		return $this->source;
	}
}
/**
 * return the error messages.
 * @return String messages.
 */
 public function getError(){
		return $this->errorMsg;
 }
 /**
  * Get uploading information.
  */
 public function getInfo(){
	return $this->info;
 }
 /**
  * Auto Name
  */
 private function autoName() {
	$num  = rand(0, 2000000);
	$num2 = rand(0, 2000000);
$this->source['name'] = $num . $num2 . $this->source['name'];
	return $this->source;
 }

 /**
 * Get Image Sizes 
 * Returns an array of variables pertaining to properties of the image.
 * USE THIS ON IMAGES ONLY
 */
 public function getImageSize() {
	 // Get the size information of the provided image.
	 $image_size = getimagesize($this->getTemp());

	 // Setup the height/width so they can be returned in a readable format
	 $return_array['width']  = $image_size[0];
	 $return_array['height'] = $image_size[1];

	 // Return the array of new data.
	 return $return_array;
 }
/**
 * Copy the uploaded file to destination.
 */
private function copyFile(){
	if(!$this->isWritable()){
		$this->errorMsg .= '<div>Error, the directory: ('.$this->destDir.') is not writable. Please fix the permission to be able to upload.</div>';
		return false;
	}
	if(copy($this->source['tmp_name'],$this->destDir . $this->source['name'])){
		// Done.
		$this->info .= '<div>file was uploaded successfully.</div>';
	} else {
		$this->errorMsg .= '<div>Error, the file was not uploaded correctly because of an internal error. Please try again, if you see this message again, please contact web admin.</div>';
	}
}
/**
 * Checks if the file was uploaded.
 * @return boolean
 */
private function uploaded(){
	if($this->source['tmp_name']=="" || $this->source['error'] !=0){
		$this->errorMsg .= '<div>Error, file was not uploaded to the server. Please try again.</div>';
		return false;
	} else 
		return true;
}
/**
 * Prepares the directory.
 */
private function preDir(){
	if($this->destDir!="" && substr($this->destDir, -1,1) != "/"){
		$this->destDir = $this->destDir . '/';
	}
	if($this->resizeDir!="" && substr($this->resizeDir, -1,1) != "/"){
		$this->destDir = $this->resizeDir . '/';
	}
	if($this->cropDir!="" && substr($this->cropDir, -1,1) != "/"){
		$this->destDir = $this->cropDir . '/';
	}
}
/**
 * Check if the folder is writable or not.
 * @return boolean
 */
private function isWritable(){
	$err = false;
	if(!is_writeable($this->destDir) && $this->destDir!=""){
		$this->errorMsg .= '<div>Error, the directory ('.$this->destDir.') is not writeable. File could not be uploaded.</div>';
		$err = true;
	}
	if(!is_writeable($this->resizeDir) && $this->resizeDir!=""){
		$this->errorMsg .= '<div>Error, the directory ('.$this->resizeDir.') is not writeable. File could not be resized.</div>';
		$err = true;
	}
	if(!is_writeable($this->cropDir) && $this->cropDir!=""){
		$this->errorMsg .= '<div>Error, the directory ('.$this->cropDir.') is not writeable. File could not be cropped.</div>';
		$err = true;
	}
	if($err == true){
		return false;
	} else {
		return true;
	}
}
/**
 * Checks if the file exists on the server
 * @return boolean
 */
private function fileExists(){
	$this->preDir();
	if(file_exists($this->destDir.$this->source)){
		$this->errorMsg .= '<div>Upload error because file already exists.</div>';
		return true;
	} else {
		return false;
	}
}
/**
 /586742130./8532 Crops image.
 * @return String fileName or False on error
 */
public function crop($file='',$width='',$height='',$top='',$left=''){
	if($file!=""){ $this->source = $file;}
	if ($width != '') $this->newWidth = $width;
	if ($height != '') $this->newHeight = $height;
	if ($top != '') $this->top = $top;
	if ($left != '') $this->left = $left;
	return $this->_resize_crop(true);
}
/**
 * Resizes an image.
 * @return String fileName or False on error
 */
public function resize($file='',$width='',$height=''){
	if($file!=""){ $this->source = $file; }
	if($width != '') $this->newWidth = $width;
	if($height != '') $this->newHeight = $height;
	return $this->_resize_crop(false);
}
/**
 * Get the Temp file location for the file.
 * If the Source was a file location, it returns the same file location.
 * @return String Temp File Location
 */
private function getTemp(){
	if(is_array($this->source)){
		return $this->source['tmp_name'];
	} else {
		return $this->source;
	}
}
/**
 * Get the File location.
 * If the source was a file location, it returns the same file location.
 * @return String File Location
 */
private function getFile(){
	if(is_array($this->source)){
		return $this->source['name'];
	} else {
		return $this->source;
	}
}
/**
 * Resize or crop- the image.
 * @param boolean $crop
 * @return String fileName False on error
 */
private function _resize_crop ($crop) {
	$ext = explode(".",$this->getFile());
	$ext = strtolower(end($ext));
	list($width, $height) = getimagesize($this->getTemp());
	if(!$crop){
		$ratio = $width/$height;
		if ($this->newWidth/$this->newHeight > $ratio) {
			$this->newWidth = $this->newHeight*$ratio;
		} else {
			$this->newHeight = $this->newWidth/$ratio;
		}
	}
	$normal  = imagecreatetruecolor($this->newWidth, $this->newHeight);
	if($ext == "jpg") {
		$src = imagecreatefromjpeg($this->getTemp());
	} else if($ext == "gif") {
            $src = imagecreatefromgif ($this->getTemp());
	} else if($ext == "png") {
            $src = imagecreatefrompng ($this->getTemp());
	}
	if($crop){
		//$pre = 'part_'; //We want to overwrite file, so comment this out.
  			if(imagecopy($normal, $src, 0, 0, $this->top, $this->left, $this->newWidth, $this->newHeight)){
				$this->info .= '<div>image was cropped and saved.</div>';
			}
			$dir = $this->cropDir;
	} else {
		//$pre = 'thumb_'; //We want to overwrite file, so comment this out.
		if(imagecopyresampled($normal, $src, 0, 0, 0, 0, $this->newWidth, $this->newHeight, $width, $height)){
			$this->info .= '<div>image was resized and saved.</div>';
		}
		$dir = $this->resizeDir;
	}
	if($ext == "jpg" || $ext == "jpeg") {
		imagejpeg($normal, $dir . $pre . $this->getFile(), $this->quality);
	} else if($ext == "gif") {
		imagegif ($normal, $dir . $pre . $this->getFile());
	} else if($ext == "png") {
		imagepng ($normal, $dir . $pre . $this->getFile(),0);
	}
	imagedestroy($src);
	return $src;
}
}
/* Examples Section */
/*
Let me explain first how to manage an image to be uploaded and then to be cropped or resized.
<?php
$uploader = new uploader();
// Setting properties then Uploading the image
$uploader->source = $_FILES['field_image'];
$uploader->destDir = "images/";
$uploader->upload();
// =====================
// Or you may use this too
$uploader->destDir = "images/";
$uploader->upload($_FILES['field_image']);
?>
Note: upload() returns the file name uploaded.

To get error messages, use this code:
<?php
echo $uploader->getError();
// This function will return all errors occured while uploading the image. But it's not printing it to print it where ever you want.
?>
And to get Information messages use this code:
<?php
echo $uploader->getInfo();
// This function will return all information to let the user print it where ever he wants.
?>

After uploading this image, we may resize it. To do that use the following code:
<?php
$uploader->newWidth = 75; // in Pexels.
$uploader->newHeight = 75;
$uploader->resizeDir = "images/resized/";
$uploader->resize();
?>
You may also use this syntax:
<?php
// $uploader->resize($file,$width,$height);
// $file could has a value of "" (nothing), in this case we use the last uploader file.
// if the $file has a String value (file url) it will resize this new file.
$uploader->resizeDir = "images/resized/";
$uploader->resize('',75,75);
// Or you may upload and resize in the same line:
$uploader->resizeDir = "images/resized/";
$uploader->resize($uploader->upload(),75,75);
?>

Crop this image after uploading it:
<?php
$uploader->cropDir = "images/cropped/";
$uploader->newWidth = 75;
$uploader->newHeight = 75;
$uploader->top = 20; // Default is ZERO.. This used to set the cropping top location from the original image.
$uploader->left = 40; // Default is ZERO.. This used to set the cropping left location from the original image.
$uploader->crop();
// You may also use this:
// $uploader->crop($file,$width,$height,$top,$left);
$uploader->cropDir = "images/cropped/";
$uploader->crop('',75,75,20,40);
?>
*/
?>

 

Upload Function

<?php
/* END STANDARD FUNCTIONS */
/* General function to deal with image uploads site_wide. */
function upload_image($file, $dir, $table, $fieldname, $id, $exists, &$data) {
	// Get image information
	if ($file['tmp_name'] != '' && $file['name'] != '') {
		if ($exists == 1) {
			// Delete Associated Image
			$imageSQL = "SELECT " . $fieldname . " FROM " . $table . " WHERE product_id = '" . $id . "'";
			$imageQuery = mysql_query($imageSQL);
			while($row = mysql_fetch_array($imageQuery, MYSQL_ASSOC)) {
				if ($row[$fieldname] != '') {
					$tmpdirectory = '../assets/' . $dir . '/'.$row[$fieldname];
					if (file_exists($tmpdirectory)) {
						unlink($tmpdirectory);
					}
				}
			}
		}				
		$directory  = '../assets/' . $dir . '/'; // Default DIR

		// Upload
		$uploader = new uploader;
		$uploader->destDir = $directory;
		$uploader->generateAutoName = true;
		$file_name = $uploader->upload($file);
		$image_sizes = $uploader->getImageSize();
		echo $uploader->getInfo();
	}

	// Check if image was uploaded and if so database name.
	if ($uploader->source['name'] != '') {
		$data[$fieldname] = $uploader->source['name'];
	}else {
		if ($exists == 1) {
			$tmpSelect = "SELECT " . $fieldname . " FROM " . $table . " WHERE product_id = '".$id."'";
			$tmpQuery  = mysql_query($tmpSelect);
			if ($row = mysql_fetch_array($tmpQuery, MYSQL_ASSOC)) {
				$data[$fieldname] = $row[$fieldname];	
			}else {
				$data[$fieldname] = NULL;	
			}
		}else {
			$data[$fieldname] = NULL;	
		}
	}
}
?>

 

Code to call function

 

<?php
		// Upload all images
		$picture_1 = $_FILES['picture_one'];
		if ($picture_1['tmp_name'] != '' && $picture_1['name'] != '') {
			$functions->upload_image($picture_1, 'product_pictures', 'products', 'picture_1', $product_id, $exists, &$data);
		}
?>

 

At this point I have done all of the debugging I can and it's not working out. Any advice is appreciated.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.