i have a page,called for example, test.html,i want to change it for example to test.php, when the user leaves the pages, is there a way to do so?
i know how to change it with php using rename..But how to call that when the user leave the page?
The first thing that comes to my mind is using the beforeunload event, triggered before the browser unloads the page to render another one, make an ajax call and let php do the rest.
jQuery:
window.onbeforeunload = function() {
$.post(
'rename-file.php',
{file: "this.html"}
).done(response) {
console.log('Response: ' + response);
}
}
PHP:
<?php
$oldname = $_POST['file'];
$newname = str_replace('.html', '.php', $oldname);
if(rename ( $oldname , $newname )) {
echo 'File renamed successfully';
} else {
echo 'File could not be renamed';
}
Will it work? It's something that has to be seen...
The onbeforeunload event might not work in all browsers, that's one of the downsides.
Other thing you have to think of is: Is this really necessary? To rename the same page I'm using to another extension knowing that the renaming process might be impossible due to the server using that file for rendering.
And last but not least, security, the above code is just a basic example, but remember that security is the key to happiness.
Related
I'm trying to figure out how this is posssible.
I want the user to be able to click on a link, and it will download a certain file. The file will be determined in an Ajax call (right now I just have a hard coded value).
Here's my situation though: When Ajax is called, the link given for the request is part of my framework which has a front controller and the url gets redirected. Thus, I can't just send the link to a file named like download.php and have just header code in there. It goes through the whole framework process, and eventually gets to the method that handles the Ajax call.
Here's my code:
$('.jobApplicationDownload').click(function() {
var that = $(this);
$
.ajax({
type : "POST",
url : "myfw/businessHome/applications/downloadJobApplicationItem",
data : {
"ajaxFileType" : that.attr("data-ftype"), "ajaxApplicationId" : that.attr("data-did")
},
success : function(html) {
alert(html);
},
error : function(XMLHttpRequest,
textStatus, errorThrown) {
alert("ERROR");
}
});
});
And here's the PHP. Remember this is after going through a Front Controller and a bunch of other methods. This is by no means the first stop after the Ajax call.
function downloadJobApplicationItem() {
//download.php
//content type
$fileName = "/myfw/common/jobs/resumes/eZACKe_1359081853_Week Three Sprints & Hurdles Workout 24th - 28th of Sept (1).pdf";
header('Content-disposition: attachment; filename='.$fileName);
header('Content-type: application/pdf');
//read from server and write to buffer
readfile('/myfw/common/jobs/resumes/eZACKe_1359081853_Week Three Sprints & Hurdles Workout 24th - 28th of Sept (1).pdf');
echo $_POST['ajaxFileType']. " ". $_POST['ajaxApplicationId'];
}
EDIT: Oh, and by the way, the result of this is the stuff I'm echoing being alerted, and no file download starting.
I'm confused when reading your question because I think you are getting mixed up between multiple questions.
Does the AJAX request reach the right handler?: the URL routing mechanism used in your framework and almost every other only matters here, and it doesn't affect whether you can reach your physical file. It's an entirely different matter. Regardless, I'd say your AJAX call is correct because the echo gets alerted
How to send the path to a file via AJAX call that gets redirected?: One trick you can consider using, which is similar to what you did, is to have a central download function as AJAX handler AND construct the path to the file using parameters sent with AJAX.
Why doesn't readfile output the desired file to the buffer: it's most likely that your path is incorrect or incompatible with server setting. It'd help if you could post your server configuration here.
And posting the name of your framework doesn't hurt either :)
I've solved this problem by buffering all the output and allowing the controllers to change or unset the redirect location. After all the controllers run, check the redirect location and write the redirect header (if necessary) at that time. Then output your buffer.
Something like this:
$appSettings = new AppSettings();
$appSettings->setRedirect(...);
$controller=new Controller($appSettings);
ob_start();
$controller->run(); //Your controller can call $appSettings->setRedirect(false);
$redirect=$appSettings->getRedirect();
if($redirect===false)
{
ob_end_flush(); //Send the buffer
}
else
{
ob_end_clean(); //Discard the buffer
header('Location: '.$redirect);
}
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?
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.
Frankly, it's just causing too much hassle in in v1.0 to have a functionality which requires three form submissions, with $_SESSION session data holding all of the intermediate stuff - only to have a user start an operation, then open a second tab and perform a second operation which tramples over the session data.
I doubt that this is malicious (but can’t discount it). More likely the user starts an operation, gets interrupted, forgets that they started or can’t find the original tab so starts again (then later finds the original tab and tries to complete the operation a second time).
Since I am coding in PHP I can detect the existence of session data on form submission (how would I do that with JS if the user as much as opens another tab – I guess that I would need Ajax – right?).
So, each time I start an operation I check for a flag in session data and if set I reload to a “I’m sorry, Dave. I’m afraid I can’t do that” page, else I set the flag and continue (remembering to clear it at the end of the operation).
I guess that that would work, but:
1) Is it acceptable to restrict browser apps to a single tab/instance?
2) Should I attempt to allow multiple instances in v2.0 ?
Any other comments, help or advice?
A better design would be to avoid storing user interaction state in the session. Put it in hidden form fields or something so that each client request carries its associated state with it. If you're concerned about the user tampering with it, use an HMAC to prevent that, and possibly encrypt it if it contains things the user shouldn't be able to see.
Only state that should be shared between tabs — like the user's login identity, or something like a shopping cart — should be stored in the session.
At most you can is keep a "last requested page" listing in the session file, with flags to indicate that the user shouldn't be allowed to move off it if it's one of these critical form flags. So if you're on form.php and it's a no-move-off one, then any new page loaded should present an "abort or close window" option.
You cannot prevent a user from opening up another tab/window, but you can prevent them from moving elsewhere in your site in those other windows/tabs.
However, consider that this is a very poor user experience. Imagine if Amazon trapped you in the shopping cart page and never let you on to another page without having to actually buy something. Consider updating your code to allow multiple different windows use the same form.
With every browser supporting tabbed browsing it would be a poor user experience to try to restrict browsing to a single tab (you might as well make a desktop app then).
One way you could solve this is by adding a CSRF token to your forms (as a hidden variable), that would be submitted with the request.
CSRF reference
There are many ways to generate the token, but essentially you:
create the token
store in your $_SESSION
output the form with <input type="hidden" name="{token name}"
value="{token value}" />
Then when the form submits you check $_REQUEST['{token name}'] == $_SESSION[{token name}]`.
If that token is different you know it wasn't the form you originally generated and thus can ignore the request until the real form comes in with the correct token.
One thing: if an attacker can figure out how you generate your CSRF tokens then they can forge requests.
Added the below script after I login(say dashboard.php)
<script>
$(document).ready(function()
{
$("a").attr("target", "");
if(typeof(Storage) !== "undefined")
{
sessionStorage.pagecount = 1;
var randomVal = Math.floor((Math.random() * 10000000) + 1);
window.name = randomVal;
var url = "url to update the value in db(say random_value)";
$.post(url, function (data, url)
{
});
}
else
{
var url = "url to remove random_value";
$.post(url, function (data, url)
{
sessionStorage.removeItem('pagecount');
sessionStorage.clear();
window.location = 'logout.php';
});
}
});
</script>
Added the below script in Header in rest of my pages - 'random_value' is from db for that user
<script>
$(document).ready(function()
{
$("a").attr("target", "_self");
if(typeof(Storage) !== "undefined")
{
if (sessionStorage.pagecount)
{
if('<?=$random_value?>' == window.name)
{
sessionStorage.pagecount = Number(sessionStorage.pagecount) + 1;
}
else
{
var url = "url to remove random_value";
$.post(url, function (data, url)
{
sessionStorage.removeItem('pagecount');
sessionStorage.clear();
window.location = 'logout.php';
});
}
}
else
{
var url = "url to remove random_value";
$.post(url, function (data, url)
{
sessionStorage.removeItem('pagecount');
sessionStorage.clear();
window.location = 'logout.php';
});
}
}
else
{
var url = "url to remove random_value";
$.post(url, function (data, url)
{
sessionStorage.removeItem('pagecount');
sessionStorage.clear();
window.location = 'logout.php';
});
}
});
</script>
If I were doing this now, I would probably code a single page AngularJs app (although any form of Js will do).
On start-up, look in local storage for a flag. If set, refuse to start, with suitable message, else set the flag & run the app.
Sure, a malicious user could get around it, since it's not a server-side check, but I would just refuse to support such.
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"];