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

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?

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.

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

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.

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

Uploading Files (PDF & Image) With CakePHP

What I am trying to do I have never done before. I am using CakePHP to build a form, I am using the form helper to do this. This all works with inputs and textareas but I am now trying to changed two of my inputs into file upload fields.
This I have done and seems the work, when I debug $this->data['Event']['img'] (The form is call Event). I get the following output :
Array
(
[name] => logo.gif
[type] => image/gif
[tmp_name] => /tmp/phpaU3aBa
[error] => 0
[size] => 7318
)
Now I am guesting here but I would have to save the file to my 'webroot' folder. I have made the path /webroot/eventfiles/img & webroot/eventfiles/pdf - I have started with doing just the image for now, so I can get it to work, but the other file type I will be uploading is a pdf.
Now I have looked at what the CakePHP website as on this but I just says to look at the PHP site and there seems to be a lot of ways to do this, but I am just not sure how to save it. So that I can access it later, e.g. it goes into the webroot folder so that Cake can see it.
Also as a side note, would also need to save the path + filename into the database. This, unless I am wrong, should be easy, just use $this->data['Event']['img']['name'] and that would save that into my database.
Please help? I have been working on this for days. I just can not seem to get my head around file upload. Is there a easy method to do this? E.g like how Cake as HTML & Form helpers, a easy method for saving uploaded files?
Thanks For Any Help You Can Give.
Glenn.
just though that I would post my answer, which fully works. I takes a pdf and jpeg image, from two file input files and then renames then to the given title, supplied by the user in a input text field. With the two vars in $newevent, these are what, with the other inputs, are saved to the database, path and the renamed image.
This code is very simple. The main body of this code come from a post on this site and I have just changed it to use for my use.
If you are also trying to add/upload different file types, e.g. doc or png, all you need to know is the header type for the document you want to upload and add it to the if statement.
Hope this will help someone else!
Glenn.
$pathimg = "/eventfiles/img/";
$pathpdf = "/eventfiles/pdf/";
$dir_pdf = getcwd().$pathpdf;
$dir_img = getcwd().$pathimg;
$PDF_Path = $dir_pdf . $this->data['Event']['pdf']["name"];
$IMG_Path = $dir_img . $this->data['Event']['img']["name"];
$IMG_WithOutSpace = preg_replace('/\s+/', '_', $newevent['title']);
$PDF_WithOutSpace = preg_replace('/\s+/', '_', $newevent['title']);
$newevent['img'] = "/vh/eventfiles/img/" . $IMG_WithOutSpace . ".jpg";
$newevent['pdf'] = "/vh/eventfiles/pdf/" . $PDF_WithOutSpace . ".pdf";
if ((( $this->data['Event']['img']["type"] == "application/pdf") || ( $this->data['Event']['img']["type"] == "image/jpeg"))) {
if (($this->data['Event']['img']["error"] > 0) || ($this->data['Event']['pdf']["error"] > 0)) {
$this->Session->setFlash(__('An error has occured during updating. Please check all the fields.', true), 'default', array('class' => 'error-message'));
$this->redirect($this->referer());
exit();
} else {
move_uploaded_file( $this->data['Event']['img']["tmp_name"], $IMG_Path);
rename($IMG_Path, $dir_img . $IMG_WithOutSpace. ".jpg");
move_uploaded_file( $this->data['Event']['pdf']["tmp_name"], $PDF_Path);
rename($PDF_Path, $dir_pdf . $PDF_WithOutSpace . ".pdf");
$filename= $this->data['Event']['pdf']["name"];
$filename= $this->data['Event']['img']["name"];
}

Categories