How to validate an image before saving in a file - php

I have a function that saves the image in the respective folder.
I want to check if the image already exist in the folder , first with name if the name are same then with the SHA1 of the image
My current function looks something like this
function descargarImagen($id,$url,$pais1)
{
$ruta = rutaBaseImagen($id,$_POST['pais']);
$contenido = file_get_contents($url);
$ext = explode('.', $url);
$extension = $ext[count($ext) -1];
$imagen['md5'] = md5($contenido);
$imagen['sha1'] = sha1($contenido);
$imagen['nombre'] = $imagen['md5'].'.'.$extension;
$ficherof = $pais[$pais1]['ruta_imagenes'].'/'.$ruta.'/'.$imagen['nombre'];
$ficherof = str_replace('//', '/', $ficherof);
//Here before putting the file I want to check if the image already exist in the folder
file_put_contents($ficherof, $contenido);
$s = getimagesize($ficherof);
$imagen['mime'] = $s["mime"];
$imagen['size'] = $s[0].'x'.$s[1];
$imagen['url'] = $urlbase_imagenes.'/'.$ruta.'/'.$imagen['nombre'];
$imagen['url'] = str_replace('//', '/', $imagen['url']);
$imagen['date'] = time();
$imagen['fichero'] = $ficherof;
return $imagen;
}
I am trying to validate in two ways
1.If the name of the image is present in the folder or not .
2.If present then check if the image is same or different , because there could be new image but same name
Any suggestion will be appreciated
Thanks in Advance

You can use this,
// Check if file already exists
if (file_exists($target_file)) {
//echo "Sorry, file already exists.";
/**
* validate images that are different but have same name
* we can use base64_encode function to compare the old and new image
* basics: http://php.net/manual/en/function.base64-encode.php
* online conversion help: http://freeonlinetools24.com/base64-image
*/
$base64_encoded_new_image=base64_encode(file_get_contents($name_of_your_new_image_that_you_want_to_upload));
$base64_encoded_old_image=base64_encode(file_get_contents($name_of_the_image_that_already_exists));
if ($base64_encoded_new_image!=$base64_encoded_old_image) {
/** so the images are actually not same although they have same name
* now do some other stuffs
*/
}
}
for more information please visit http://www.w3schools.com/php/php_file_upload.asp

The hint given by this comment:
//Here before putting the file I want to check if the image already exist in the folder
makes me think you're asking for file_exists, which is the first thing that's shown if you search for "php file exist" in any search engine...

Related

PHP - Simple script for image compression with pngquant

:) i found this 1 line of code in another post which successfully compresses the image using pngquant. the thing is, it outputs the optimised image with a different name (obviously to preserve the original).
im trying to find a way to:
a) add a minimum quality parameter of 60
b) use an if/else statement to to allow the user to choose to overwrite the existing file or output a new optimised image (of a user specified name)
thank you! ntlri - not to long read it
<?php system('pngquant --quality=85 image.png'); ?>
so what i have tried is the following.. for some reason the single quotes need to be double quotes to parse the variables correctly..
<?php
$min_quality = 60; $max_quality = 85;
$keep_original = 'dont_keep';
if ($keep_original == 'keep') {
$image_name = 'image.png';
$path_to_image = 'images/' . $image_name;
$new_file = 'image2.png';
$path_to_new_image = 'images/' . $new_file;
// don't know how to output to specified $new_file name
system("pngquant --quality=$min_quality-$max_quality $path_to_image");
} else {
$image_name = 'image.png';
$path_to_image = 'images/' . $image_name;
// don't know if you can overwrite file by same name as additional parameter
system("pngquant --quality=$min_quality-$max_quality $path_to_image");
// dont't know how you get the name of the new optimised image
$optimised_image = 'images/' . $whatever_the_optimised_image_is_called;
rename($optimised_image, $image_name);
unlink($optimised_image);
}
?>
from the docs of this program :
The output filename is the same as the input name except that\n\ it
ends in \"-fs8.png\", \"-or8.png\" or your custom extension
so , for this question:
// don't know how to output to specified $new_file name
system("pngquant --quality=$min_quality-$max_quality $path_to_image");
to choose a new name, assume you are compress image name.png :
--ext=_x.png
this will create new image called name_x.png
so , your $new_file would be just a suffix ,
$new_file = '_x.png'; // to choose new file name name_x.png
// don't know if you can overwrite file by same name as additional
parameter
as mentioned in the program docs , the new file name will be suffixed by either -fs8.png or -or8.png , so you may rename the file which will produced with this suffix , OR simply set the --ext option to : .png and this will append to the original file
--ext=.png
for more details, check the repository
i spoke to pornel whos the chappie that developed pngquant. its actually a lot simpler than all that i wrote that before...
! important - it is very important to use escapeshellarg() else people can take over your server by uploading a file with a special filename apparently.
$image_name = 'image.png';
$target_file = 'images/' . $image_name;
$existing_image = 'image.png'; // image already on server if applicable
$keep = 'keep';
$target_escaped = escapeshellarg($target_file);
if ($keep == 'keep') {
// process/change output file to image_compressed.png keeping both images
system("pngquant --force --quality=70 $target_escaped --ext=_compressed.png");
$remove_ext = substr($newFileName, 0 , (strrpos($newFileName, ".")));
// $new_image is just the name (image_compressed.png) if you need it
$new_image = $remove_ext . '_compressed.png';
// remove old file if different name
if ($existing_image != $newFileName) {
$removeOld = '../images/' . $existing_image;
unlink($removeOld);
} // comment out if you want to keep existing file
} else {
// overwrite if file has the same name
system("pngquant --force --quality=70 $target_escaped --ext=.png");
// remove old file if different name
if ($existing_image != $newFileName) {
$removeOld = '../images/' . $existing_image;
unlink($removeOld);
}
$new_image = $newFileName;
}
to override same name use this command
pngquant.exe --ext=.png --force input.png
so the output name will remain input.png

