I am getting an undefined variable - php

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

Related

How to delete database row in this php script

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!

Where to place the unlink code to delete a file from the server

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".

How to i post image id to php along with $_FILE

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'] . "'>

How to pass a php code in a javascript function?

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
}

PHP variable from external .php file, inside JavaScript?

I have got this JavaScript code for uploading files to my server (named it "upload.js"):
function startUpload(){
document.getElementById('upload_form').style.visibility = 'hidden';
return true;
}
function stopUpload(success){
var result = '';
if (success == 1){
result = '<div class="correct_sms">The file name is [HERE I NEED THE VARIABLE FROM THE EXTERNAL PHP FILE]!</div>';
}
else {
result = '<div class="wrong_sms">There was an error during upload!</div>';
}
document.getElementById('upload_form').innerHTML = result;
document.getElementById('upload_form').style.visibility = 'visible';
return true;
}
And I've got a simple .php file that process uploads with renaming the uploaded files (I named it "process_file.php"), and connects again with upload.js to fetch the result:
<?php
$file_name = $HTTP_POST_FILES['myfile']['name'];
$random_digit = rand(0000,9999);
$new_file_name = $random_digit.$file_name;
$path= "../../../images/home/smsbanner/pixels/".$new_file_name;
if($myfile !=none)
{
if(copy($HTTP_POST_FILES['myfile']['tmp_name'], $path))
{
$result = 1;
}
else
{
$result = 0;
}
}
sleep(1);
?>
<script language="javascript" type="text/javascript">window.top.window.stopUpload(<?php echo $result; ?>);</script>
What I need is inside upload.js to visualize the new name of the uploaded file as an answer if the upload process has been correct? I wrote inside JavaScript code above where exactly I need to put the new name answer.
You have to change your code to the following.
<?php
$file_name = $HTTP_POST_FILES['myfile']['name'];
$random_digit=rand(0000,9999);
$new_file_name=$random_digit.$file_name;
$path= "../../../images/home/smsbanner/pixels/".$new_file_name;
if($myfile !=none)
{
if(copy($HTTP_POST_FILES['myfile']['tmp_name'], $path))
{
$result = 1;
}
else
{
$result = 0;
}
}
sleep(1);
?>
<script language="javascript" type="text/javascript">window.top.window.stopUpload(<?php echo $result; ?>, '<?php echo "message" ?>');</script>
And your JavaScript code,
function stopUpload(success, message){
var result = '';
if (success == 1){
result = '<div class="correct_sms">The file name is '+message+'!</div>';
}
else {
result = '<div class="wrong_sms">There was an error during upload!</div>';
}
document.getElementById('upload_form').innerHTML = result;
document.getElementById('upload_form').style.visibility = 'visible';
return true;
}
RageZ's answer was just about what I was going to post, but to be a little more specific, the last line of your php file should look like this:
<script language="javascript" type="text/javascript">window.top.window.stopUpload(<?php echo $result; ?>, '<?php echo $new_file_name ?>');</script>
The javascript will error without quotes around that second argument and I'm assuming $new_file_name is what you want to pass in. To be safe, you probably even want to escape the file name (I think in this case addslashes will work).
A dumb man once said; "There are no stupid questions, only stupid answers". Though he was wrong; there are in fact loads of stupid questions, but this is not one of them.
Besides that, you are stating that the .js is uploading the file. This isn't really true.
I bet you didn't post all your code.
You can make the PHP and JavaScript work together on this problem by using Ajax, I recommend using the jQuery framework to accomplish this, mostly because it has easy to use functions for Ajax, but also because it has excellent documentation.
How about extending the callback script with:
window.top.window.stopUpload(
<?php echo $result; ?>,
'<?php echo(addslashes($new_file_name)); ?>'
);
(The addslashes and quotes are necessary to make the PHP string come out encoded into a JavaScript string literal.)
Then add a 'filename' parameter to the stopUpload() function and spit it out in the HTML.
$new_file_name=$random_digit.$file_name;
Sorry, that is not sufficient to make a filename safe. $file_name might contain segments like ‘x/../../y’, or various other illegal or inconsistently-supported characters. Filename sanitisation is much harder than it looks; you are better off making up a completely new (random) file name and not relying on user input for it at all.

Categories