Can I add user ID to the file name in file upload? - php

I would like to add user ID to file name in file upload. I tried this:
$date=date("Y-m-d");
$id=mysql_insert_id();
//Abstract File codes
$info = pathinfo($_FILES['abstract']['name']);
$ext = $info['extension']; // get the extension of the file
$newname = $id."_Abstract.".$ext;
$target = "application/abstracts/"; $target = $target .$newname;
if (empty($ext))
{ $abstract='' ;}
else $abstract=$newname;
But I only get 0 for ID.
I can display $name but $id is not working. Is it because I do not have an input for $id on my form? Thank you. I should also mention that the user is filling out an application form (for the first time) and attaching files on the same page. I had the file upload after the application was submitted I don;t think I would have problem call the $id. But since everything is on one page I might be calling an empty $id.

Related

How to delete image in database also in source folder

Can any one help me how to delete the image inside the folder?
this my code for deleting the image inside the database and its working
<?php
require('connection/dbconn.php');
if(ISSET($_POST['id'])){
foreach ($_POST['id'] as $id){
$dbconn->query("delete from `uploading` where `id` = '$id'");
}
}
?>
For deleting file with PHP, you have to use unlink function.
But you have to also provide a filepath, which is in your case should consists from upload directory path and fileID (which is $_POST['id']?)
/**
* Do user permissions check for this operation before going further
*/
foreach ($_POST['id'] as $fileId) {
$filePath = "/path/to/upload/dir/$fileId";
if (file_exists($filePath)) {
unlink($filePath);
}
}
Don't forget to make security and data consistency checks. For example, that the user, that sent this request for deleting has enough rights for it.
To delete the image from server, you will have to pass theimageName variable to your PHP script, and then you can delete the file using built-in function unlink():
$path = //your path to the upload images
unlink( $path . $imageName);
unlink( $path . 'Thumbnails/' . $imageName); //if also have thumbnail
You are interacting with your server file system, you'll want to be sure and sanitize the variables (prevent someone from using ../../../ to get to unwanted parts of your file system).
$imageName= str_replace( array( '..', '/', '\\', ':' ), '', $imageName);
You should sanitize the variables to make sure you escape .. characters in the filename otherwise you could something like "../../../public/index.php
Update:
You would have to store the name of an image in the database and create a hidden field in your delete form. While deleting, get the image name as $image = $_POST['image']; and then follow the unlink process.
Select image name from db or send image name with id
Use unlink function to delete file image
unlink('/path-to-upload-dir/' . $_POST['imagename']);

php - rand() update image with the name of the previous one