Unable to upload Image on live site

I have a site where there is member registration. All data will be saved but I get only this error:
Could not move the file "/tmp/phpa4pH3I" to "/home/sporter/public_html/someonect.org/uploads\membersImages/33921.jpg" ()
My code is like this
public function store(){
// dd(Input::all());
$validator = Validator::make(Input::all(), Members::$rules);
if($validator->passes()):
$first_name = Input::get('mem_firstName');
$last_name = Input::get('mem_lastName');
$email = Input::get('mem_email');
$image = Input::get('mem_image');
$phone = Input::get('mem_phone');
$occupation = Input::get('mem_occupation');
$citizen = Input::get('mem_citizen');
$address = Input::get('mem_address');
$destinationPathImage = str_replace('PROJECT\\', '', base_path().'\uploads\membersImages\\') ;
//Generating a random name
$randomName = rand(11111,99999);
//Renaming the image
$ImageName = $randomName.'.'.'jpg'; // renameing image
$imagePath = $destinationPathImage.$ImageName;
Members::create([
'first_name'=>$first_name,
'last_name'=>$last_name,
'email'=>$email,
'image'=>$imagePath,
'phone'=>$phone,
'occupation' => $occupation,
'citizen' => $citizen,
'address'=>$address
]);
...
I don't understrand clearly your str_replace part, but if you setup your url in config properly, you don't need this.
I'm using this kind of upload for an image:
if($request->hasFile('mem_image')) {
$file = $request->file('mem_image');
$ext = $request->file('mem_image')->getClientOriginalExtension();
$filename = rand(11111,99999). '.' . $ext;
$file->move('./uploads/', $filename);
$member->mem_image = '/uploads/' . $filename;
$member->save();
}
In case, your uploads directory is in your public folder.
If your script have permission for writing in target folder. The problem can be only in path. Check what contain in variable $destinationPathImage. It must be correct and exists path. In your error message I see problem with slashes.
also think that it's be cool to check exists of destination folder and file exists before save to database record with path of file.
You're not using the proper slashes.
Replace \uploads\membersImages\\ with /uploads/membersImages/.
If it still not working, please double check the permissions in that folder using the is_writable php function. However, have in mind that the is_writable function is not working properly on windows platforms.

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

PHP Delete file

I am trying to develop a user page for a forum and I'm kinda struggling with the image upload.
The problem is that I would like to limit the user to only be able to upload one single image, but be able to change it anytime. so basically, I would like to either overwrite the existing file either delete the old picture and add a new one instead.
At this point I have a piece of code that adds a timestamp at the end of the file (which I don't really need actually).
CODE:
if(isset($_POST['upload']))
{
$extension=strstr($_FILES['uploadedfile']['name'], ".");
$filename = "_/userfiles/userpics/".basename($_FILES['uploadedfile']['name'],
$extension);
$target = "_/userfiles/userpics/".basename($_FILES['uploadedfile']['name']);
$valid = true;
if(file_exists($target))
{
$filename = $filename . time();
$target = $filename . $extension;
}
if($valid)
{
// move the file into the folder of our choise
move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target);
$img_sql = "INSERT INTO sp_userimage (imageid, path, id) value ('', '".$target."', '".$_SESSION['userid']."')";
$img_result = mysql_query($img_sql);
echo "upload sucessfull";
}
Make use of unlink() in PHP Manual.
if(file_exists($target))
{
unlink($target); // deletes file
//$filename = $filename . time();
//$target = $filename . $extension;
}
I think this might be a bit better suited for you. You might have to edit it a tad.
if($valid)
{
// Check if user has a file.
$img_check = mysql_query("SELECT * FROM sp_userimage WHERE id = " . (int) $_SESION['user_id']);
if( mysql_num_rows($img_check) > 0 ){
$row = mysql_fetch_object($img_check);
// Delete the file.
unlink($row->path);
}
// move the file into the folder of our choise
move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target);
$img_sql = "INSERT INTO sp_userimage (imageid, path, id) value ('', '".$target."', '".$_SESSION['userid']."')";
$img_result = mysql_query($img_sql);
echo "upload sucessfull";
}
It might be easier to normalize the image type (e.g. only jpegs) and then name the file as the userid. For example:
$target = 'userpics' . DIRECTORY_SEPARATOR . $_SESSION['userid'];
move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target);
This will simply overwrite the old picture with the new one. Given that this type of filename is deterministic, you also don't need to store the filename in the database.
Use unlink() function
read more here PHP unlink
okay ,if u want to delete the file for that particular user only.
then store the filename vs user in some MapTable in db.
mysql_query("CREATE TABLE t_usr_file_map(
usr_id INT NOT NULL ,
file_name VARCHAR(100),
)")
or die(mysql_error());
and at the time of reupload , fetch the filename from the table for that user , unlink it and reupload the fresh one again.
OR,
or u can use PHP file_rename function at the time of upload. rename filename to the userid
rename ( string $oldname , string $newname [, resource $context ] )
and u can always do unlink based on user-id
Its very simple by unlink()
as:
unlink(dirname(__FILE__) . "/../../public_files/" . $filename);
if (file_exists($path))
{
$filename= rand(1,99).$filename;
unlink($oldfile);
}
move_uploaded_file($_FILES['file']['tmp_name'],$filename);

