PHP - How to compare database content to a user file upload? - php

I need to compare the user uploaded a file with the database, but
the uploaded file should not get stored into the database.
So, for example, my database looks like this
NAME CONTENT
KEY helloworld
and the user uploads a text file which contains this:
youhello
So now, since the database and the textfile has the word hello in it
it should output something like matched
I'm having issue implementing this logic
function checking_for_virus($connection){
$name = $_FILES['file']['name'];
$fileContents = file_get_contents($_FILES['file']['tmp_name']);
if(isset($_POST['userFile'])){
if (isset($_FILES) && $_FILES['file']['type']!= 'text/plain') {
echo "<span>File could not be accepted ! Please upload any '*.txt' file.</span>";
exit();
}
/* IMPLEMENTATION OF THE LOGIC TO COMPARE THE FILE FROM THE DATABASE CONTENT*/
}
}
The expected result should be matched since both the database content
and text file has hello in it.
Could anyone please provide me with an explanation to implement this.

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
}

saving a file in php without saving in a folder in yii php

Am saving a file as a long blob in php by first saving it in a folder then to a db, the problem is that the server has write permissions so i would like to save it directly
This is what i have tried (This works perfectly):
if(isset($_POST['image'])){
$id = 0;
$image = $_POST['image'];
$tmp_image = date('YmdHisu').'.jpg';
file_put_contents($tmp_image, base64_decode($image));
$sql = "INSERT INTO fingerprint(template)
VALUES ('".addslashes(file_get_contents($tmp_image))."')";
try
{
$connection=Yii::app()->db;
$command=$connection->createCommand($sql);
$rowCount=$command->execute(); // execute the non-query SQL
echo "saved successifully";
unlink($tmp_image);
}
catch(Exception $ex)
{
echo 'Query failed' , $ex->getMessage();
unlink($tmp_image);
}
}
How can i save this in a blob field in mysql without first having to save it in a folder then saving to db
Let's assume you've sent the file via Android using POST method to your server running Yii1.
First of all the physical file is contained in the $_FILES variable and in the $_POST variable, as you said, contains a string of the file encoded in base 64 format (i write this for a clear answer).
$_FILE DOCUMENTATION
Now this is how you can try to upload the file with the standard MVC yii way using yii code:
It's true that you're uploading your file from an external device but Yii came in your help with CUploadedFile Class:
Call getInstance to retrieve the instance of an uploaded file, and then use saveAs to save it on the server. You may also query other information about the file, including name, tempName, type, size and error.
In particular you should use the function getInstancesByName that returns an array of instances starting with specified array name.
$temp = CUploadedFile::getInstanceByName("image"); // $_FILES['image']
and with this you can access to the file data:
$temp->name; // Name of the file
$temp->type; // Type of the file
$temp->size; // Size of the file
// etc etc..
$temp->saveAs("/your/path/" . $tmp_image . $temp->type); // Save your file
for final you can check if the file was saved and execute your query:
if($temp->saveAs("/your/path/" . $tmp_image . $temp->type)) {
// File is saved you can execute the query for save the record in your db
} else {
// Something went wrong.
}
You can also transfer this logic in a model.
check this link for more infos
Hope this will help you.

How to insert data into database in a multiple file input?

I have a code that lets a person upload multiple images through a form.
Problem is, the images upload fine on to the server but not sure how to get the images to be sent into the database.
PHP:
else{ // No error found! Move uploaded files
if(move_uploaded_file($_FILES["files"]["tmp_name"][$f], $targetscreenshots.$name))
$count++; // Number of successfully uploaded file
}
Where do I put the following code?
{
mysql_query("INSERT into Colleges (`files`) VALUES ('$files')"); // inserting data if file is moved
echo "Your screenshots have been uploaded successfully!"
}
This is my own code which i am using in my script.
<?php
$upath="../images/";
//uploads is the name of file array that is being uploaded.
foreach ($_FILES['uploads']['name'] as $key=>$file) {
$target = $upath.$file;
$path=substr($target,3);
// echo $path; THIS CAN BE STORED DIRECTLY TO THE DATABASE
move_uploaded_file($_FILES['uploads']['tmp_name'][$key], $target)
or die();
mysql_query(**YOUR INSERT QUERY HERE. IT WONT BE EXECUTED IF IMAGE IS NOT UPLOADED PROPERLY.**)or die(mysql_error());
}
?>
I read your comment and so i gave this answer... Kindly correct me if i have misinterpreted your question.
You are missing code that is responsible for database modification, I suggest you read some tutorials like this one.
I haven't tested it, but at least it looks like it involves all the steps required.
$files = $_FILES["files"]["tmp_name"][$f]
Just Insert the file path or name in the DB

PHP File Download with Query String

