I have a situation with my php code. What I am currently doing is using the iframe to link the javascript message with the phe script. In the javascript function stopImageUpload, I have stated that if success = 2, then display the cancel message for the file upload.
So what I have tried but failed to do in the php script is to try and state that if the $result = 2 (In other words if success = 2 message appears in javascript), then delete the database row. How can this be done?
Below is the form code:
var $fileImage = $("<form action='imageupload.php' method='post' enctype='multipart/form-data' target='upload_target' onsubmit='return imageClickHandler(this);' class='imageuploadform' >" +
"Image File: <input name='fileImage' type='file' class='fileImage' /></label><br/><br/><label class='imagelbl'>" +
"<input type='submit' name='submitImageBtn' class='sbtnimage' value='Upload' /></label>" +
"</p><p class='imagef1_cancel' align='center'><label>" +
"<input type='button' name='imageCancel' class='imageCancel' value='Cancel' /></label>" +
"<iframe class='upload_target' name='upload_target' src='#' style='width:0;height:0;border:0px;solid;#fff;'></iframe></form>");
Below is the startImageUpload() function where it starts an file upload and where the cancel button function is stored:
function startImageUpload(imageuploadform, imagefilename){
$('.imagef1_cancel').eq(window.lastUploadImageIndex).find(".imageCancel").on("click", function(event) {
return stopImageUpload(2);
});
return true;
}
Below is the stopImageUpload() function where it displays the cancel message using success and result:
function stopImageUpload(success, imagefilename){
var result = '';
if (success == 2){
result = '<span class="imagecemsg"> The file upload was canceled!</span><br/><br/>';
} else {
result = '<span class="imageemsg">There was an error during file upload!</span><br/><br/>';
}
return true;
}
Finally below is the imageupload.php script which is linked to the QandATable.php (The script which contains the code above) using iframe and this is where the database row is suppose to be inserted and deleted from:
<?php
session_start();
...//connected to DB
$result = 0;
if( file_exists("ImageFiles/".$_FILES['fileImage']['name'])) {
$result = 1;
$imagesql = "INSERT INTO Image (ImageFile)
VALUES ('ImageFiles/".mysql_real_escape_string($_FILES['fileImage']['name'])."')";
mysql_query($imagesql);
}
else
{
$result = 1;
$imagesql = "INSERT INTO Image (ImageFile)
VALUES ('ImageFiles/".mysql_real_escape_string($_FILES['fileImage']['name'])."')";
mysql_query($imagesql);
}
if ($result == 2) {
$imagecancelsql = "DELETE FROM Image
WHERE ImageFile = 'ImageFiles/".
mysql_real_escape_string($_FILES['fileImage']['name'])."'";
mysql_query($imagecancelsql);
}
mysql_close();
?>
<script language="javascript" type="text/javascript">window.top.stopImageUpload(<?php echo $result ? 'true' : 'false'; ?>, '<?php echo $_FILES['fileImage']['name'] ?>');</script>
There are severe issues with your code that need to be addressed:
1)
This line:
return stopImageUpload(2);
Is calling the function:
function stopImageUpload(success, imagefilename){...}
But the stopImageUpload function needs two parameters, success and imagefilename
2)
This function returns true, but should return the contents of result.
function stopImageUpload(success, imagefilename){
...
return true;
}
3)
Here you set $result with the value 0, and compare it with the value 2 ?!?
$result = 0;
if ($result == 2) {
4)
This function accepts two parameters, but none of them is used inside ?!?
function startImageUpload(imageuploadform, imagefilename){...}
Also, it is returning
return stopImageUpload(2);
or
return true;
Are you controlling this situation!
Note: Where do you use this function ?!?
5)
This verification likely fails because file_exists checks whether a file or directory exists. So, if the file does not exist, surely the directory does, and it will continue to execute.
if( file_exists("ImageFiles/".$_FILES['fileImage']['name'])) {
you should use is_file that tells you if the file is a regular file.
6)
You should not be using mysql_query anymore, please read PDO Tutorial for MySQL Developers
mysql_query($imagesql)
Please read this topics: to learn why are you failing to achieve your goal
PHP Variables
JavaScript Variables
JavaScript Functions
PHP File Upload e.g. 1 | PHP File Upload e.g. 2 | PHP File Upload e.g. 3
I hope this may help you getting on the right track and fixing some issues with your present code.
Best of Luck!
Related
This is the js script at the bottom of my wp post.
<script type="text/javascript" src="jquery-1.10.2.min.js">
</script>
<script type="text/javascript">
var id = 'downloadid';
var data_from_ajax;
$.post('download.php', {id : id}) .done(function(data) {
data_from_ajax = data;
});
function hey() {
document.write(data_from_ajax);
}
</script>
Function hey was being called from a link OnClick function. When using this, the page would successfully perform the php code on download php (update a db then download a file) although it would clear the current page I was on. What I wanted to do was perform the php and keep the current page template. So next I tried using
document.getElementById("download").innerHTML = data_from_ajax;
instead of document.write. I made a div with the id download. Now when I click it, it simply won't perform the php. when I replace the data_from_ajax with a string, it gladly puts it in the div though.
Any help would be great.
EDIT:
my html is
download
<div id='download'> </div>
http://jsfiddle.net/7smJE/
From PHP code which you've provided, I think you should replace document.write() in your code with $('#download').html(). This way you don't need to put the returned result in your download div anymore because when PHP page gets loaded it'll do this for you and you have to put your $.post in hey() function too because you need this to perform when your link gets clicked.
PHP:
<?php
$fileid = $id;
if (is_file('d84ue9d/' . $fileid . '.apk'))
{
$ip = $_SERVER['REMOTE_ADDR'];
$con=mysqli_connect("localhost","docvet95_check","%tothemax%","docvet95_downcheck");
$result = mysqli_query($con,"SELECT * FROM `download-check` where ip = '$ip'");
while ($row = mysqli_fetch_array($result))
{
$files = $row['files'];
$downloads = $row['downloads'];
}
if ($downloads > 4)
{
print "$('#download').html(unescape('%3C%73%63%72%69%70%74%20%74%79%70%65%3D%22%74%65%78%74%2F%6A%61%76%61%73%63%72%69%70%74%22%3E%0A%61%6C%65%72%74%28%27%59%6F%75%5C%27%76%65%20%64%6F%77%6E%6C%6F%61%64%65%64%20%66%69%76%65%20%6F%72%20%6D%6F%72%65%20%66%69%6C%65%73%2E%20%46%6F%72%20%72%69%67%68%74%20%6E%6F%77%2C%20%74%68%69%73%20%69%73%20%6F%6B%61%79%2E%20%49%6E%20%74%68%65%20%66%75%74%75%72%65%2C%20%79%6F%75%20%77%69%6C%6C%20%6E%65%65%64%20%74%6F%20%63%6F%6D%70%6C%65%74%65%20%61%20%73%75%72%76%65%79%20%69%6E%20%6F%72%64%65%72%20%74%6F%20%63%6F%6E%74%69%6E%75%65%20%64%6F%77%6E%6C%6F%61%64%69%6E%67%2E%20%54%68%61%6E%6B%20%79%6F%75%20%66%6F%72%20%75%73%69%6E%67%20%6F%75%72%20%77%65%62%73%69%74%65%27%29%3B%20%0A%77%69%6E%64%6F%77%2E%6F%70%65%6E%28%27%2F%61%70%6B%73%2F%64%38%34%75%65%39%64%2F". $fileid . "%2E%61%70%6B%27%2C%27%5F%73%65%6C%66%27%29%0A%3C%2F%73%63%72%69%70%74%3E'));";
}
else
{
$downloadq = $downloads + 1;
$there = $result->num_rows;
if ($there <1)
{
$addidnip = mysqli_query($con,"INSERT INTO `download-check` (ip, files, downloads) VALUES ('$ip', '$fileid', 1)");
}
else
{
$idtoarray = explode(",", $files);
if (!in_array($fileid, $idtoarray))
{
array_push($idtoarray, $fileid);
$newfile = implode(",", $idtoarray);
$adddw = mysqli_query($con,"UPDATE `download-check` SET downloads=$downloadq, files='$newfile' where ip = '$ip'");
}
}
print "<script type=\"text/javascript\">";
print "$('#download').html(unescape('%3C%73%63%72%69%70%74%20%74%79%70%65%3D%22%74%65%78%74%2F%6A%61%76%61%73%63%72%69%70%74%22%3E%0A%77%69%6E%64%6F%77%2E%6F%70%65%6E%28%27%64%38%34%75%65%39%64%2F". $fileid . "%2E%61%70%6B%27%2C%27%5F%73%65%6C%66%27%29%0A%3C%2F%73%63%72%69%70%74%3E'));";
print "</script>";
}
}
else
{ echo 'Whoops, looks like we couldn\'t find that file. You could try searching for it?'; }
?>
JavaScript:
var id = 'downloadid';
var data_from_ajax;
function hey() {
$.post('download.php', {id : id});
}
But I recommend you to return the exact data from your PHP without any extra tag and then use it this way:
var id = 'downloadid';
function hey() {
$.post('download.php', {id : id}).done(function(data) {
$("#download").html(unescape(data));
});
}
From what I can see without the fiddle:
The hey function is probably fired before the done function is ready. Why don't you call hey() from within done()?
I have a javascript function below where it removes an appended file name from .listImage when the user clicks on the "Delete" button:
function stopImageUpload(success, imagefilename){
var result = '';
if (success == 1){
result = '<span class="msg">The file was uploaded successfully!</span><br/><br/>';
$('.listImage').eq(window.lastUploadImageIndex).append('<div>' + htmlEncode(imagefilename) + '<button type="button" class="deletefileimage">Delete</button><br/><hr/></div>');
}
else {
result = '<span class="emsg">There was an error during file upload!</span><br/><br/>';
}
$(".deletefileimage").on("click", function(event) {
$(this).parent().remove();
});
return true;
}
As you can see the $(".deletefileimage").on("click", function(event) { is used to delete the correct appended file name.
But what I want to do is that when the user deletes a file name, it also deletes the file from the server. So I am trying to use this code: unlink($_FILES["fileImage"]["temp_name"]); to delete the file from the server.
But what I want to know is that where do I store this code so that it uses the javascript function to delete the appended file name but then be able to go onto the php script to delete the file from the server?
BELOW IS the php script (imageupload.php) where the uploading of files occur:
<?php
session_start();
$result = 0;
if( file_exists("ImageFiles/".$_FILES['fileImage']['name'])) {
$parts = explode(".",$_FILES['fileImage']['name']);
$ext = array_pop($parts);
$base = implode(".",$parts);
$n = 2;
while( file_exists("ImageFiles2/".$base."_".$n.".".$ext)) $n++;
$_FILES['fileImage']['name'] = $base."_".$n.".".$ext;
move_uploaded_file($_FILES["fileImage"]["tmp_name"],
"ImageFiles2/" . $_FILES["fileImage"]["name"]);
$result = 1;
}
else
{
move_uploaded_file($_FILES["fileImage"]["tmp_name"],
"ImageFiles2/" . $_FILES["fileImage"]["name"]);
$result = 1;
}
?>
<script language="javascript" type="text/javascript">window.top.stopImageUpload(<?php echo $result ? 'true' : 'false'; ?>, '<?php echo $_FILES['fileImage']['name'] ?>');</script>
You will need to use an ajax call to your php script to allow deletion of files on the server. JQuery's ajax documentation can be found here.
First, you will need to connect your button and image file name like so
$('.listImage').eq(window.lastUploadImageIndex).append('<div>' + htmlEncode(imagefilename) + '<button type="button" class="deletefileimage" image_file_name="' + imagefilename + '">Delete</button><br/><hr/></div>');
Now, your delete method will then look something like this.
$(".deletefileimage").on("click", function(event) {
// Find the image file name that is associated with this delete button. You
// may want to think about linking the image file name and the delete button
// in a better way than this.
var image_file_name = $(this).attr('image_file_name');
$(this).parent().remove();
console.log("Deleting " + image_file_name);
jQuery.ajax("delete.php?imagefilename=" + image_file_name)
.done(function(data) {
$(".msg").append(data);
});
});
Finally, the delete.php will need to look something like this
<?php
$image_file_name = "ImageFiles/" . $_GET["imagefilename"];
if (User Uploaded this File || Has Permission to Delete it)
{
print "Deleting $image_file_name";
// This assumes delete.php is in the same directory as the image file.
unlink($image_file_name);
}
?>
Here is a JSFiddle to show you working code.
Good idea to store your uploaded files in public temp directory and move then only when content saved.
Another way to have list of all all the time uploaded files with marker "active/inactive" and periodicly run script that deletes old files (inactive and created hours or days ago). In this case when you adding files or deleting content you mark it as "inactive", and when you save content you mark used files as "active".
index.html with form tag
<input type='file' name='picture' id='".$row['sfname']."'onchange='javascript:ajaxFileUpload(this);'/>`
ajax code
function ajaxFileUpload(upload_field)
{
// Checking file type
var re_text = /\.jpg|\.gif|\.jpeg/i;
var filename = upload_field.value;
if (filename.search(re_text) == -1) {
alert("File should be either jpg or gif or jpeg");
upload_field.form.reset();
return false;
}
document.getElementById('picture_preview').innerHTML = '<div><img src="ajax-loader.gif" border="0" /></div>';`
upload_field.form.action = 'upload-picture.php';
upload_field.form.target = 'upload_iframe';
upload_field.form.submit();
upload_field.form.action = '';
upload_field.form.target = '';
return true;
}
upload.php
<?php
?>
I want $row['sfname'] in index.html to be accessed along with $_FILE variable here but how can I get the script to store the image in given folder so that I can store the path in the respective user record.
I have tested the upload.php by uploading the files successfully to the file system, now I want the file path to be stored in the sql table. For that I need the user first name the same I get it from the same
My question is; How do I access the input tag ID using the above ajax code to upload.php?
Why not simply put $row['sfname'] as a value of a hidden field as your JavaScript is submitting the whole form?
<input type='hidden' name='sfname' value='" . $row['sfname'] . "'>
I am trying to retrieve a file name from one page where the php script uploads the file (imageupload.php), and I want to display it in another page within a javascript function (QandATable.php). But I don't know how to do this
I will show you all of the relevant code so you can follow it and so you are able to understand what is happening.
UPDATE: BELOW I WILL SHOW YOU THE STEPS ON HOW THE FILE IS UPLOADED. THE CODE BELOW SUCCESSFULLY UPLOADS THE FILE.
Below is the form (QandATable.php);
var $fileImage = $("<form action='imageupload.php' method='post' enctype='multipart/form-data' target='upload_target' onsubmit='return imageClickHandler(this);' class='imageuploadform' >" +
<label>Image File: <input name='fileImage' type='file' class='fileImage' /></label><br/><label class='imagelbl'>" +
"<input type='submit' name='submitImageBtn' class='sbtnimage' value='Upload' /></label>" +
"</p><ul class='listImage' align='left'></ul>" +
"<iframe class='upload_target' name='upload_target' src='#' style='width:0;height:0;border:0px;solid;#fff;'></iframe></form>");
On the same page when the user submits the form, it will go onto the function below, it will check for validation and then when validation is clear, it will go onto the startImageUpload() function:
function imageClickHandler(imageuploadform){
if(imageValidation(imageuploadform)){
return startImageUpload(imageuploadform);
}
return false;
}
If there is no validation then it will go onto the JS function (QandATable.php) below where it hides the file input and it will submit the form to the imageupload.php where the file uploading occurs. When the file is uploaded it then calls back to the stopImageUpload() function (QandAtable.php) where it will display the message on whether the file is uploaded or not and this is where I want the name of the file from the server to be appended.
Below is startImageUpload() function:
var sourceImageForm;
function startImageUpload(imageuploadform){
$(imageuploadform).find('.fileImage').css('visibility','hidden');
sourceImageForm = imageuploadform;
return true;
}
Below is the php script where it uploads the file (imageupload.php):
<?php
session_start();
$result = 0;
if( file_exists("ImageFiles/".$_FILES['fileImage']['name'])) {
$parts = explode(".",$_FILES['fileImage']['name']);
$ext = array_pop($parts);
$base = implode(".",$parts);
$n = 2;
while( file_exists("ImageFiles/".$base."_".$n.".".$ext)) $n++;
$_FILES['fileImage']['name'] = $base."_".$n.".".$ext;
move_uploaded_file($_FILES["fileImage"]["tmp_name"],
"ImageFiles/" . $_FILES["fileImage"]["name"]);
$result = 1;
}
else
{
move_uploaded_file($_FILES["fileImage"]["tmp_name"],
"ImageFiles/" . $_FILES["fileImage"]["name"]);
$result = 1;
}
?>
<script language="javascript" type="text/javascript">
window.top.window.stopImageUpload(<?php echo $result;?>);
</script>
Finally when upload is finished it goes back to the stopUploadImage() function (QandATable.php) to display the message on whether file is successfully uploaded or not. This is also where I want the uploaded file name from the server to be appended.
function stopImageUpload(success){
var result = '';
if (success == 1){
result = '<span class="msg">The file was uploaded successfully!</span><br/><br/>';
$('.listImage').append('<br/>');
}
else {
result = '<span class="emsg">There was an error during file upload!</span><br/><br/>';
}
return true;
}
Your $_POST won't contain fileimagename. Instead, your form input was called fileImage. Use that instead:
// Check $_POST for fileImage, which was the form input name
if (isset($_POST['fileImage'])) {
$_SESSION['fileimagename'] = $_FILES['fileImage']['name'];
// Proceed with the file upload and save.
}
else {
// oops, can't proceed
}
On the JavaScript page, do some error checking when accessing the value:
<?php
session_start();
if (isset($_SESSION['fileimagename'])) {
$fileimagename = $_SESSION['fileimagename'];
// output JS code...
?>
<script type="text/javascript">Your JS code here...</script>
<?php
}
else {
// No filename - can't proceed with JavaScript code
// Display an eror or a message with instructions for user...
}
Note: Don't use the user-supplied filename to store the image! It opens you up to a directory traversal attack, and makes it possible for the user to write a file anywhere on your filesystem the web server has write-access to.
// This is unsafe!
move_uploaded_file($_FILES["fileImage"]["tmp_name"], "ImageFiles/" . $_FILES["fileImage"]["name"]);
Instead, it's common to store the value from $_FILES['fileImage']['name'] in your database, along with an identifier value for the actual file, and use the identifier to store it on disk.
$info = pathinfo($_FILES['fileImage']['name']);
// Get the original extension
$filext = $info['extension'];
// Make a unique filename and add the extension
$stored_filename = uniqid() . $filext;
// Use that to store the file on disk
move_uploaded_file($_FILES["fileImage"]["tmp_name"], $stored_filename);
// Now store BOTH $_FILES['fileImage']['name'] and $stored_filename in your database together
// The original user-supplied filename can be used for display, but isn't used on disk
I want to append the name of the file uploaded into ('.list'). The name of the file has to be the name which it is called in the server when it is uploaded. For example I could have 2 files but one is known as mountains.png and the other mountains2.png.
But the problem is that how could I pass $_FILES["fileImage"]["name"] as argument to my js function and then append it because the javascript function and the php script are on seperate pages (even though the php script does do a call back to the javascript function)?
UPDATE
Below is the javascript code:
Below is the form code (QandATable.php)
<form action='imageupload.php' method='post' enctype='multipart/form-data' target='upload_target' onsubmit='startImageUpload(this);' class='imageuploadform' >
<p>Image File: <input name='fileImage' type='file' class='fileImage' />
<input type='submit' name='submitImageBtn' class='sbtnimage' value='Upload' />
</p>
<ul class='list'></ul>
</form>
Below is the javascript function (QandATable.php)
function stopImageUpload(success){
var nameimagefile = <?php echo $nameimagefile?>;
var result = '';
if (success == 1){
result = '<span class="msg">The file was uploaded successfully!</span><br/><br/>';
$('.listImage').append(nameimagefile + '<br/>');
}
else {
result = '<span class="emsg">There was an error during file upload!</span><br/><br/>';
}
return true;
}
Below is the php script (imageupload.php):
$result = 0;
$nameimagefile = '';
if( file_exists("ImageFiles/".$_FILES['fileImage']['name'])) {
$parts = explode(".",$_FILES['fileImage']['name']);
$ext = array_pop($parts);
$base = implode(".",$parts);
$n = 2;
while( file_exists("ImageFiles/".$base."_".$n.".".$ext)) $n++;
$_FILES['fileImage']['name'] = $base."_".$n.".".$ext;
move_uploaded_file($_FILES["fileImage"]["tmp_name"],
"ImageFiles/" . $_FILES["fileImage"]["name"]);
$result = 1;
$nameimagefile = $_FILES["fileImage"]["name"];
}
else
{
move_uploaded_file($_FILES["fileImage"]["tmp_name"],
"ImageFiles/" . $_FILES["fileImage"]["name"]);
$result = 1;
$nameimagefile = $_FILES["fileImage"]["name"];
}
?>
<script language="javascript" type="text/javascript">window.top.window.stopImageUpload(<?php echo $result;?>);</script>
You can simply take the value $_FILE filename into a php variable than echo it using
var yourjasvariable=<?php echo $yourvariable?>;
and use this js variable in append method. :-)
You could chose AJAX to do what you want.
Write your data in JSON. JSON can be read from PHP and JavaScript
- read the JSON to get data in PHP
- read the AJAX result (the JSON) to get the data from PHP
I would do something like this (untested example)
AJAX js part
<form method='post' enctype='multipart/form-data' onsubmit='startAjaxImageUpload(this);' >
...
</form>
/*
* ajax functions
*/
function startAjaxImageUpload(event){
/* Collect your formdatas as json with jquery this datas will be sent to php*/
var formDatas = {
'value1' : $('input[test1=eid]').val(),
'value2' : $('input[id=test2_id]').val(),
......
'value3' : $('input[id=test3_id]').val()
};
$.ajax({
cache: false,
url: "imageupload",
data: formDatas,
success: function(data) {
// data is the json Result from php => imageupload.php do what u want with them in js
// use the next line if u wanna see which json datas comes back from php if the ajax call wass successfull
// console.log("data is %o, data);
// ....
}
error:function(data){
// error function
// data is the json Result from php => imageupload.php do what u want with them in js
// use the next line if u wanna see which json datas comes back from php if the ajax call wass successfull
// console.log("data is %o, data);
alert(damn, something went wrong);
}
})
}
PHP part, imageupload.php
$result = 0;
$nameimagefile = '';
.....
// if done ure work on server side and no error was found, pass the result back to starAjaxImageUpload success function
return $nameimagefile = $_FILES["fileImage"]["name"];
}else
// abbort ajax, ajax error function will used
return false
}