I have a table CRUD that display my database.
When I upload an image in my image folder I generate a random name of numbers with that function rand()
Here is what I have coded :
My upload function
function importer_image()
{
if(isset($_FILES["image"]))
{
$extension = explode('.', $_FILES['image']['name']);
$new_name = rand() . '.' . $extension[1];
$destination = './upload/' . $new_name;
move_uploaded_file($_FILES['image']['tmp_name'], $destination);
return $new_name;
}
}
My upload php
if($_POST["operation"] == "Ajouter")
{
$image = '';
if($_FILES["image"]["name"] != '')
{
$image = importer_image();
}
The problem is then when I code the update function, the substitued image stays in my folder and the new one has a new name generated. In order to avoid this, I would like to create a condition that says if $image !='' 1/ erase the old file 2/ upload the new file and keep the same name than the deleted image.
So I'm trying to create an update php process that would 1/ delete unlink() 2/ upload the new image with the name of the previous image.
In order to delete the old image and maintain new name of image as previous, you have to take a hidden input in your form which contain your uploaded image name.
For e.g :
<input type="hidden" name="old-image" value="here is your previous image">
Now when your upload function will hit then you can get previous image name by request and can delete or maintain new image as previous.
if($_FILES['image']['name'] != '') {
$old_image = $_POST['old-image']; // get old image
$new_name = $old_image; // make new image name as previous
unlink('/upload/'.$old_image); // remove old image from folder
$destination = './upload/' . $new_name;
move_uploaded_file($_FILES['image']['tmp_name'], $destination);
return $new_name;
} else {
//if there is no image uploaded in the form then it will maintain old image
return $new_name= $_POST['old-image'];
}
Hope it will help you.
Your code to get extension works only if you have just one dot in the uploaded filename, it won't work for example on image_a.1.jpg. Use instead:
$extension = strrchr($_FILES['image']['name'],'.');
Also, using rand() for naming will eventually give you a headache when it generates the same number the second time and the uploaded image will overwrite the old one or not get saved, possibly producing error showing the user your full server save path. I'd use some hashing, like:
$new_name = md5($_FILES['image']['name'] . time());
If you need to save the file name as int, use crc32() instead of md5(). You could convert md5() result to int, but that would produce a very long int (128bit) that might not fit in your database or even PHP code.

How do I replace a file on Laravel's file system

I have a form which accepts a resume, and I would like the user to be able to upload files. I got this route to work, however, I want to replace the files uploaded by that user (I rename the file with their last name and the current time). My code is below:
$file = $request->file('cv');
$fileName = $user->id . "+" . date("Y-m-d H:i:s");
$destinationPath = config('app.CVDestinationPath') . "/" . $fileName . "." . $file->getClientOriginalExtension();
$uploaded = Storage::put($destinationPath, file_get_contents($file->getRealPath()));
if ($uploaded) { //update the database
dd("DONE");
}
So if a user has an id of 2, and he uploads two files. I will have two files associated with that user. I want to replace any file with the id of 2 if it exists. Also what is the max file size upon a post request I can store?
Can anyone provide any guidance?

White empty images after PHP upload and MySQL insertion

I have created a PHP and MySQL script which successfully uploads submitted images via PHP to a folder on my server, and then adds the filename with extension to my MySQL database.
With an FTP program I can see the submitted image inside the correct folder on my server with its correct file size. However, when I type the file path of the newly uploaded image (http://xxxxxx.com/images/image.jpg) into my browser, I get a blank page. Also when I try to import the image onto a website, nothing shows up.
However, when I re-download the image via the FTP program onto my computer, I can see that the image is TOTALLY OK. What am I missing?
Excerpts of my code are below:
<?php
// getting current post id and slug
$pid = $_POST['pid'];
$slug = $_POST['slug'];
//This is the directory where images will be saved
$target = '../company/'.$slug.'/images/';
$target = $target . basename( $_FILES['image']['name']);
//This gets all the other information from the form
$pic = ($_FILES['image']['name']);
$fileTmpLoc = ($_FILES["image"]["tmp_name"]);
$extract = explode(".", $pic);
$fileExt = end($extract);
list($width, $height) = getimagesize($fileTmpLoc);
if($width < 10 || $height < 10){
header("location: ../message.php?msg=ERROR: That image has no dimensions");
exit();
}
$rename = rand(100000000000,999999999999).".".$fileExt;
// check for correct filetype
if (!preg_match("/\.(gif|jpg|png)$/i", $pic) ) {
header("location: ../message.php?msg=ERROR: incorrect filetype");
exit();
}
include_once "../database-connect.php";
//Writes the information to the database
mysqli_query($dbconnection,"UPDATE companies SET picture='$rename' WHERE ID='$pid'") ;
//Writes the photo to the server
if(move_uploaded_file($fileTmpLoc, "../company/'.$slug.'/images/$rename"))
{
.... etc
What am I missing that it does not show up in the browser?
Maybe the path is not what you think it is when you try to link to the image or when you try to open it.
Note that this looks very wrong:
if(move_uploaded_file($fileTmpLoc, "../company/'.$slug.'/images/$rename"))
This will add two quotes and two dots to your path, so if $slug is some_company, the path will be:
/company/'.some_company.'/images/123456789.jpg
Perhaps you don't see or didn't notice that in your ftp program.
Also note that you have an sql injection problem, you should switch to prepared statements with bound variables.
Problem was indeed the URL output structure. Have changed it, like jeroen suggested:
if(move_uploaded_file($fileTmpLoc, "../images/$rename"))
Works fine now

Create profile picture uploader in zend framework

I have recently started working on zend framework. I want to upload a profile picture and rename & re-size it. Am using the code below. with this am able to upload but am not able to rename and am not getting a way to re-size the uploaded file.
if($this->getRequest()->isPost())
{
if(!$objProfilePictureForm->isValid($_POST))
{
//return $this->render('add');
}
if(!$objProfilePictureForm->profile_pic->receive())
{
$this->view->message = '<div class="popup-warning">Errors Receiving File.</div>';
}
if($objProfilePictureForm->profile_pic->isUploaded())
{
$values = $objProfilePictureForm->getValues();
$source = $objProfilePictureForm->profile_pic->getFileName();
//to re-name the image, all you need to do is save it with a new name, instead of the name they uploaded it with. Normally, I use the primary key of the database row where I'm storing the name of the image. For example, if it's an image of Person 1, I call it 1.jpg. The important thing is that you make sure the image name will be unique in whatever directory you save it to.
$new_image_name = 'new';
//save image to database and filesystem here
$image_saved = move_uploaded_file($source, '../uploads/thumb'.$new_image_name);
if($image_saved)
{
$this->view->image = '<img src="../uploads/'.$new_image_name.'" />';
$objProfilePictureForm->reset();//only do this if it saved ok and you want to re-display the fresh empty form
}
}
}
To Rename a file while uploading, you will have to add the "Rename-Filter" to your file-form-element. The class is called Zend_Filter_File_Rename.
// Create the form
$form = new Zend_Form();
// Create an configure the file-element
$file = new Zend_Form_Element_File('file');
$file->setDestination('my/prefered/path/to/the/file') // This is the path where you want to store the uploaded files.
$file->addFilter('Rename', array('target' => 'my_new_filename.jpg')); // This is for the filename
$form->addElement($file);
// Submit-Button
$form->addElement(new Zend_Form_Element_Submit('save');
// Process postdata
if($this->_request->isPost())
{
// Get the file and store it within the specified destination with the specified name.
$file->receive();
}
To make the filename dynamically you may name it with a timestamp or something. You may also apply the Rename-filter within your post-data-processing before the call of $file->receive(). This could be useful if you insert a row into a table and want to name the file with the id of the just inserted row.
Since you want to store a profile picture you could get the id of the user from your db and name the pic with that id.

Categories