How to unlink image and delete from database using codeigniter in php - php

I have upload images in rooturl + uploads/slider
and image name store in database slider_image.
I want to delete slider_image from databse and also delete from folder.
my folder location :
http://localhost/game/uploads/slider/soccer.jpg
image_name:
soccer.jpg
I got an warning error :
Severity: WarningMessage: unlink(): http does not allow unlinking
my model code:
public function deleteSlider($sliderID)
{
$this->db->delete('slider_tbl',array('slider_id' => $sliderID));
$path = base_url("uploads/slider/".$result[0]->slider_image);
if($this->db->affected_rows() >= 1){
if(unlink($path))
return TRUE;
} else {
return FALSE;
}
}

Try Changing your $path.
$path = base_url("uploads/slider/".$result[0]->slider_image);
to
$path = "./uploads/slider/" . $result[0]->slider_image;

Change
$path = base_url("uploads/slider/".$result[0]->slider_image);
to
$path = FCPATH . "uploads/slider/" . $result[0]->slider_image;

You need to use the path to the file on the server, not the URL, so you need something like:
$path = "/uploads/slider/".$result[0]->slider_image;
without the base_url.

Related

How to copy an image from one folder to another using php

I'm having difficulty in copying an image from one folder to another, now i have seen many articles and questions regarding this, none of them makes sense or work, i have also used copy function but its giving me an error. " failed to open stream: No such file or directory" i think the copy function is only for files. The image i wanna copy is present in the root directory. Can anybody help me please. What i am doing wrong here or is there any other way???
<?php
$pic="somepic.jpg";
copy($pic,'test/Uploads');
?>
You should write your code same as below :
<?php
$imagePath = "/var/www/projectName/Images/somepic.jpg";
$newPath = "/test/Uploads/";
$ext = '.jpg';
$newName = $newPath."a".$ext;
$copied = copy($imagePath , $newName);
if ((!$copied))
{
echo "Error : Not Copied";
}
else
{
echo "Copied Successful";
}
?>
You should have file name in destination like:
copy($pic,'test/Uploads/'.$pic);
For your code, it must be like this:
$pic="somepic.jpg";
copy($pic,'test/Uploads/'.$pic);
Or use function, like this:
$pic="somepic.jpg";
copy_files($pic,'test/Uploads');
function copy_files($file_path, $dest_path){
if (strpos($file_path, '/') !== false) {
$pathinfo = pathinfo($file_path);
$dest_path = str_replace($pathinfo['dirname'], $dest_path, $file_path);
}else{
$dest_path = $dest_path.'/'.$file_path;
}
return copy($pic, $dest_path);
}

PHP - Renaming a file to disallow duplicates

So I am using this script to upload a file to a directory and show it live.
<?php
function UploadImage($settings = false)
{
// Input allows you to change where your file is coming from so you can port this code easily
$inputname = (isset($settings['input']) && !empty($settings['input']))? $settings['input'] : "fileToUpload";
// Sets your document root for easy uploading reference
$root_dir = (isset($settings['root']) && !empty($settings['root']))? $settings['root'] : $_SERVER['DOCUMENT_ROOT'];
// Allows you to set a folder where your file will be dropped, good for porting elsewhere
$target_dir = (isset($settings['dir']) && !empty($settings['dir']))? $settings['dir'] : "/uploads/";
// Check the file is not empty (if you want to change the name of the file are uploading)
if(isset($settings['filename']) && !empty($settings['filename']))
$filename = $settings['filename'] . "sss";
// Use the default upload name
else
$filename = preg_replace('/[^a-zA-Z0-9\.\_\-]/',"",$_FILES[$inputname]["name"]);
// If empty name, just return false and end the process
if(empty($filename))
return false;
// Check if the upload spot is a real folder
if(!is_dir($root_dir.$target_dir))
// If not, create the folder recursively
mkdir($root_dir.$target_dir,0755,true);
// Create a root-based upload path
$target_file = $root_dir.$target_dir.$filename;
// If the file is uploaded successfully...
if(move_uploaded_file($_FILES[$inputname]["tmp_name"],$target_file)) {
// Save out all the stats of the upload
$stats['filename'] = $filename;
$stats['fullpath'] = $target_file;
$stats['localpath'] = $target_dir.$filename;
$stats['filesize'] = filesize($target_file);
// Return the stats
return $stats;
}
// Return false
return false;
}
?>
<?php
// Make sure the above function is included...
// Check file is uploaded
if(isset($_FILES["fileToUpload"]["name"]) && !empty($_FILES["fileToUpload"]["name"])) {
// Process and return results
$file = UploadImage();
// If success, show image
if($file != false) { ?>
<img src="<?php echo $file['localpath']; ?>" />
<?php
}
}
?>
The thing I am worried about is that if a person uploads a file with the same name as another person, it will overwrite it. How would I go along scraping the filename from the url and just adding a random string in place of the file name.
Explanation: When someone uploads a picture, it currently shows up as
www.example.com/%filename%.png.
I would like it to show up as
www.example.com/randomstring.png
to make it almost impossible for images to overwrite each other.
Thank you for the help,
A php noob
As contributed in the comments, I added a timestamp to the end of the filename like so:
if(isset($settings['filename']) && !empty($settings['filename']))
$filename = $settings['filename'] . "sss";
// Use the default upload name
else
$filename = preg_replace('/[^a-zA-Z0-9\.\_\-]/',"",$_FILES[$inputname]["name"]) . date('YmdHis');
Thank you for the help

