How to upload image with random name in databse in codeigniter 4 - php

Like codeigniter 3 encryt_name in file upload
How can I encrypt name of file in codeigniter 4? Help me guys

When retrieving your file you can work with the uploaded file library of CI4 : https://codeigniter4.github.io/userguide/libraries/uploaded_files.html
In this lib you can use the getRandomName() function.
You can generate a cryptographically secure random filename, with the
current timestamp prepended, with the getRandomName() method. This is
especially useful to rename files when moving it so that the filename
is unguessable
https://codeigniter4.github.io/userguide/libraries/files.html?highlight=getrandomname#new-features
You'll eventually get something similar to :
// get files from $_FILES
if($imagefile = $this->request->getFiles())
{
foreach($imagefile['images'] as $img)
{
// check if each file is valid and from an HTTP source
if ($img->isValid() && ! $img->hasMoved())
{
// generate a new random name and move the file
$newName = $img->getRandomName();
$img->move(WRITEPATH.'uploads', $newName);
}
}
}

Related

hashing content of uploaded file in php

I have a upload form and also a Dropzone file uploader beside it where users can upload their .csv files .
I want to check whether the file is new or not.
the check should contain if the contents of file are new or not
I store the file names in database for checking new files, but the problem is when the user rename the same file and upload it again.
My solution is hashing the content of each file and store it beside its name in database.
but I don't know how to hash content of .csv file in php , Laravel.
I've tried using
hash_file('md5' , Request::file('myFileName')->getClientOriginalName());
but it results in file or stream not found.
What is the correct way of checking the new file regardless of its name?
Thanks in advance.
Calculating hash of a file is a correct way to go.
Do something like this:
public function uploadFile() {
// check if upload is valid file (example: request()->file('myFileName')->isValid() )
// calculate hash of a file
$fileHash = sha1_file( request()->file('myFileName')->path() );
//search for file in database and block same file upload (Files is Elequent model)
if( Files::where('hash', $fileHash)->firstOrNull() != null) {
abort(400); // abort upload
}
// do something with file and save hash to DB
}

Save a file to a different folder using php?

I want to know if it is possible to save a file to a different folder once it is opened. My current logic is -
$myfile = $_POST['file']; // gets path of (in this case an image)
$size = getimagesize($myfile); //for some reason I get an error message when this fails
// I'm assuming there is a better way of determining if the file is an image file or not.
if($size)
{
//save file to said file path
}
Try:
if($size)
{
copy($myfile, $newfile); //$newfile - with full path!
}

verify file name at upload with only a given file name

How can i verify a file name when uploading e.g. xyz.xlsx for this specific file and no other? Thus the file is uploaded if and only if its name is xyz with extension xlsx "xyz.xlsx".
If I understand what your looking for, just grab the filename and test it.
Example:
if($_FILES['uploadedfile']['name'] == "xyz.xlsx")
http://us2.php.net/manual/en/features.file-upload.post-method.php
When you do an upload with PHP, you get a $_FILES array (kind of like $_POST). You'll find the original filename in $_FILES['userfile']['name']. You can verify that as MyGlass suggests in his answer.
if($_FILES['uploadedfile']['name'] == "xyz.xlsx")
Additionally, codeignitor provides a file upload class that can be used to eliminate some of the boiler plate of file uploads here: http://ellislab.com/codeigniter/user-guide/libraries/file_uploading.html
Use $this->upload->data() to get the array with the filename info (the key is 'file_name').
$data = $this->upload->data();
if($data['file_name'] == "xyz.xlsx")

Saving a PDF file using PHP

I have a problem with saving PDF files to folders on my server. The code worked at one time and now it doesn't. What I want it to do is to check if someone is trying to upload a PDF when a form is submitted, and if there is a PDF in the file field it uploads it and then saves the path to the mysql database. Code is below:
if (!empty($_FILES['pdf'])){
$idir = "../files/PDF/"; //my directory file is supposed to be saved in
$randomd=rand(0000000,9999999); //creates a random number as filename
$domain = "http://".$_SERVER['HTTP_HOST'];
$file_ext = strrchr($_FILES['pdf']['name'], '.'); grabs file extension. my code checked if the file was a pdf a different way and neither seems to work.
$destination=$randomd.$file_ext; //new filename
if ($file_ext=='pdf') {
move_uploaded_file($_FILES['pdf']['tmp_name'], "$idir" . $destination);
$pdf= $domain."/files/PDF/".$destination; } else { echo("File type not supported.");
mysql_query("UPDATE tbl_listings SET pdf='$pdf' WHERE listing_id='$lid'");
}
The if not empty does not work and it always tries to upload a file, but when I check the folder nothing is in there and it doesnt update the mysql.
$_FILES['pdf'] will never be empty(when the form has been submitted), no matter if a file has been selected or not, it will always return an array.
Check $_FILES['pdf']['error'] , it will be 4 when no file has been uploaded.

PHP - upload and overwrite a file (or upload and rename it)?

I have searched far and wide on this one, but haven't really found a solution.
Got a client that wants music on their site (yea yea, I know..). The flash player grabs the single file called song.mp3 and plays it.
Well, I am trying to get functionality as to be able to have the client upload their own new song if they ever want to change it.
So basically, the script needs to allow them to upload the file, THEN overwrite the old file with the new one. Basically, making sure the filename of song.mp3 stays intact.
I am thinking I will need to use PHP to
1) upload the file
2) delete the original song.mp3
3) rename the new file upload to song.mp3
Does that seem right? Or is there a simpler way of doing this? Thanks in advance!
EDIT: I impimented UPLOADIFY and am able to use
'onAllComplete' : function(event,data) {
alert(data.filesUploaded + ' files uploaded successfully!');
}
I am just not sure how to point THAT to a PHP file....
'onAllComplete' : function() {
'aphpfile.php'
}
???? lol
a standard form will suffice for the upload just remember to include the mime in the form. then you can use $_FILES[''] to reference the file.
then you can check for the filename provided and see if it exists in the file system using file_exists() check for the file name OR if you don't need to keep the old file, you can use perform the file move and overwrite the old one with the new from the temporary directory
<?PHP
// this assumes that the upload form calls the form file field "myupload"
$name = $_FILES['myupload']['name'];
$type = $_FILES['myupload']['type'];
$size = $_FILES['myupload']['size'];
$tmp = $_FILES['myupload']['tmp_name'];
$error = $_FILES['myupload']['error'];
$savepath = '/yourserverpath/';
$filelocation = $svaepath.$name.".".$type;
// This won't upload if there was an error or if the file exists, hence the check
if (!file_exists($filelocation) && $error == 0) {
// echo "The file $filename exists";
// This will overwrite even if the file exists
move_uploaded_file($tmp, $filelocation);
}
// OR just leave out the "file_exists()" and check for the error,
// an if statement either way
?>
try this piece of code for upload and replace file
if(file_exists($newfilename)){
unlink($newfilename);
}
move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $newfilename);

Categories