Delete file using a link - php

i want to have function like delete file from database by using link instead of button. how can i do that? do i need to use href/unlink or what?
Can i do like popup confirmation wther yes or no. i know how to do that, but where should i put the code?
this is the part how where system will display all filename and do direct upload. Beside each files, there will be a function for 'Remove':
$qry = "SELECT * FROM table1 a, table2 b
WHERE b.id = '".$rs[id]."' AND a.ptkid = '".$rs[id]."' ";
$sql = get_records_sql($qry);
foreach($sql as $rs){ ?>
<?echo ''. basename($rs->faillampiran).'';
?><td><?echo ' [Remove]';?></td><?
?><br>
<? }
?>
thankz all

The elegant way of doing this would be to use both PHP and JavaScript. PHP is a server-side language, and should probably be removed as much as possible from the client side stuff. One great way to do it would be to essentially create yourself an API.
The API would be a PHP script that deletes a row. It takes a variable in via GET and returns a boolean that says "yes we deleted the row" or "something went wrong." I like to use JSON, which in JavaScript is easier to work with than XML, and jQuery's getJSON function, a package that makes it really easy to get going.
In the .php file (we call it api.php later), if your results are successful return out success boolean. We use PHP's json_encode on an array, and echo out the result:
$variable = someFunctonToSanitize($_REQUEST['idToDelete']);
$query_to_run = "delete query using $variable";
$result = mysql_query($query_to_run);
// set headers
header('Content-type: text/json');
header('Content-type: application/json');
// if the query was successful, echo true
if($result) {
echo json_encode(array("success"=>"true"));
} else { // else echo false
echo json_encode(array("success"=>"false"));
}
In your JavaScript, here using jQuery (this is discouraged, see comments below):
$('#deleteLink').click(function(event) {
// prevent link from actually going anywhere
event.preventDefault();
// Fire off API request
$.getJSON("api.php?idToDelete=whatever", function(data){
if(data.success) {
alert("Item was deleted.");
} else {
alert("There was an error");
}
});
});
With a .post() request, per #Col. Shrapnel and #josh3736's comments (note: also changed $_GET to $_REQUEST to work with both):
$.post("api.php", { "idToDelete": "whatever" },
function(data){
if(data.success) {
alert("Item was deleted.");
} else {
alert("There was an error");
}
}, "json");
In your HTML:
Delete!

No links nor buttons can be used for the database interaction. It is server-side code to do such things. You have to understand that your application has 3 layers:
an HTML form
an server-side code
a database
the first one cannot interact with the last one directly.
So, on the one hand, it doesn't matter, with link or button you do call your server side code (the code remains the same).
But, on the other hand, there is a rule:
use GET method (link) to request information and POST (form/button) to modify it.
So, you should not use links to remove files, because some too smart bot can wipe all your database in a second.
As for your question where to place the code, just write a php script, unlink.php which deletes a file by hardcoded path. Then, after you've done that, make this file an action for the HTML form. Hardcoded one. Once you've done that - you can try to generate this form from your database.
This - step-by-step way - is the only possible way to develop a wab-application

Make a link:
Delete
Then make a delete.php that handles deleting and make sure you check that the session is authorised.

In PHP you use unlink() to delete a file. If you provide a page which accepts the file name (or better yet, file Id) as a parameter you can call unlink() on the file. Obviously there are some serious security implications which you will need to account for.

For confirm Delete, use this in onclick function()
In a href tag, itself :
<a href="" onclick="return ConfirmDelete();" ></a>
In upper Page use javascript like this,
function ConfirmDelete() {
var confm = window.confirm("Are you sure want to delete this !");
if(confm == true) {
return true;
} else {
return false;
}
}
For delete option give the same page link and pass the parameter and get the parameter by get function
<a href='samepagename?deleteid='.<?php echo $id;?>
In get parameter use like this,
$deleteid = $_GET["deleteid"];

Related

Calling a function to control a confirm alert from within an if statement

