KCfinder upload image for many users - php

My website lets logged users to use CKeditor and CKFinder to create pages or blog and of course upload image from editor. I got problem for many users that will use the same images in a single folder. I have searching for the same problem on StackOverflow and I found this question:
KCFinder with CKEditor - setting up dynamic folders for upload files.
I think the solution was good, but rather than creating many folders, I am just thinking how to save every user images by using a prefix of their user ID. For example the user with ID 10 will save his images with prefix 10_xxxxx.jpg and so on.
How to do it. Any body could show me where part of the file script that could be modified? I am using KCFinder V.3.12. Sorry for my English.
$_SESSION['id'] = 10;
public function upload() {
$config = &$this->config;
$file = &$this->file;
$url = $message = "";
if ($config['disabled'] || !$config['access']['files']['upload']) {
if (isset($file['tmp_name'])) #unlink($file['tmp_name']);
$message = $this->label("You don't have permissions to upload files.");
} elseif (true === ($message = $this->checkUploadedFile())) {
$message = "";
$dir = "{$this->typeDir}/";
if (isset($_GET['dir']) &&
(false !== ($gdir = $this->checkInputDir($_GET['dir'])))
) {
$udir = path::normalize("$dir$gdir");
if (substr($udir, 0, strlen($dir)) !== $dir)
$message = $this->label("Unknown error.");
else {
$l = strlen($dir);
$dir = "$udir/";
$udir = substr($udir, $l);
}
}
if (!strlen($message)) {
if (!is_dir(path::normalize($dir)))
#mkdir(path::normalize($dir), $this->config['dirPerms'], true);
$filename = $this->normalizeFilename($file['name']);
$target = file::getInexistantFilename($dir . $filename);
if (!#move_uploaded_file($file['tmp_name'], $target) &&
!#rename($file['tmp_name'], $target) &&
!#copy($file['tmp_name'], $target)
)
$message = $this->label("Cannot move uploaded file to target folder.");
else {
if (function_exists('chmod'))
#chmod($target, $this->config['filePerms']);
$this->makeThumb($target);
$url = $this->typeURL;
if (isset($udir)) $url .= "/$udir";
$url .= "/" . basename($target);
if (preg_match('/^([a-z]+)\:\/\/([^\/^\:]+)(\:(\d+))?\/(.+)$/', $url, $patt)) {
list($unused, $protocol, $domain, $unused, $port, $path) = $patt;
$base = "$protocol://$domain" . (strlen($port) ? ":$port" : "") . "/";
$url = $base . path::urlPathEncode($path);
} else
$url = path::urlPathEncode($url);
}
}
}

Related

Base64_decoded image string saved to directory doesn't show image

I am trying to upload an image from my android application to a php script on my server. In my script, I am attempting to decode the image (using base64_decode) and then use file_put_contents() to save the image as a file in my directory. My problem is that the file 'appears' empty when I have .jpg at the end of the file name. When I removed that to see what was added for the image encoding, I see a very long string of characters, (65214 bytes specifically that were written to the file). When I run the code again, only this time uploading the $_POST['sent_image'] without decoding, I get the same exact string of text.
I am not sure what I am doing wrong... The end goal would be to save the image on the server, so it could be viewed elsewhere online, and also be able to retrieve it and get back into another activity in my android application.
All suggestions are appreciated!
NOTE: I have also tried imagecreatefromstring(), but that causes 0 bytes to be written.
My Code:PHP that gets encoded android image and tries to save to server directory:
<?php
include('inc.php');
if ((isset($_POST['searchinput'])) && (isset($_POST['newUnitStatus'])) && (isset($_POST['generalCause'])) && (isset($_POST['newUnitStatusComment'])) && (isset($_POST['newUnitStatusPhoto'])) && (isset($_POST['lexauser'])) && (isset($_POST['password']))) {
$sgref = "";
$searchinput = $_POST['searchinput'];
$newUnitStatus = $_POST['newUnitStatus'];
$generalCause = $_POST['generalCause'];
$newUnitStatusComment = $_POST['newUnitStatusComment'];
$lexauser = $_POST['lexauser'];
$pass = $_POST['password'];
if ((strpos($searchinput, "/") !== false)) {
$barcodesplit = preg_split('/\D/im', $searchinput, 4);
$sgref = $barcodesplit[0];
$lineitem = $barcodesplit[1];
$unitnumber = $barcodesplit[2];
$totalunits = $barcodesplit[3];
$unitname = $sgref."-".$lineitem."-".$unitnumber."_of_".$totalunits;
$photo = $_POST['newUnitStatusPhoto'];
$decodedPhoto = str_replace('data:image/jpg;base64,', '', $photo);
$decodedPhoto = str_replace(' ', '+', $decodedPhoto);
$newUnitStatusPhoto = base64_decode($decodedPhoto);
//$newUnitStatusPhoto = imagecreatefromstring($decodedPhoto);
$fileName = "".$unitname."_rej";
$target = '../LEXA/modules/bms/uploads/';
$newFile = $target.$fileName;
$docType = "Reject";
$success = file_put_contents($newFile, $newUnitStatusPhoto);
if($success === false) {
$response['message'] = "Couldn not write file.";
echo json_encode($response);
} else {
$response['message'] = "Wrote $success bytes. ";
echo json_encode($response);
}
} else {
$sgref = $searchinput;
$response['message'] = "I'm sorry, but you must enter a unit's uniqueid value to add a unit exception. Please view the siblings for this SG and pick the unit you need. Then you can add the new status.";
echo json_encode($response);
}
} else {
$response['message'] = "Your search value did not get sent. Please try again.";
echo json_encode($response);
}//End logic for post values.
?>
Thank you!
Using str_replace may be problematic if image format is other than jpg, for example.
Example code:
<?php
$photo = $_POST['newUnitStatusPhoto'];
if(substr($photo, 0,5) !== "data:"){
//do error treatment as it's not datauri
die("Error: no data: scheme");
};
$decodedPhoto = substr($photo, 5);
$mimeTerminator = stripos($decodedPhoto,";");
if($mimeTerminator === false){
die("Error: no mimetype found");
};
$decodedPhoto = substr($decodedPhoto, $mimeTerminator+8); //1<;>+4<base>+2<64>+1<,>
// $decodedPhoto = str_replace('data:image/jpg;base64,', '', $photo);
// $decodedPhoto = str_replace(' ', '+', $decodedPhoto);
$newUnitStatusPhoto = base64_decode($decodedPhoto);
//$newUnitStatusPhoto = imagecreatefromstring($decodedPhoto);
$unitname = "testando";
$fileName = "".$unitname."_rej.jpg";
$target = 'img/';
$newFile = $target.$fileName;
if(file_exists($newFile))
unlink($newFile);
$success = file_put_contents($newFile, $newUnitStatusPhoto);
echo $success;

Getting Videos from server directory to display in container on page using PHP

I have been trying to modify some PHP to allow my page to get to a directory and its sub-directories to get video files to display dynamically on my page, I'm using the scripts as follows
$imagetypes = array("video/ogv", "video/webm", "video/mp4");
$dir = "../uploadedVideo/*/";
function getImages($dir)
{
global $imagetypes;
// array to hold return value
$retval = array();
// add trailing slash if missing
if(substr($dir, -1) != "/") $dir .= "/";
// full server path to directory
$fulldir = "{$_SERVER['DOCUMENT_ROOT']}/$dir";
$d = #dir($fulldir) or die("getVideo: Failed opening directory $dir for reading");
while(false !== ($entry = $d->read())) {
// skip hidden files
if($entry[0] == ".") continue;
// check for image files
$f = escapeshellarg("$fulldir$entry");
$mimetype = trim(`file -bi $f`);
foreach($imagetypes as $valid_type) {
if(preg_match("#^{$valid_type}#", $mimetype)) {
$retval[] = array(
'file' => "/$dir$entry",
'size' => getimagesize("$fulldir$entry")
);
break;
}
}
}
$d->close();
return $retval;
}
This the top of my page before the HTML
This the div I'm looking to display static images or thumbnail, which when clicked on will be viewed in the page
<div class="vidSelect">
<?php
// fetch image details
$video = getImages("video");
// display on page
foreach($video as $vid) {
echo "<div class=\"vidContainer\" src=\"{$vid['file']}\"
{$vid['size'][3]}></div>\n";
} ?>
</div>
I haven't as yet sorted the video player, as I'm just looking to get the videos to show up first but have run out of ideas and skills to get any further.
It looks as if something is being seen as 3 div containers are being created although there are five sub directories within one main directory I want to access, Any help would be most gratefully received
So I see your Type is wrong from the comments. Also the Source is not correct.
function getImages($dir) {
global $imagetypes;
// array to hold return value
$retval = array();
// add trailing slash if missing
if (substr($dir, -1) != "/") $dir. = "/";
// full server path to directory
$fulldir = "{$_SERVER['DOCUMENT_ROOT']}/$dir";
$d = #dir($fulldir) or die("getVideo: Failed opening directory $dir for reading");
while (false !== ($entry = $d - > read())) {
// skip hidden files
if ($entry[0] == ".") continue;
// check for image files
$f = escapeshellarg("$fulldir$entry");
$mimetype = trim(`file - bi $f`);
foreach($imagetypes as $valid_type) {
if (preg_match("#^{$valid_type}#", $mimetype)) {
$retval[] = array(
'file' = > "$dir$entry",
'size' = > getimagesize("$fulldir$entry"));
break;
}
}
}
$d - > close();
return $retval;
}
Then in your HTML:
< div class = "vidSelect" >
<? php
// fetch image details
$video = getImages("video");
// display on page
foreach($video as $vid) {
echo "<div class='vidContainer' src='{$vid['file']}' type='{$vid['size']['mime']}'></div>\n";
} ?>
< /div>

php Getting files list &(ampersand) character error

I have code for getting files list in php, but if file name contain & character it doesn't display that file.
Here's the code:
Ps. I'm not php programmer and I really don't know what is this error.
All help will be very appreciated
Thanks so much in advance.
<?php
include_once('config.inc.php');
$current_dir = 'root';
if(array_key_exists('directory',$_POST)) {
$current_dir = $_POST['directory'];
}
// Creating a new XML using DOMDocument
$file_list = new DOMDocument('1.0');
$xml_root = $file_list->createElement('filelist');
$xml_root = $file_list->appendChild($xml_root);
// Setting the 'currentPath' attribute of the XML
$current_path = $file_list->createAttribute('currentPath');
$current_path->appendChild($file_list->createTextNode($current_dir));
$xml_root->appendChild($current_path);
// Replacing the word 'root' with the real root path
$current_dir = substr_replace($current_dir, $root, 0, 4);
$di = new DirectoryIterator($current_dir);
// Creating the XML using DirectoryIterator
while($di->valid())
{
if(false == $di->isDot())
{
if($di->isDir() && true != in_array($di->getBasename(),$h_folders))
{
$fl_node = $file_list->createElement('dir');
$xml_root->appendChild($fl_node);
}else if($di->isFile() && true !== in_array($di->getBasename(),$h_files)
&& true !== in_array(get_ext($di->getBasename()),$h_types))
{
$fl_node = $file_list->createElement('file');
$xml_root->appendChild($fl_node);
}else
{
$di->next();
continue;
}
$name = $file_list->createElement('name',$di->getBasename());
$fl_node->appendChild($name);
$path = substr_replace($di->getRealPath(), 'root', 0, strlen($root));
$path_node = $file_list->createElement('path', $path);
$fl_node->appendChild($path_node);
$di->next();
}else $di->next();
}
function get_ext($filename)
{
$exp = '/^(.+)\./';
return preg_replace($exp,'',$filename);
}
// Returning the XML to Flash.
echo $file_list->saveXML();
?>
The & character is used in HTML to write entities.
If you want to display arbitrary text in HTML, you need to escape it by calling htmlentities().
If you give some source I can help, file content not file name.
Example how get list of files:
$c = "/some/path/to/file/here";
if(is_dir($c)){
foreach(scandir($c) as $file){
if($file != '.' && $file != '..'){
$d = $c.DIRECTORY_SEPARATOR.$file;
echo " \"". realpath($d) ."\"\n";
}
}
}

Retrieving Facebook photos from a php script

I want to develop an app in php that I can link with a particular photo album in my Facebook profile (or with all my photos) in order to know the direct url link of each photo.
The idea is to make an php script who shows in chronological order my facebook photos like a presentation. Im php programmer, but I know nothing about Facebook integration API. So guys if you can suggest me ways to do this it will be nice. Sorry for my English. Thanks!
here is a class for retriving specific user profile pictures (PHP), you'll get the idea from it to create what you want:
<?php
class FBPicture {
public $uid;
public $dir;
public $type = 'large';
public function setUId ($id) {
$this->uid = $id;
}
public function setDir ($dir) {
$this->dir = $dir;
}
public function fetch ($_uid=null, $_dir=null, $_type=null) {
if ($_uid === null)
throw new CHttpException ('Facebook User ID or Username is not set.');
if ($_dir === null)
$_dir = '/storage/';
if ($_type === null)
$_type = 'large';
$this->uid = $_uid;
$this->dir = $_dir;
$this->type = $_type;
$dir = getcwd () . $this->dir;
$type = $this->type;
// request URI
$host = 'http://graph.facebook.com/' . $_uid;
$request = '/picture';
$type = '?type=' . $type;
$contents = file_get_contents ($host.$request.$type);
// create the file (check existance);
$file = 'fb_' . $uid . '_' . rand (0, 9999);
$ext = '.jpg';
if (file_exists ($dir)) {
if (file_exists ($dir.$file.$ext)) {
$file .= $dir.$file.'2'.$ext;
if ($this->appendToFile ($file, $contents)) {
return str_replace ($dir, '', $file);
}
} else {
$file = $dir.$file.$ext;
touch ($file);
if ($this->appendToFile ($file, $contents)) {
return str_replace ($dir, '', $file);
}
}
} else {
// false is returned if directory doesn't exist
return false;
}
}
private function appendToFile ($file, $contents) {
$fp = fopen ($file, 'w');
$retVal = fwrite ($fp, $contents);
fclose ($fp);
return $retVal;
}
}
// sample usage:
// $pic will be the filename of the saved file...
$pic = FBPicture::fetch('zuck', 'uploads/', 'large'); // get a large photo of Mark Zuckerberg, and save it in the "uploads/" directory
// this will request the graph url: http://graph.facebook.com/zuck/picture?type=large
?>

swfupload destroy session? php

hy, i need a little help here:
i use SWFupload to upload images!
in the upload function i make a folder call $_SESSION['folder'] and all the files i upload are in 1 array call $_SESSION['files'] after uploads finish i print_r($_SESSION) but the array is empty? why that?
this is my upload.php:
if($_FILES['image']['name']) {
list($name,$error) = upload('image','jpeg,jpg,png');
if($error) {$result = $error;}
if($name) { // Upload Successful
$result = watermark($name);
print '<img src="uploads/'.$_SESSION['dir'].'/'.$result.'" />';
} else { // Upload failed for some reason.
print 'noname'.$result;
}
}
function upload($file_id, $types="") {
if(!$_FILES[$file_id]['name']) return array('','No file specified');
$isimage = #getimagesize($_FILES[$file_id]['tmp_name']);
if (!$isimage)return array('','Not jpg');
$file_title = $_FILES[$file_id]['name'];
//Get file extension
$ext_arr = split("\.",basename($file_title));
$ext = strtolower($ext_arr[count($ext_arr)-1]); //Get the last extension
//Not really uniqe - but for all practical reasons, it is
$uniqer = substr(md5(uniqid(rand(),1)),0,10);
//$file_name = $uniqer . '_' . $file_title;//Get Unique Name
//$file_name = $file_title;
$file_name = $uniqer.".".$ext;
$all_types = explode(",",strtolower($types));
if($types) {
if(in_array($ext,$all_types));
else {
$result = "'".$_FILES[$file_id]['name']."' is not a valid file."; //Show error if any.
return array('',$result);
}
}
if((!isset($_SESSION['dir'])) || (!file_exists('uploads/'.$_SESSION['dir']))){
$dirname = date("YmdHis"); // 20010310143223
$pathtodir = $_SERVER['DOCUMENT_ROOT']."/ifunk/uploads/";
$newdir = $pathtodir.$dirname;
if(!mkdir($newdir, 0777)){return array('','cannot create directory');}
$_SESSION['dir'] = $dirname;
}
if(!isset($_SESSION['files'])){$_SESSION['files'] = array();}
//Where the file must be uploaded to
$folder = 'uploads/'.$_SESSION['dir'].'/';
//if($folder) $folder .= '/'; //Add a '/' at the end of the folder
$uploadfile = $folder.$file_name;
$result = '';
//Move the file from the stored location to the new location
if (!move_uploaded_file($_FILES[$file_id]['tmp_name'], $uploadfile)) {
$result = "Cannot upload the file '".$_FILES[$file_id]['name']."'"; //Show error if any.
if(!file_exists($folder)) {
$result .= " : Folder don't exist.";
} elseif(!is_writable($folder)) {
$result .= " : Folder not writable.";
} elseif(!is_writable($uploadfile)) {
$result .= " : File not writable.";
}
$file_name = '';
} else {
if(!$_FILES[$file_id]['size']) { //Check if the file is made
#unlink($uploadfile);//Delete the Empty file
$file_name = '';
$result = "Empty file found - please use a valid file."; //Show the error message
} else {
//$_SESSION['files'] = array();
$_SESSION['files'][] .= $file_name;
chmod($uploadfile,0777);//Make it universally writable.
}
}
return array($file_name,$result);
}
SWFUpload doesn't pass the session ID to the script when you upload, so you have to do this yourself. Simply pass the session ID in a get or post param to the upload script, and then in your application do this before session_start:
if(isset($_REQUEST['PHPSESSID'])) {
session_id($_REQUEST['PHPSESSID']);
}
you must pass the session ID to the upload file used by swfupload.
more details here

Categories