How to display a message if file already exists - php

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);
?>

Related

Determinate line file it´s empty in loop for

The file called "file_changes.dat", it´s totally empty, no have any informations, and create in server, i use this script for simple show data from this file, the script it´s the next :
$fil_dat_changes=file("file_changes.dat");
$f_changes=fopen("file_changes.dat","w");
for($fh=0;$fh<sizeof($fil_dat_changes);$fh++) {
if(trim($fil_dat_changes[$fh])=="")
{
print "NO DATA";
fputs($f_changes,"".date("dmYHis").""."\n");
}
else
{
print "YES EXISTS LINE";
}
}
fclose($f_changes);
And i don´t know why if file it´s empty, when i put :
if(trim($fil_dat_changes[0])=="")
Don´t show nothing, and also don´t put the line with fputs, i think the result must show NO DATA ans insert the informations, but don´t insert nothing
I don´t understand which it´s the problem because i think if don´t exists any line of informations or data, must insert the line finally in the file
That´s it´s my question, why don´t insert data, thank´s in advance all community, regards
You can check the file contains data using filesize(). BUT as you also open the file for writing in
$f_changes=fopen("file_changes.dat","w");
this will always empty the file and set it for writing. This will clear any data already in the file.
If instead you check if the file is empty and then use file_put_contents() to write to the file, this will only do this if the file is empty...
if ( 0 == filesize( "file_changes.dat" ) ) {
file_put_contents("file_changes.dat", date("dmYHis").PHP_EOL);
}
else {
echo "YES EXISTS LINE";
}

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

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.

equivalent $_FILES["imageToUpload"]["tmp_name"] when I use file_get_contents() function

I have a function like this:
fitImageSizeAndSave($_FILES["imageToUpload"]["tmp_name"], $target_file) { ... }
That function works well. The first argument is $_FILES["imageToUpload"]["tmp_name"]. Ok, it's good when an user upload an image from his local computer. But sometimes he enters a external link and I get that image like this:
$image = file_get_contents($_POST['external_link']);
How can I make $image like $_FILES["imageToUpload"]["tmp_name"] for passing it to the function?
use file_put_contents() and then reference the temporary file that you've just put the data into
#Martin Sounds a great idea, may you please add an answer? –
$_FILES["imageToUpload"]["tmp_name"] is simply a string to a file location on the server, it is not a resuorce in itself.
$filePathLocation = $_SERVER['DOCUMENT_ROOT']."/some-temporary/file/storage";
$imageData = file_get_contents($_POST['external_link']);
if($imageData){
file_put_contents($imageData, $filepathLocation);
}
else {
$filepathLocation = $_FILES["imageToUpload"]["tmp_name"];
}
fitImageSizeAndSave($filepathLocation, $target_file) { ... }
The above, step by step:
Set a temporary storage location; possibly based on microtime() or something unique (database Id, if relevant) to limit different processes overwriting the same file path.
get the contents of the $_POST file URL. save to a string variable.
Check if variable is loaded ok; else use uploaded temporary file location THIS IS FOR ILLUSTRATION ONLY - You should have a more complete process for checking which data to use and the validity of said data already set up in your script.
Send this variable to your custom function, knowning it is populated with one or the other of the possibilities above.
The below is the PHP script to get image from url and save into your location machine or into own server
$imageurl ='http://i.ndtvimg.com/i/2015-08/mahesh-babu_630x450_81440064359.jpg';
$content = file_get_contents($imageurl);
if(file_put_contents('imagefolder/randomImageName.jpg', $content)){
echo "File uploaded through URL";
}else{
echo "File not uploaded...";
}

Delete File Even A Fatal Error

I am trying to create an online php editor .Alternative to eval , i am doing it as
Get the codes by form post (having an iframe as target) request and save it in a temp file
including that temp file ,so codes gets executed
deleting that temp file
CODE
<?php
session_start();
if(isset($_POST['winCode']))
{
$data=$_POST['winCode'];
$_SESSION['data']=$data;
// creating a $_SESSION['data'] ,so that
// user can maximize the resultant iframe
}
file_put_contents(session_id()."_runphp.php",$_SESSION['data']);
include(session_id()."_runphp.php");//generate output
unlink(session_id()."_runphp.php");//delete temp file
?>
This is working well , but when a user generates error by his codes ..unlink doesn't work .. How can i set unlink to run even a fatal error occurs.
Use register_shutdown_function.
Follow the link http://php.net/manual/en/function.register-shutdown-function.php
register_shutdown_function( "shutdown_handler" );
function shutdown_handler() {
// delete file here
}
Note: This is not a good practice to execute the user entered code as it is. This system to open to Cross Site Scripting Attacks.

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