Drupal 7 save user picture programmatically

I have found this script http://d.danylevskyi.com/node/7 which I have used as a starter for the below code.
The goal is to be able to save a user picture:
<?php
define('DRUPAL_ROOT', getcwd());
require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
$uid = 99;
$account = user_load($uid);
// get image information
$image_path = 'public://avatars/upload/b8f1e69e83aa12cdd3d2babfbcd1fe27_4.gif';
$image_info = image_get_info($image_path);
// create file object
$file = new StdClass();
$file->uid = $uid;
$file->uri = $image_path;
$file->filemime = $image_info['mime_type'];
$file->status = 0; // Yes! Set status to 0 in order to save temporary file.
$file->filesize = $image_info['file_size'];
// standard Drupal validators for user pictures
$validators = array(
'file_validate_is_image' => array(),
'file_validate_image_resolution' => array(variable_get('user_picture_dimensions', '85x85')),
'file_validate_size' => array(variable_get('user_picture_file_size', '30') * 1024),
);
// here all the magic :)
$errors = file_validate($file, $validators);
if (empty($errors)) {
file_save($file);
$edit['picture'] = $file;
user_save($account, $edit);
}
?>
A picture is created in sites/default/files/pictures/ with the name picture-99-1362753611.gif
Everything seems correct in the file_managed table except that:
the filename field is empty
the uri field shows public://avatars/upload/b8f1e69e83aa12cdd3d2babfbcd1fe27_4.gif
the status field is set to 0 (temporary)
The picture field in the users table gets updated with the fid of the above mentioned entry.
I would guess that the file_managed table should store the final file (in sites/default/pictures) instead of the original file info and that the users table should link to the one too.
Any idea how I can achieve that? I am quite new to the Drupal API. Thank you.
Edit:
I understand that I am giving the original file to the file_save and user_save functions. But which one actually creates the file in sites/default/pictures/ ?
Try adding the following to your code:
$file->filename = drupal_basename($image_path);
$file->status = FILE_STATUS_PERMANENT;
$file = file_save($file); // Use this instead of your current file_save
Does that help?
------------------ EDIT ------------------
If you want to save a copy of the file in a new location, you can replace the third line above with something like
// Save the file to the root of the files directory.
$file = file_copy($file, 'public://');

Categories