How to check if a folder exists before creating it in laravel?

I need to know if a folder exists before creating it, this is because I store pictures inside and I fear that the pictures are deleted if overwrite the folder.
The code I have to create a folder is as follows
$path = public_path().'/images';
File::makeDirectory($path, $mode = 0777, true, true);
how can I do it?
See: file_exists()
Usage:
if (!file_exists($path)) {
// path does not exist
}
In Laravel:
if(!File::exists($path)) {
// path does not exist
}
Note: In Laravel $path start from public folder, so if you want to check 'public/assets' folder the $path = 'assets'
With Laravel you can use:
$path = public_path().'/images';
File::isDirectory($path) or File::makeDirectory($path, 0777, true, true);
By the way, you can also put subfolders as argument in a Laravel path helper function, just like this:
$path = public_path('images/');
You can also call this method of File facade:
File::ensureDirectoryExists('/path/to/your/folder')
which creates a folder if it does not exist and if exists, then does nothing
In Laravel 5.x/6 you can do it with Storage Facade:
use Illuminate\Support\Facades\Storage;
$path = "path/to/folder/";
if(!Storage::exists($path)){
Storage::makeDirectory($path);
}
Way -1 :
if(!is_dir($backupLoc)) {
mkdir($backupLoc, 0755, true);
}
Way -2 :
if (!file_exists($backupLoc)) {
mkdir($backupLoc, 0755, true);
}
Way -3 :
if(!File::exists($backupLoc)) {
File::makeDirectory($backupLoc, 0755, true, true);
}
Do not forget to use use Illuminate\Support\Facades\File;
Way -4 :
if(!File::exists($backupLoc)) {
Storage::makeDirectory($backupLoc, 0755, true, true);
}
In this way you have to put the configuration first in config folder
filesystems.php . [Not recommended unless you are using external disks]
The recommended way is to use
if (!File::exists($path))
{
}
See the source code
If you look at the code, it's calling file_exists()
I normally create random folders inside the images for each file this helps a bit in encrypting urls and thus public will find it hardr to view your files by simply typing the url to your directory.
// Check if Logo is uploaded and file in random folder name -
if (Input::hasFile('whatever_logo'))
{
$destinationPath = 'uploads/images/' .str_random(8).'/';
$file = Input::file('whatever_logo');
$filename = $file->getClientOriginalName();
$file->move($destinationPath, $filename);
$savedPath = $destinationPath . $filename;
$this->whatever->logo = $savedPath;
$this->whatever->save();
}
// otherwise NULL the logo field in DB table.
else
{
$this->whatever->logo = NULL;
$this->whatever->save();
}
This is what works great for me
if(!File::exists($storageDir)){
File::makeDirectory($storageDir, 0755, true, true);
$img->save('Filename.'.png',90);
}

MootoolsFancy Upload

i have just come across what i think i need for my front end multi uploader script in joomla.
Mootools fancy upload looks great! but i am having trouble when i uncomment the script that uploads the images inside the uploads folder?
All i have done is uncommented the default script inside the test file and created a folder called uploads which i set to 757 and also tried 777
But for some reason the uploader now returns some strange error about md 5 hash stuff?
eastern_beach_jetty.jpgAn error occured:
Warning: md5_file(/tmp/phpUjHol4) [function.md5-file]: failed to open stream: No such file or directory in /home/user/www.mydomain.com.au/test/server/script.php on line 133
{"status":"1","name":"eastern_beach_jetty.jpg","hash":false}
The fancy uploader website from where i got the script is here http://digitarald.de/project/fancyupload/
Any help on this would be so greatly apprecited,
thank you.
John
Coincidentally, I did the same mistake as you, the reason is that the first move tmp file to the destination folder, and then referring to the tmp file, which no longer exists, because it is in the target folder. I know that the late response, but it was as if someone had the same problem.
Not:
move_uploaded_file($_FILES['Filedata']['tmp_name'], '../uploads/' . $_FILES['Filedata']['name']);
$return['src'] = '/uploads/' . $_FILES['Filedata']['name'];
if ($error) {
(...)
} else {
(...)
// $return['hash'] = md5_file($_FILES['Filedata']['tmp_name']);
// ... and if available, we get image data
$info = #getimagesize($_FILES['Filedata']['tmp_name']);
if ($info) {
$return['width'] = $info[0];
$return['height'] = $info[1];
$return['mime'] = $info['mime'];
}
}
Yes:
if ($error) {
(...)
} else {
(...)
// $return['hash'] = md5_file($_FILES['Filedata']['tmp_name']);
// ... and if available, we get image data
$info = #getimagesize($_FILES['Filedata']['tmp_name']);
if ($info) {
$return['width'] = $info[0];
$return['height'] = $info[1];
$return['mime'] = $info['mime'];
}
}
move_uploaded_file($_FILES['Filedata']['tmp_name'], '../uploads/' . $_FILES['Filedata']['name']);
$return['src'] = '/uploads/' . $_FILES['Filedata']['name'];

Zend_Form_Element_File the move_uploaded_file function don't return anything

I am trying to upload a picture. I have Form_Zend and I use:
$image = new Zend_Form_Element_File('image');
$image->setLabel('Upload an avatar:')
->setMaxFileSize(8388608)
// ->setDestination('./usersImages')
->setDescription('Click Browse and choose an image');
$image->addValidator('Count', false, 1);
$image->addValidator('Size', false, 8388608);
$image->addValidator('Extension', false, 'jpg,jpeg,png,gif');
$this->addElement($image, 'image');
My controller action code:
if ($form->image->isUploaded()) {
$values = $form->getValues();
$source = $form->image->getFileName();
$extention = substr($source, strrpos($source, '.', -1));
$date = date('mdYhisa', time());
$new_image_name = 'avatar_' . $date . '_' . $idUser . $extention;
$destination = "C:\\xampp\\tmp\\Srututututut.png";
$image_saved = move_uploaded_file($source, $destination);
if ($image_saved) {
$data = array(
'img' => $new_image_name,
);
$userDT->update($data, 'id=' . $idUser);
}
}
}
But this move_uploaded_file is not returning nothing :/
What I have done:
Checked if the file is uploading - yes it is in: C:\xampp\htdocs\Story\public\usersImages (if I set destination in this form element) or
C:\xampp\tmp (if I dont set it)
I was wondering about access to this folders but if it save there this images I think it has rights but I set in the apache:
<Directory "C:/xampp/htdocs/Story/public/usersImages">
Allow from All
</Directory>
I was even tried use this function only in C:\xampp\tmp folder:
$source: C:\xampp\tmp\database.png
$destination: C:\xampp\tmp\Srututututut.png
And still nothing :/
Do You have any suggestions?
I think that the problem is with $source = $form->image->getFileName();. The reason is that it will return a name of the file uploaded rather than where it was uploaded to (i.e. its temporary localization).
Thus, I think your source should be as follows:
$fileInfo = $mainForm->image->getTransferAdapter()->getFileInfo();
$source = $fileInfo['image']['tmp_name'];
// to check if the source really points to the uploaded file.
var_dump(file_exists($source));
Ok,
I have no idea why this function is not working. I have changed my idea to set the $form->image destination first in the controller and then rename it and it is working.
Thanks for help guys ;D

Categories