I am curious how I could make a PHP script where you pass your username and password to my webserver and it downloads a file (or multiple) that is specific to that one user only. I am not sure where to start. Could someone please help? thanks!
Here it is:
http://www.php.net/manual/en/function.readfile.php
You shouldn't put a password directly in the URL. Instead, use a random generated token, for example using MD5 ($token = md5($username.time());). So, your user table should look like this :
id
email
password
token
The URLs you'll provide to your user will be like this :
http://www.example.com/download.php?token=$userToken&file=$file
And download.php:
<?php
if ( ! isset($_GET['token']) || ! isset($_GET['file'])) {
//throw 404
}
//check token exists in DB else throw 403
//use readfile function :)
First you could create a mysql table for all users. Then you could make a second one where the filenames and usernames are saved like "file:test.png user:xyz" that every file has an owner. If somebody wants to download a file you have to check if this user is the file owner in the database. The list of all files then shows all files of this user.
Here's a simple example:
download.php
<?php
if (isset($_GET['user_info']) && check_validity($_GET['user_info'])) {
$file_info = determine_file_info($_GET['user_info']);
header("Content-type: " . $file_info['type']);
header('Content-disposition: attachment; filename="' . $file_info['name'] . '"');
readfile($file_info['absolute_path']);
exit;
}
?>
That mock-up imagines you have defined a function check_validity that determines if the given user info is valid, and that you have defined a function determine_file_info that uses the user info to build an array of file type, file name, and file path (where the file is on the server).

How to display a message if file already exists

I have a javascript function in one page and in another page I have a php script which concentrates on file uploading. At the moment my files are uploading successfully which is great news. My question though is that I want to use the php to check if a file already exists in the folder but I want to use the javascript function to display an message to state file already exists if this is true. How can this be done?
Below is the php code which checks if file exists:
if (file_exists("upload/" . $_FILES["fileImage"]["name"]))
{
}
Below is the Javascript function when file stops uploading. at moment if file doesn't upload it displays a message stating there is an error while uploading file and it displays a message if file is successfully uploaded, but I want an extra message where if file doesn't upload but this is because the file already exists, then I want it to display a message stating file already exists.
function stopImageUpload(success){
var result = '';
if (success == 1){
result = '<span class="msg">The file was uploaded successfully!</span><br/><br/>';
}
else {
result = '<span class="emsg">There was an error during file upload!</span><br/><br/>';
}
}
P.S Please no one put in their answer why don't I just put an echo in the php code, I don't want to do it like that because the user never actually navigates to the php script.
In yours PHP code that checks if file exists do
else{
echo 2;
}
In yours JS code in else clausule do
if(success == 2){
result = '<span class="emsg">File already exist!</span><br/><br/>';
}
That is a quick solution, but it gives You a way to do more complex file handling via JS/PHP. For example. When PHP returns a data 1, then everything is ok, when 2 then file exists, when 3 then file is too large, when 4 then file with bad extension, when 5 then something else, and so on.
This method I have encountered when learning C/C++(in C this way is like a standard thing). This way You can give info how some parts of code went.
Still, I would generete a a random name for file, if the name is irrelevant, and if name of file is important then wold use AJAX to check it, and display info about it, or maybe append a number after file name (file(1).xyz, file(2).xyz, file(3).xyz). That depends on what You are trying to achieve.
You say.
P.S Please no one put in their answer why don't I just put an echo in
the php code, I don't want to do it like that because the user never
actually navigates to the php script.
you need to execute some php code anyway. so you will have to do this one way or another. then , display the information to the user using whatever way you want.
since we dont have all the code i assume you have a input[type=file] in the html code , so you need to use ajax with the value of the input. send it to your server , check if the filename already exists , then respond with true or false with ajax from php and execute the code in javascript that will tell the user if the file exists or not. you can use jQuery to do that :
$("#myInput").on("change",function(event){
$.getJSON("checkFileService.php",{filename:$(event.currentTarget).val()},
function(datas){
if(datas.exists === true){
doSomething();
else{
doSomethingElse();
}
}
}
Check the jQuery ajax api for more infos
you'll have to write a php script that outputs some json string like {"exists":true} in order for the client script to work.
#safarov Can you show me an example of a function to see if file already exists, then write different name for new uploaded file?
Save/upload a simple text file named "filenamecounter.txt",
containing only text 1 in it.
<?php
//Get the original name of file
$tmp_name = $_FILES["filename"]["tmp_name"];
//Get/Read File Name Counter
$filenamecounter = file_get_contents('filenamecounter.txt');
//If it is less than 10, add a "0"/Zero to make it like 01,02,03
if (strlen($filenamecounter) <= 1){
$filenamecounter = str_pad($filenamecounter, 2, '0', STR_PAD_LEFT);
}
//Assign Filename + Variable
$name = "filename".$filenamecounter.".txt";
//Save file with new name
move_uploaded_file($tmp_name, $name);
//write quotecounter to file.
$filenamecounter++;
file_put_contents("filenamecounter.txt", $filenamecounter);
?>

Categories