Good evening ..
I have a form where you assign work to a worker, however, if that work is already assigned then user has a choice of either reassigning it or returning to previous page.
so I'm trying to write the syntax for a confirm alert that redirects user to one page or another depending on his choice ,
I placed it within the head section and it goes something like this:
function show_confirm() {
var con = confirm("Already assigned.. would you like to reassign?");
if (con ==true) {
window.location = "reassign.php"
} else {
window.location = "index.php"
}
}
The question is : how do you call this function depending on an if statement? I have seen some examples on the internet where people place the function (rather than just call it ) directly inside the if statement, but wouldn't that be mixing different kinds of script?
So .. how do you call the function from within this if statement?
I tried this but it didnt work:
$flat=$_POST['flat'];
$check= mysql_query("SELECT * FROM assignment WHERE flat = '$flat'");
$num= mysql_num_rows($check);
if ($num!=0) { show_confirm();
} else { //irrellivant code
Since this is a JavaScript function, you just place the function itself inside the header, and then in PHP, you output the call to the function in your if like this:
if ($num!=0) {
echo '<script type="text/javascript">show_confirm();</script>';
} else {
//irrelevant code
}
PHP is a server-side scripting language, while JavaScript is client-side. You can't call the JavaScript function directly from the server-side like you were trying to do. You can however output javascript to the page via PHP as I have done in my example.
Yes, you are trying to mix php (server side) and javascript (client side) in one process which won't work.
When you submit the form to check if they are already assigned you then need to redirect them to a confirm page, from there you would have yes/no buttons linking to the reassign and go back pages.
The best solution would actually be to handle this with AJAX but given the nature question I think its best to stick with non-ajax workflow.
Let me know if that makes sense, if not I will add some more detail

PHP function on close with jQuery AJAX

I've been working this problem for awhile and seen a lot of different approaches. I have code that I believe should be working, but for one reason or another is not.
Here is my JavaScript code file name - test.js:
function deleteTempTable() {
$.ajax({
url: "exit.php",
success: function(data) {
alert("Deleting Temp Table");
}
});
}
I placed the alert purely for testing purposes to make sure the AJAX call was being made, and it is.
Here is the HTML for the button that makes the AJAX call file name - form.template:
<input type="button" title="Click to close window" value="Close"
onclick="deleteTempTable();" style="width:80px" name="close">
This does work as I get the JavaScript alert just fine.
Here is an EXAMPLE of the php code I'm using (it's not exact as it has some stuff I can't share, custom classes etc, either way I've reused this same pattern else where and it works fine and drops the tables as needed) file name - exit.php :
<?php
session_start();
require $_SERVER['DOCUMENT_ROOT'] . "path/to/file.php";
$tempTableName = $_SESSION['tempTableName'];
//Not really hard coding this it's just an example
$odbcConn = odbc_connect('DataBaseName', 'UserName', 'Password');
$sqlCmd = "DROP TABLE IF EXISTS $tempTableName;";
odbc_exec($odbcConn, $sqlCmd);
?>
When I click the button the JavaScript alert pops up, but it appears as the the php is ignored since the table still exists. Elsewhere in my code use the same php pattern to drop tables when new sets of data are requested, and they drop fine. Just not when I try to do it with this button.
Any ideas or pointers would be great!
Also I saw this question, "Calling PHP function using JQuery .ajax()", but his problem was syntax, and I'm pretty sure with my IDE I'm not having a syntax error, and from what I've seen this is the solution posted.
UPDATE
Thanks to some suggestions I was able to get a test that would confirm the php code itself works, but is not actually being executed by the AJAX call. Essentially I just ran the page that created the table, ie index.php, and then directed the browser to exit.php and the table was deleted as I would have expected. So the only conclusion is that exit.php is not actually being called/executed by the AJAX call.
I don't know if this could be the problem but here is my actual url assignment (more or less): url: "/folder1/folder2/folder3/folder4/exit.php" I had tried url: "exit.php" as well, so I don't know if I need the full root path to the file or not, or if this is some how the issue. At this point I'm just brain storming since I at least now know the php is not being executed or opened properly.
UPDATE
Well thanks to Salivador walking me through some trouble shooting the problem is solved. Basically the code is correct. So feel free to use it if you need to do something like this, however don't do what I did and mess up the PATH TO THE FILE!
face palm
Your ajax call is executed, but are you sure that your PHP code is executed correctly and as intended?
Try to output the $tempTableName to see do you actually getting the right name for your table, try to see the response of odbc_exec(...) command to see what is the result of deletion.
quick reaction is that the sqlcommand is including a semi-colon, remove that
heres an alternate method, do this in your php code
html
<input type="button" title="Click to close window" value="Close"
onclick="deleteTempTable('mytable');" style="width:80px" name="close">
exit.php
if($_REQUEST['command'] == 'droptable') {
echo dropTable($_REQUEST['tablename'] ));
}
...
function dropTable($tableName){
/*your sql stuff/code here*/
$sqlCmd = 'Drop Table '.$tablename;
$rz = odbc_exec($odbcConn, $sqlCmd);
if (!$rz){
$result = true;
} else {
$result = false;
}
return $result;
}
then you could do this
function deleteTempTable(tablename) {
var params = 'command=droptable&tablename='+tablename;
$.ajax({
url: "exit.php?"+params,
success: function(data) {
if(data == true) {
alert("Deleting Temp Table");
} else {
alert("Didnt work");
}
}
});
}
Just one way of doing it , i personally wouldnt use an onclick to fire the function, i prefer selector bound events
why are you storing this table name in session data? wouldnt a form var work out better?

