I have a four image field in my form for different use. When I try to upload images on two fields image_oneand image_two sometimes it uploads image_one and sometimes only image_two
My controller code:
if(Input::file('image_one'))
{
$image_one = $post->storePostPicture($request->file('image_one'));
if($image_one !== false) {
$post->image_one = $image_one;
$post->save();
}
}
if(Input::file('image_two'))
{
$image_two = $post->storePostPicture($request->file('image_two'));
if($image_two !== false) {
$post->image_two = $image_two;
$post->save();
}
}
And my storePostPicture function in model :
public function storePostPicture($image) {
if($image instanceof \Illuminate\Http\UploadedFile && $image->isValid() && $image->isReadable()) {
$filePath = 'public/images/user' . DIRECTORY_SEPARATOR . 'post';
if(!File::exists(storage_path('app' . DIRECTORY_SEPARATOR . $filePath))) {
File::makeDirectory(storage_path('app' . DIRECTORY_SEPARATOR . $filePath), 0755, true);
}
$imageName = sha1(time().time()) . ".". $image->getClientOriginalExtension();
if($image->storeAs($filePath, $imageName) !== false) {
$path = "/storage/images/user/post/";
return $path . DIRECTORY_SEPARATOR . $imageName;
}
}
return false;
}
What am I doing wrong?
In your migration table, make sure you have made all the image fields nullable:
$table->string('image_one')->nullable();
$table->string('image_two')->nullable();
...
Also, save your post model after collecting all the data.
if(Input::file('image_one'))
{
$image_one = $post->storePostPicture($request->file('image_one'));
if($image_one !== false) {
$post->image_one = $image_one;
}
}
if(Input::file('image_two'))
{
$image_two = $post->storePostPicture($request->file('image_two'));
if($image_two !== false) {
$post->image_two = $image_two;
}
}
$post->save(); //saving the post model here
Related
I have the next code but i need scan multiple dir on array.
public static function scanFiles($directory, $recursive = true, $listDirs = false, $listFiles = true, $exclude = '') {
$arrayItems = array();
$skipByExclude = false;
$handle = opendir($directory);
if ($handle) {
while (false !== ($file = readdir($handle))) {
preg_match("/(^(([\.]){1,2})$|(\.(svn|git|md))|(Thumbs\.db|\.DS_STORE|\.html))$/iu", $file, $skip);
if($exclude){
preg_match($exclude, $file, $skipByExclude);
}
if (!$skip && !$skipByExclude) {
if (is_dir($directory. DS . $file)) {
if($recursive) {
$arrayItems = array_merge($arrayItems, self::scanFiles($directory. DS . $file, $recursive, $listDirs, $listFiles, $exclude));
}
if($listDirs){
$file = $directory . DS . $file;
$arrayItems[] = $file;
}
} else {
if($listFiles){
$file = $directory . DS . $file;
$arrayItems[] = $file;
}
}
}
}
closedir($handle);
}
return $arrayItems;
}
Your use is: scanFiles('path/to/folder')
But I need the path to be an array, example: scanFiles(array('path/to/folder1', 'path/to/folder2')).
Some one help...?
Thank you in advance and sorry for my bad english.
you can change the function like this, just adding foreach with the code block that you have for scanning directory
public static function scanFiles($directories, $recursive = true, $listDirs = false, $listFiles = true, $exclude = '') {
$arrayItems = array();
$skipByExclude = false;
foreach($directories as $directory) {
$handle = opendir($directory);
if ($handle) {
while (false !== ($file = readdir($handle))) {
preg_match("/(^(([\.]){1,2})$|(\.(svn|git|md))|(Thumbs\.db|\.DS_STORE|\.html))$/iu", $file, $skip);
if ($exclude){
preg_match($exclude, $file, $skipByExclude);
}
if (!$skip && !$skipByExclude) {
if (is_dir($directory. DS . $file)) {
if ($recursive) {
$arrayItems = array_merge($arrayItems, self::scanFiles($directory. DS . $file, $recursive, $listDirs, $listFiles, $exclude));
}
if ($listDirs) {
$file = $directory . DS . $file;
$arrayItems[] = $file;
}
} else {
if ($listFiles) {
$file = $directory . DS . $file;
$arrayItems[] = $file;
}
}
}
}
closedir($handle);
}
}
return $arrayItems;
}
Here is my get_status function which is inside the controller. I am trying to generate zip fle in the given path '/var/www/html/hdfcdsademo/uploadpdf/'.$this->session->userdata("product_type").'/'.
public function get_status(){
$query=$this->db->query("select (select COUNT(DISTINCT(dsahubwise)) FROM month_3_lap where isgenerated=0 && product_pre='".$this->session->userdata("product_type")."') as pending,(select COUNT(DISTINCT(dsahubwise)) FROM month_3_lap where isgenerated=1 && product_pre='".$this->session->userdata("product_type")."') as generate");
$result=$query->row();
if($result->pending==0){
$this->generatepdf_model->createZipFromDir('/var/www/html/hdfcdsademo/uploadpdf/'.$this->session->userdata("product_type").'/','/var/www/html/hdfcdsademo/uploadpdf/'.$this->session->userdata("product_type").'/LAP_DSA.zip');
$this->db->query("UPDATE generatepdf SET isgenerate=0,is_archive=1 where product_pre='".$this->session->userdata("product_type")."'");
}
echo json_encode(['pending'=>$result->pending,'generate'=>$result->generate]);
}
This is my createZipFromDir function inside the model.
public function createZipFromDir($dir, $zip_file) {
$zip = new ZipArchive;
if (true !== $zip->open($zip_file, ZIPARCHIVE::CREATE | ZIPARCHIVE::OVERWRITE)) {
return false;
}
$this->zipDir($dir, $zip);
return $zip;
}
public function zipDir($dir, $zip, $relative_path = DIRECTORY_SEPARATOR) {
$dir = rtrim($dir, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR;
if ($handle = opendir($dir)) {
while (false !== ($file = readdir($handle))) {
if ($file === '.' || $file === '..') {
continue;
}
if (is_file($dir . $file)) {
$zip->addFile($dir . $file, $file);
} elseif (is_dir($dir . $file)) {
$this->zipDir($dir . $file, $zip, $relative_path . $file);
}
}
}
closedir($handle);
}
Before uploading a file to a directory, you have to create the directory on server:
public function get_status(){
$query=$this->db->query("select (select COUNT(DISTINCT(dsahubwise)) FROM month_3_lap where isgenerated=0 && product_pre='".$this->session->userdata("product_type")."') as pending,(select COUNT(DISTINCT(dsahubwise)) FROM month_3_lap where isgenerated=1 && product_pre='".$this->session->userdata("product_type")."') as generate");
$result=$query->row();
if($result->pending==0){
$dir='/var/www/html/hdfcdsademo/uploadpdf/'.$this->session->userdata("product_type");
if (!file_exists($dir)) {
mkdir($baseDir, 0777, true);
}
$this->generatepdf_model->createZipFromDir('/var/www/html/hdfcdsademo/uploadpdf/'.$this->session->userdata("product_type").'/','/var/www/html/hdfcdsademo/uploadpdf/'.$this->session->userdata("product_type").'/LAP_DSA.zip');
$this->db->query("UPDATE generatepdf SET isgenerate=0,is_archive=1 where product_pre='".$this->session->userdata("product_type")."'");
}
echo json_encode(['pending'=>$result->pending,'generate'=>$result->generate]);
}
I've got 3 different classes (class Thumbnail in Thumbnail.php, class Upload in Upload.php and class ThumbnailUpload in ThumbnailUpload.php) all in the same namespace (PhotoProject). Currently, it will load an image, create a thumbnail and store both in selected directory, but it will not store the information requested into a database. If you look in the code snippet of blog_insert.php, once it gets to calling $loader->collectFilenames to be assigned to $names, nothing is ever stored in $names[]. I've did a var_dump, and $names is always empty. Any suggestions? Below are the code snippets.
class Upload {
protected $collectednames = [];
protected $typeCheckingOn = true;
protected $notTrusted = ['bin', 'cgi', 'exe', 'js'];
protected $newName;
protected $destination;
protected $max = 8388608;
protected $messages = [];
protected $permitted = [
'image/gif',
'image/png',
'image/jpg'
];
...
public function collectFilenames() {
return $this->collectednames;
}
blog_insert.php
<?php
use PhotoProject\ThumbnailUpload;
require_once '../includes/connection.php';
$conn = dbConnect();
if (isset($_POST['insert'])) {
$OK = false;
$stmt = $conn->stmt_init();
// if a file has been uploaded, process it
if(isset($_POST['upload_new']) && $_FILES['image']['error'] == 0) {
$imageOK = false;
require_once '../PhotoProject/ThumbnailUpload.php';
$loader = new ThumbnailUpload('path to store images');
$loader->setThumbDestination('path to store thumbnail');
$loader->upload();
$names = $loader->collectFilenames();
// $names will be an empty array if the upload failed
if ($names) {
$sql = 'INSERT INTO images (filename, caption) VALUES (?, ?)';
Class Thumbnail
<?php
namespace PhotoProject;
class Thumbnail {
protected $original;
protected $originalwidth;
protected $originalheight;
protected $basename;
protected $thumbwidth;
protected $thumbheight;
protected $maxSize = 350;
protected $canProcess = false;
protected $imageType;
protected $destination;
protected $suffix = '_thb';
protected $messages = [];
public function __construct($image) {
if (is_file($image) && is_readable($image)) {
$details = getimagesize($image);
} else {
$details = null;
$this->messages[] = "Cannot open $image.";
}
// if getimagesize() returns an array, it looks like an image
if (is_array($details)) {
$this->original = $image;
$this->originalwidth = $details[0];
$this->originalheight = $details[1];
$this->basename = pathinfo($image, PATHINFO_FILENAME);
// check the MIME type
$this->checkType($details['mime']);
} else {
$this->messages[] = "$image doesn't appear to be an image.";
}
}
public function setDestination($destination) {
if (is_dir($destination) && is_writable($destination)) {
// get last character
$last = substr($destination, -1);
// add a trailing slash if missing
if ($last == '/' || $last == '\\') {
$this->destination = $destination;
} else {
$this->destination = $destination . DIRECTORY_SEPARATOR;
}
} else {
$this->messages[] = "Cannot write to $destination.";
}
}
public function setMaxSize($size) {
if (is_numeric($size) && $size > 0) {
$this->maxSize = abs($size);
} else {
$this->messages[] = 'The value for setMaxSize() must be a positive number.';
$this->canProcess = false;
}
}
public function setSuffix($suffix) {
if (preg_match('/^\w+$/', $suffix)) {
if (strpos($suffix, '_') !== 0) {
$this->suffix = '_' . $suffix;
} else {
$this->suffix = $suffix;
}
} else {
$this->suffix = '';
}
}
public function create() {
if ($this->canProcess && $this->originalwidth != 0) {
$this->calculateSize($this->originalwidth, $this->originalheight);
$this->createThumbnail();
} elseif ($this->originalwidth == 0) {
$this->messages[] = 'Cannot determine size of ' . $this->original;
}
}
public function getMessages() {
return $this->messages;
}
protected function checkType($mime) {
$mimetypes = ['image/jpeg', 'image/png', 'image/gif'];
if (in_array($mime, $mimetypes)) {
$this->canProcess = true;
// extract the characters after 'image/'
$this->imageType = substr($mime, 6);
}
}
protected function calculateSize($width, $height) {
if ($width <= $this->maxSize && $height <= $this->maxSize) {
$ratio = 1;
} elseif ($width > $height) {
$ratio = $this->maxSize/$width;
} else {
$ratio = $this->maxSize/$height;
}
$this->thumbwidth = round($width * $ratio);
$this->thumbheight = round($height * $ratio);
}
protected function createImageResource() {
if ($this->imageType == 'jpeg') {
return imagecreatefromjpeg($this->original);
} elseif ($this->imageType == 'png') {
return imagecreatefrompng($this->original);
} elseif ($this->imageType == 'gif') {
return imagecreatefromgif($this->original);
}
}
protected function createThumbnail() {
$resource = $this->createImageResource();
$thumb = imagecreatetruecolor($this->thumbwidth, $this->thumbheight);
imagecopyresampled($thumb, $resource, 0, 0, 0, 0, $this->thumbwidth,
$this->thumbheight, $this->originalwidth, $this->originalheight);
$newname = $this->basename . $this->suffix;
if ($this->imageType == 'jpeg') {
$newname .= '.jpg';
$success = imagejpeg($thumb, $this->destination . $newname, 100);
} elseif ($this->imageType == 'png') {
$newname .= '.png';
$success = imagepng($thumb, $this->destination . $newname, 0);
} elseif ($this->imageType == 'gif') {
$newname .= '.gif';
$success = imagegif($thumb, $this->destination . $newname);
}
if ($success) {
$this->messages[] = "$newname created successfully.";
} else {
$this->messages[] = "Couldn't create a thumbnail for " .
basename($this->original);
}
imagedestroy($resource);
imagedestroy($thumb);
}
}
Class ThumbnailUpload
<?php
namespace PhotoProject;
use PhotoProject\Upload;
require_once 'Upload.php';
require_once 'Thumbnail.php';
class ThumbnailUpload extends Upload {
protected $thumbDestination;
protected $deleteOriginal;
protected $suffix = '_thb';
public function __construct($path, $deleteOriginal = false) {
parent::__construct($path);
$this->thumbDestination = $path;
$this->deleteOriginal = $deleteOriginal;
}
/*
** Setter method for the thumbnail destination
*/
public function setThumbDestination($path) {
if (!is_dir($path) || !is_writable($path)) {
throw new \Exception("$path must be a valid, writable directory.");
}
$this->thumbDestination = $path;
}
public function setThumbSuffix($suffix) {
if (preg_match('/\w+/', $suffix)) {
if (strpos($suffix, '_') !== 0) {
$this->suffix = '_' . $suffix;
} else {
$this->suffix = $suffix;
}
} else {
$this->suffix = '';
}
}
public function allowAllTypes() {
$this->typeCheckingOn = true;
}
protected function createThumbnail($image) {
$thumb = new Thumbnail($image);
$thumb->setDestination($this->thumbDestination);
$thumb->setSuffix($this->suffix);
$thumb->create();
$messages = $thumb->getMessages();
$this->messages = array_merge($this->messages, $messages);
}
protected function moveFile($file) {
$filename = isset($this->newName) ? $this->newName : $file['name'];
$success = move_uploaded_file($file['tmp_name'],
$this->destination . $filename);
if ($success) {
// add a message only if the original image is not deleted
if (!$this->deleteOriginal) {
$result = $file['name'] . ' was uploaded successfully';
if (!is_null($this->newName)) {
$result .= ', and was renamed ' . $this->newName;
}
$this->messages[] = $result;
}
// create a thumbnail from the uploaded image
$this->createThumbnail($this->destination . $filename);
// delete the uploaded image if required
if ($this->deleteOriginal) {
unlink($this->destination . $filename);
}
} else {
$this->messages[] = 'Could not upload ' . $file['name'];
}
}
}
Class Upload
<?php
namespace PhotoProject;
class Upload {
protected $collectednames = [];
protected $typeCheckingOn = true;
protected $notTrusted = ['bin', 'cgi', 'exe', 'js'];
protected $newName;
protected $renameDuplicates;
protected $destination;
protected $max = 8388608;
protected $messages = [];
protected $permitted = [
'image/gif',
'image/png',
'image/jpg'
];
public function __construct($path) {
if (!is_dir($path) || !is_writable($path)) {
throw new \Exception("$path must be a valid, writable directory.");
}
$this->destination = $path;
}
public function setMaxSize($num) {
if (is_numeric($num) && $num > 0) {
$this->max = (int) $num;
}
}
public function allowAllTypes() {
$this->typeCheckingOn = false;
if (!$suffix) {
$this->suffix = ''; // empty string
}
}
public function upload($renameDuplicates = true) {
$this->renameDuplicates = $renameDuplicates;
$uploaded = current($_FILES);
if (is_array($uploaded['name'])) {
// deal with multiple uploads
foreach ($uploaded['name'] as $key => $value) {
$currentFile['name'] = $uploaded['name'][$key];
$currentFile['type'] = $uploaded['type'][$key];
$currentFile['tmp_name'] = $uploaded['tmp_name'][$key];
$currentFile['error'] = $uploaded['error'][$key];
$currentFile['size'] = $uploaded['size'][$key];
if ($this->checkFile($currentFile)) {
$this->moveFile($currentFile);
}
}
} else {
if ($this->checkFile($uploaded)) {
$this->moveFile($uploaded);
}
}
}
public function getMessages() {
return $this->messages;
}
public function collectFilenames() {
return $this->collectednames;
}
public function getMaxSize() {
return number_format($this->max/1024, 1) . ' KB';
}
protected function checkFile($file) {
$accept = true;
if ($file['error'] != 0) {
$this->getErrorMessage($file);
// stop checking if no file submitted
if ($file['error'] == 4) {
return false;
} else {
$accept = false;
}
}
if (!$this->checkSize($file)) {
$accept = false;
}
if ($this->typeCheckingOn) {
if (!$this->checkType($file)) {
$accept = false;
}
}
if ($accept) {
$this->checkName($file);
}
return $accept;
return true;
}
protected function checkName($file) {
$this->newName = null;
$nospaces = str_replace(' ', '_', $file['name']);
if ($nospaces != $file['name']) {
$this->newName = $nospaces;
}
$extension = pathinfo($nospaces, PATHINFO_EXTENSION);
if (!$this->typeCheckingOn && !empty($this->suffix)) {
if (in_array($extension, $this->notTrusted) || empty($extension)) {
$this->newName = $nospaces . $this->suffix;
}
}
if ($this->renameDuplicates) {
$name = isset($this->newName) ? $this->newName : $file['name'];
$existing = scandir($this->destination);
if (in_array($name, $existing)) {
// rename file
$basename = pathinfo($name, PATHINFO_FILENAME);
$extension = pathinfo($name, PATHINFO_EXTENSION);
$i = 1;
do {
$this->newName = $basename . '_' . $i++;
if (!empty($extension)) {
$this->newName .= ".$extension";
}
} while (in_array($this->newName, $existing));
}
}
}
protected function getErrorMessage($file) {
switch($file['error']) {
case 1:
case 2:
$this->messages[] = $file['name'] . ' is too big: (max: ' .
$this->getMaxSize() . ').';
break;
case 3:
$this->messages[] = $file['name'] . ' was only partially
uploaded.';
break;
case 4:
$this->messages[] = 'No file submitted.';
break;
default:
$this->messages[] = 'Sorry, there was a problem uploading ' .
$file['name'];
break;
}
}
protected function checkSize($file) {
if ($file['error'] == 1 || $file['error'] == 2 ) {
return false;
} elseif ($file['size'] == 0) {
$this->messages[] = $file['name'] . ' is an empty file.';
return false;
} elseif ($file['size'] > $this->max) {
$this->messages[] = $file['name'] . ' exceeds the maximum size
for a file (' . $this->getMaxSize() . ').';
return false;
} else {
return true;
}
}
protected function checkType($file) {
if (in_array($file['type'], $this->permitted)) {
return true;
} else {
if (!empty($file['type'])) {
$this->messages[] = $file['name'] . ' is not permitted type of file.';
return false;
}
}
}
protected function moveFile($file) {
$filename = isset($this->newName) ? $this->newName : $file['name'];
$success = move_uploaded_file($file['tmp_name'],
$this->destination . $filename);
if ($success) {
// add the amended filename to the array of uploaded files
$this->filenames[] = $filename;
$result = $file['name'] . ' was uploaded successfully';
if (!is_null($this->newName)) {
$result .= ', and was renamed ' . $this->newName;
}
$this->messages[] = $result;
} else {
$this->messages[] = 'Could not upload ' . $file['name'];
}
}
}
I'm trying to upload a file in my symfony2 project by using a simple Form.
I did read the official doc of symfony but Id want only move my file to directory and update a field in a db table (called user) not create an entity for the file. I use an example I succeed to upload but in .tmp extension (ex. phpXXX.tmp). Any Ideas please.
here my code :
Document.php:
use Symfony\Component\HttpFoundation\File\File;
use Symfony\Component\HttpFoundation\File\UploadedFile;
class Document
{
private $file;
private $subDir;
private $filePersistencePath;
/** #var string */
protected static $uploadDirectory = '%kernel.root_dir%/../styles/images';
static public function setUploadDirectory($dir)
{
self::$uploadDirectory = $dir;
}
static public function getUploadDirectory()
{
if (self::$uploadDirectory === null) {
throw new \RuntimeException("Trying to access upload directory for profile files");
}
return self::$uploadDirectory;
}
public function setSubDirectory($dir)
{
$this->subDir = $dir;
}
public function getSubDirectory()
{
if ($this->subDir === null) {
throw new \RuntimeException("Trying to access sub directory for profile files");
}
return $this->subDir;
}
public function setFile(File $file)
{
$this->file = $file;
}
public function getFile()
{
return new File(self::getUploadDirectory() . "/" . $this->filePersistencePath);
}
public function getOriginalFileName()
{
return $this->file->getClientOriginalName();
}
public function getFilePersistencePath()
{
return $this->filePersistencePath;
}
public function processFile()
{
if (! ($this->file instanceof UploadedFile) ) {
return false;
}
$uploadFileMover = new UploadFileMover();
$this->filePersistencePath = $uploadFileMover->moveUploadedFile($this->file, self::getUploadDirectory(),$this->subDir);
}
}
UploadFileMover
use Symfony\Component\HttpFoundation\File\UploadedFile;
class UploadFileMover {
public function moveUploadedFile(UploadedFile $file, $uploadBasePath, $relativePath) {
$originalName = $file->getFilename();
// use filemtime() to have a more determenistic way to determine the subpath, otherwise its hard to test.
// $relativePath = date('Y-m', filemtime($file->getPath()));
$targetFileName = $relativePath . DIRECTORY_SEPARATOR . $originalName;
$targetFilePath = $uploadBasePath . DIRECTORY_SEPARATOR . $targetFileName;
$ext = $file->getExtension();
$i = 1;
while (file_exists($targetFilePath) && md5_file($file->getPath()) != md5_file($targetFilePath)) {
if ($ext) {
$prev = $i == 1 ? "" : $i;
$targetFilePath = $targetFilePath . str_replace($prev . $ext, $i++ . $ext, $targetFilePath);
} else {
$targetFilePath = $targetFilePath . $i++;
}
}
$targetDir = $uploadBasePath . DIRECTORY_SEPARATOR . $relativePath;
if (!is_dir($targetDir)) {
$ret = mkdir($targetDir, umask(), true);
if (!$ret) {
throw new \RuntimeException("Could not create target directory to move temporary file into.");
}
}
$file->move($targetDir, basename($targetFilePath));
return str_replace($uploadBasePath . DIRECTORY_SEPARATOR, "", $targetFilePath);
}
}
controller :
public function uploadImgAction(Request $req) {
if ($req->getMethod() == 'POST') {
$status = 'success';
$uploadedURL = '';
$message = 'Image modifiée';
$image = $req->files->get('fileselect');
if (($image instanceof UploadedFile) && ($image->getError() == '0')) {
if ($image->getSize() < 2000000) {
$originalName = $image->getClientOriginalName();
$name_array = explode('.', $originalName);
$file_type = $name_array[sizeof($name_array) - 1];
$valid_filetypes = array('jpg', 'jpeg', 'bmp', 'png');
if (in_array(strtolower($file_type), $valid_filetypes)) {
//télécharegement du fichier
//Start Uploading File
$document = new Document();
$document->setFile($image);
$document->setSubDirectory('uploads');
$document->processFile();
$uploadedURL=$uploadedURL = $document->getUploadDirectory() . DIRECTORY_SEPARATOR . $document->getSubDirectory() . DIRECTORY_SEPARATOR . $image->getBasename();
} else {
$status = 'echoue';
$message = 'Seuls les extensions png, jpg, jpeg et bmp sont acceptées';
}
} else {
$status = 'echoue';
$message = 'La taille du fichier dépasse 2MB';
}
} else {
$status = 'echoue';
$message = 'Une erreur de télechargement';
}
return $this->render('PIRecrutementBundle:xx:xxx.html.twig');
//return new Response($uploadedUrl);
} else {
return $this->render('xxxBundle:xx:xxx.html.twig');
}
}
Exactly as Tomasz Turkowski said the solution is to change the base-name of the file by its real name using $file->getClientOriginalName( in class UploadFileMover.
class UploadFileMover {
public function moveUploadedFile(UploadedFile $file, $uploadBasePath, $relativePath)
{
// $originalName = $file->getFilename();
$originalName = $file->getClientOriginalName();
// use filemtime() to have a more determenistic
Without changing anything like .tmp to some other extention or the original name, you can still store the same obtained path in DB. I think you can write a query to store the path in DB after this statement in your controller
$uploadedURL=$uploadedURL = $document->getUploadDirectory() . DIRECTORY_SEPARATOR . $document->getSubDirectory() . DIRECTORY_SEPARATOR . $image->getBasename();
By using the variable $uploadURL like
{
//in your methodAction
"Update [YOUR TABLE] SET [PATHcolomn]=".$uploadURL." WHERE USERid=".$user->getUid()." "
$path= "SELECT [PATHcolomN] FROM [YOUR TABLE] WHERE USERid=".$user->getUid()." "
$this->data['path']=$path;
return $this->data;
}
After Updating, you can fetch this path in the place of <img src= {{ path }} >
I am using windows, Mysql DB, PHP
I am building the Joomla Component whose one of the functionality is to synchronize the folders
I want to sync two folders of different name.. How can I do this? It has to be dne in the same machine, no two different servers are involved in it..
How to sync two folders in PHP?
UPDATED
IN Context of Alex Reply
What if i am editing any .jpg file in one folder and saving it with same name as it has, also this file is already present in other folder. And I want this edited pic to be transfered to the other folder.? also I have Joomla's nested file structured to be compared
UPDATE 2
I have a recursive function which will output me the complete structure of folder... if u can just use it to concat ur solution in...
<?
function getDirectory($path = '.', $ignore = '') {
$dirTree = array ();
$dirTreeTemp = array ();
$ignore[] = '.';
$ignore[] = '..';
$dh = #opendir($path);
while (false !== ($file = readdir($dh))) {
if (!in_array($file, $ignore)) {
if (!is_dir("$path/$file")) {
$stat = stat("$path/$file");
$statdir = stat("$path");
$dirTree["$path"][] = $file. " === ". date('Y-m-d H:i:s', $stat['mtime']) . " Directory == ".$path."===". date('Y-m-d H:i:s', $statdir['mtime']) ;
} else {
$dirTreeTemp = getDirectory("$path/$file", $ignore);
if (is_array($dirTreeTemp))$dirTree = array_merge($dirTree, $dirTreeTemp);
}
}
}
closedir($dh);
return $dirTree;
}
$ignore = array('.htaccess', 'error_log', 'cgi-bin', 'php.ini', '.ftpquota');
$dirTree = getDirectory('.', $ignore);
?>
<pre>
<?
print_r($dirTree);
?>
</pre>
I just ran this, and it seems to work
function sync() {
$files = array();
$folders = func_get_args();
if (empty($folders)) {
return FALSE;
}
// Get all files
foreach($folders as $key => $folder) {
// Normalise folder strings to remove trailing slash
$folders[$key] = rtrim($folder, DIRECTORY_SEPARATOR);
$files += glob($folder . DIRECTORY_SEPARATOR . '*');
}
// Drop same files
$uniqueFiles = array();
foreach($files as $file) {
$hash = md5_file($file);
if ( ! in_array($hash, $uniqueFiles)) {
$uniqueFiles[$file] = $hash;
}
}
// Copy all these unique files into every folder
foreach($folders as $folder) {
foreach($uniqueFiles as $file => $hash) {
copy($file, $folder . DIRECTORY_SEPARATOR . basename($file));
}
}
return TRUE;
}
// usage
sync('sync', 'sync2');
You simply give it a list of folders to sync, and it will sync all files. It will attempt to skip files that appear the same (i.e. of whom their hash collides).
This however does not take into account last modified dates or anything. You will have to modify itself to do that. It should be pretty simple, look into filemtime().
Also, sorry if the code sucks. I had a go at making it recursive, but I failed :(
For a one way copy, try this
$source = '/path/to/source/';
$destination = 'path/to/destination/';
$sourceFiles = glob($source . '*');
foreach($sourceFiles as $file) {
$baseFile = basename($file);
if (file_exists($destination . $baseFile)) {
$originalHash = md5_file($file);
$destinationHash = md5_file($destination . $baseFile);
if ($originalHash === $destinationHash) {
continue;
}
}
copy($file, $destination . $baseFile);
}
It sounds like you just want to copy all files from one folder to another. The second example will do this.
I using this, and it seems to work, also make new dir if not exist .....
//sync the files and folders
function smartCopy($source, $dest, $options=array('folderPermission'=>0755,'filePermission'=>0755))
{
//$result = false;
if (is_file($source)) {
if ($dest[strlen($dest)-1]=='/') {
if (!file_exists($dest)) {
cmfcDirectory::makeAll($dest,$options['folderPermission'],true);
}
$__dest=$dest."/".basename($source);
} else {
$__dest=$dest;
}
$result = copy($source, $__dest);
chmod($__dest,$options['filePermission']);
} elseif(is_dir($source)) {
if ($dest[strlen($dest)-1]=='/') {
if ($source[strlen($source)-1]=='/') {
//Copy only contents
} else {
//Change parent itself and its contents
$dest=$dest.basename($source);
#mkdir($dest);
chmod($dest,$options['filePermission']);
}
} else {
if ($source[strlen($source)-1]=='/') {
//Copy parent directory with new name and all its content
#mkdir($dest,$options['folderPermission']);
chmod($dest,$options['filePermission']);
} else {
//Copy parent directory with new name and all its content
#mkdir($dest,$options['folderPermission']);
chmod($dest,$options['filePermission']);
}
}
$dirHandle=opendir($source);
while($file=readdir($dirHandle))
{
if($file!="." && $file!="..")
{
if(!is_dir($source."/".$file)) {
$__dest=$dest."/".$file;
} else {
$__dest=$dest."/".$file;
}
echo "$source/$file ||| $__dest<br />";
$result=smartCopy($source."/".$file, $__dest, $options);
}
}
closedir($dirHandle);
} else {
$result=false;
}
return $result;
}
//end of function
echo smartCopy('media', 'mobile/images');
function recurse_copy($src,$dst) {
$dir = opendir($src);
#mkdir($dst);
while(false !== ( $file = readdir($dir)) ) {
if (( $file != '.' ) && ( $file != '..' )) {
if ( is_dir($src . '/' . $file) ) {
recurse_copy($src . '/' . $file,$dst . '/' . $file);
}
else {
if(md5_file($src . '/' . $file) !== md5_file($dst . '/' . $file))
{
echo 'copying' . $src . '/' . $file; echo '<br/>';
copy($src . '/' . $file, $dst . '/' . $file);
}
}
}
}
closedir($dir);
}
If its on a Linux/Posix system then (depending on what access you have) it may be a lot simpler / faster to:
$chk=`rsync -qrRlpt --delete $src $dest`;
C.