Keeping $_session['username'] inside a ajax function

I've been messing with a script, and i'm now currently at the protection part.
Basically i cant manage to receive a $_session['username'] request.
I can not use cookies, as these can be faked. And it's a pretty big security hole.
Is this a common issue?
(The non-ajax and ajax page have the same session-id, and yes. i do use session_start();)
If you know any good comment-scripts it would be appriciated if you would like to link! c: )
edit:
The user logs in, and the session is started.
Now i'm combining a page/post with a modified comment script. (found here: http://tutorialzine.com/2010/06/simple-ajax-commenting-system/ )
What i've done is that i made it work with multiple pages, and removed the user & password thing that was provided with the script.
The request is something similar to this:
$user = $_session['username'];
if(!($data['user'] = $user)){
$errors['error'] = $_session['username']; //just to see if it can find the username
}
The above request returns a null value, but if i run "echo $_session['username'];" on the page that calls java, i get "powback".
EDIT:
i couldn't get this to work, but i made a bypass. I managed to insert $_session['username'] directly into the database with an other kind of validation. The current one was stupid... It should work properly now. Thank you!
How are you passing the session ID if not via a cookie? If you're passing it via URL (which is an even bigger security risk), make sure you pass it in the URL of your AJAX request.
Try this
var v="any variable to be passed";
$.post( "passingfile.php",{name:v},
function(data) {
Alert("Pass OK");
});
return false;
});
If you for the security try not to pass session id via url
you can use this inside any function or document ready. and change page name where you want to post value.
var postRecord = 'variable='+value;
$.post("PHP_Page_Where_you_are_using_session.php", postRecord, function(response,status, xhr){
if (status == "success") {
alert('done');
}
else if (status == "error") {
alert('Something went wrong, we are working to fix it');
}
});
on another page you can get post value within $_POST['variable'];
change name of variable to another one that you want to use.

Passing Javascript String to PHP output

I'm using this web service that prints out table using Javascript functions. I need the table to print out in plain html. This could be done if the Javascript string was transferred to a PHP file. So basically, this is similar to AJAX, but it is in reverse.
You could do that with ajax also
var value = 'This is a test';
if ($(value).val() != 0) {
$.post("jquery2php.php", {
variable:value
}, function(data) {
if (data != "") {
alert('We sent Jquery string to PHP : ' + data);
}
});
}
Important thing here is we are using $.post, so we are can gather the information with $_POST
We are sending only 1 value, named variable.
PHP part;
<?php
$jqueryVariable = $_POST['variable'];
echo $jqueryVariable;
?>
I believe, this is the most elegant way to achieve what you want.
not necessarily reverse, You could pass the string as a URL variable (www.yoursite.com/?string=yourvariable) and have PHP process it from there.
I've quoted a ugly method down here But i dont recommend this..
Instead store values in hidden fields in forms and access them through js or do something else..
<?php
echo "<script type=text/javascript>var x = $value; </script>";
?>
then use the variable x in js..
Anyway if you explain ur situation a bit clearer, we can give u best alternate solution
what you should do is use jQuery's .load() to load in the php's html results into the page
in the docs i've linked above they give this example
<script>
$("#success").load("/not-here.php", function(response, status, xhr) {
if (status == "error") {
var msg = "Sorry but there was an error: ";
$("#error").html(msg + xhr.status + " " + xhr.statusText);
}
});
</script>
EDIT
in response to your comment on Pixeler's post. You will not be able to just view the source of a ajax based solution. if your ultimate goal is to be able to read the source you have basically three options
send them to a new page
load in an iframe
do it the way you have, use fire fox and web devloper addon which will allow you to view generated source. (or something similar)
I'm not sure why there is a need to see the source users don't really care about the source typically the developer uses that

PHP Javascript variable help

Is there any way I could get the value of a html text field without using GET or POST or REQUEST? Alternatively, is there any way to get the field value in the same form or page else where.
This works with direct value such as "james", "system" and so on. the only problem is how do i make it work with html field values
Like:
<input type = "submit" onclick = "
<?php $username = "kut";
$result = checkname($username);
if($result)
{
?> alert("success"); <?php
}
else {?> alert("failed"); <?php
}?>
">
How can i replace "kut" with the value of a text field with id = "username" ?
<?php $username = "?>document.getElementById('username').value;<?php"?>
or something like that...???
In short, I need to get the value of a html field else where in the same page inside a javascript function, using PHP... like in the above javascriptFunction(), function
You have fundamental misunderstanding of how client-server architecture works.
PHP can be executed thousands of miles away, even days apart, from place where and when JavaScript does.
First PHP generates whole page, all of HTML, all of JavaScript source code (unexecuted), and then, after PHP is done and gone, browser starts running JavaScript.
These two can't be mixed together like you wanted, even though it may seem so in the PHP source code.
Although you can communicate with the server again using AJAX or similar, you probably should first understand how client-server architecture works and try to solve the problem without AJAX (e.g. handle all of it on server side, or all on client side).
You can not directly call a PHP function in JavaScript. You could set a JavaScript value from php before the page loads via echo. PHP is executed on the server while JavaScript is executed on the client side.
1> I suggest using jQuery to handle the Ajax part.
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script>
function check_user(){
var user_el=document.getElementById('username');
if(!user_el){ return false; }
var username=user_el.value; // this could all be replaced with $('username').val()
$.getJSON('check_var.php',{"user":username},function(data){
if(data.result=='error'){ alert('something was wrong with the PHP stuff'); }
alert(data.userstatus);
});
}
</script>
2> On the PHP side, as check_var.php, you need a script that takes the username input, checks the DB, and sends back the result as JSON data.
<?php
if(!isset($_GET['user']){ exit; }
$username=preg_replace('#['^\w\d]#','',$_POST['user']);
//do your database query. I assume you have that part all set.
//since I'm not filling in all of that, you'll need to fix this next part to work with your system
//let's pretend it's like $found=check_user($username);
//be sure to use mysql_real_escape_string or prepared statements on the $username var since you're working with user input
$status=$some_db_error ? 'error' : 'success';
$results=array('result'=>$status,'userstatus'=>$found);
header('Content-Type: application/json');
echo json_encode($results);

Categories