Stop $_GET being processed after reload - php

I'm creating a link which appends a $_GET variable to the end of it for use of deleting files / other PHP tasks.
Delete file
Part of my PHP code looks for the variable and if it exists, it runs the unset function to remove the file, but when I reload the webpage, it obviously tries to remove the file again. Is there any way to remove the $_GET after it has been run once to stop the processing after a refresh?
<?php
if (isset($_GET['delete_file'])) {
if (file_exists($full_path.$_GET['delete_file'])) {
unlink($_GET['delete_file']);
} else {
echo "File ".$full_path.$_GET['delete_file']." doesn't exist";
}
}
?>
Delete file

You can use ajax to remove files so it won't refresh.
Delete file
<script>
function deletefile(filename){
var data = {delete_file:filename };
$.ajax({
url: 'delete.php',
type: 'post',
data: data,
success: function(response) {
// .. do something with response ..
// you can use window.location to refresh page
// or if you have js method to refresh page. you can call it here
}
});
}
</script>
In php file you can retrive with post
<?php
if (isset($_POST['delete_file'])) {
if (file_exists($full_path.$_POST['delete_file'])) {
unlink($_POST['delete_file']);
} else {
echo "File ".$full_path.$_POST['delete_file']." doesn't exist";
}
}
?>
But as the commenters say this is open to potential security issues. You need to take care of security if you use this approach in production.

Related

jQuery AJAX - Set PHP Session variable

I am looking to store a variable across an entire session so that when a user closes a promotional bar it stays closed and doesn't pop back up every time they navigate to a new page.
On page load I have the following:
$.ajax
({
url: 'promo.php',
type: 'post',
data : formData,
success: function(result)
{
alert(result);
}
});
The formData isn't too important right now as it isn't used.*
promo.php:
<?php
if (isset($_SESSION['promoBar'])) {
echo $_SESSION['promoBar'];
}
else {
$_SESSION['promoBar'] = "closed";
echo "does not exist";
}
?>
The idea is that on page load it will check if the $_SESSION['promoBar'] variable exists, and if it does, return it's value. Otherwise set a value.
Currently the alert always displays does not exist. I was expecting it to display does not exist the first time and then closed each time I navigate to a new page.
What have I done wrong?
Try this...
Use "session_start" before check
session_start();
if (isset($_SESSION['promoBar'])) {
echo $_SESSION['promoBar'];
}
else {
$_SESSION['promoBar'] = "closed";
echo "does not exist";
}
?>

Running a PHP Script without redirecting or refreshing the page

I am very new to PHP and Javascript.
Now I am running a PHP Script by using but it redirect to another page.
the code is
<a name='update_status' target='_top'
href='updateRCstatus.php?rxdtime=".$time."&txid=".$txid."&balance=".$balance."&ref=".$ref."'>Update</a>
How do I execute this code without redirecting to another page and get a popup of success and fail alert message.
My script code is -
<?PHP
$rxdtime=$_GET["rxdtime"];
$txid=$_GET["txid"];
$balance=$_GET["balance"];
$ref=$_GET["ref"];
-------- SQL Query --------
?>
Thanks in advance.
You will need to use AJAX to do this. Here is a simple example:
HTML
Just a simple link, like you have in the question. However I'm going to modify the structure a bit to keep it a bit cleaner:
<a id='update_status' href='updateRCstatus.php' data-rxdtime='$time' data-txid='$txid' data-balance='$balance' data-ref='$ref'>Update</a>
I'm assuming here that this code is a double-quoted string with interpolated variables.
JavaScript
Since you tagged jQuery... I'll use jQuery :)
The browser will listen for a click event on the link and perform an AJAX request to the appropriate URL. When the server sends back data, the success function will be triggered. Read more about .ajax() in the jQuery documentation.
As you can see, I'm using .data() to get the GET parameters.
$(document).ready(function() {
$('#update_status').click(function(e) {
e.preventDefault(); // prevents the default behaviour of following the link
$.ajax({
type: 'GET',
url: $(this).attr('href'),
data: {
rxdtime: $(this).data('rxdtime'),
txid: $(this).data('txid'),
balance: $(this).data('balance'),
ref: $(this).data('ref')
},
dataType: 'text',
success: function(data) {
// do whatever here
if(data === 'success') {
alert('Updated succeeded');
} else {
alert(data); // perhaps an error message?
}
}
});
});
});
PHP
Looks like you know what you're doing here. The important thing is to output the appropriate data type.
<?php
$rxdtime=$_GET["rxdtime"];
$txid=$_GET["txid"];
$balance=$_GET["balance"];
$ref=$_GET["ref"];
header('Content-Type: text/plain; charset=utf-8');
// -------- SQL Query -------
// your logic here will vary
try {
// ...
echo 'success';
} catch(PDOException $e) {
echo $e->getMessage();
}
Instead of <a href>, use ajax to pass the values to your php and get the result back-
$.post('updateRCstatus/test.html', { 'rxdtime': <?php ecdho $time ?>, OTHER_PARAMS },
function(data) {
alert(data);
});

Passing a $_SESSION failed when creating the $_SESSION within Ajax function

I have a simple registration form and the new comers will be registered with an ajax function. There I create a $_SESSION['is_logged'] when the registration is finished.
On var_dumb I get that the var is set. But when redirect on another page it is empty (I have included already the session_start() on the both pages...
I have read somewhere in the net that:
"Sessions are ONLY written on a page load/refresh".
Is this the case, or I have to look for some other issues within my code.
the ajax:
$.ajax({
url:"../controllers/register.php",
type:"POST",
data:res,
success: function(responce){
if (responce==1) {
$('#msg').addClass('msg-warning');
$("#form").css('display',"none");
$('#msg').append("<p>It seems that you have already submited the form. Click to "+
" <a href='login.php'>log-in</a> or to <a href='register.php'>register</a>.</p>");
}
else if (responce==2) {
$('#msg').addClass('msg-warning');
$("#form").css('display',"none");
$('#msg').append("<p>You have successfully created account. Click to "+
" <a href='start.php'>welcome</a> to start your .</p>");
$('.menu').append("<li><a href='logout.php'>Log out</a></li>")
}
else{
$('#msg').text(responce);
}
},
error: function(){
$('#msg').text("Opss, try again");
}
});
the register.php file:
if (isset($_SESSION['submited'])) {
echo 1;
exit;
}
include_once('../models/functions.php');
// Give the post parametters to another var
$arr=$_POST;
// function for uploading
$reg = registerMe($arr);
if ($reg === true) {
$_SESSION['submited']=1;
$_SESSION['is_logged']=1
echo(2);
}
else{
echo($reg);
}
exit;
The session_start(); is included in the header of the first page where from the ajax is started.And the second page - where the $_SESSION['is_logged'] is lost, again the session_start(); is part of dc_header(); function. start.php:
<?php
dc_header("Речник|Регистрация");
if (!isset($_SESSION['is_logged'])) {
#header("location: ../views/login.php");
var_dump($_SESSION);
}
?>
add
session_start();
to the top of register.php
You need to specify session_start, so your server who was commanded to execute "register.php" (either from ajax, direct call, browser scripts, cron job or whatever possible you-name-it) will handle the execution and the setting of $_SESSION variables in reference to the connected clients session. Server won't guess by itself that this is an "ajax call from an already session_start page". You need to specify that whatever is done in register.php is done in the current client's session.

JQUERY - .html() can also view php

The following script sends data with ajax for login
I want to format the data returned by using, in essence, a session variable ($ _SESSION)
I can do it
$("#login").click(function(){
username=$("#user_name").val();
password=$("#password").val();
$.ajax({
type: "POST",
url: "inc/login.inc.php",
data: "username="+username+"&password="+password,
success: function(msg){
if(msg!='false')
{
$("#login_form").fadeOut("normal");
$("#shadow").fadeOut();
$("#profile").html("<\?php print(\"$_SESSION['name'].\" <a href='inc\/logout.inc.php' id='logout'>Logout k2<\/a>\");\?>");
//valori menù
if(tipo=='1')
{$("#admin").css('display','none')}
}
else
{
$("#add_err").html("Username o password errata");
}
},
beforeSend:function()
{
$("#add_err").html("<img hspace='84' src='img/loading.gif' alt='Loading...' width='32' height='32'>" )
}
});
return false;
});
especially this is possible, in this way would print the name of the user just logged. otherwise I would not know how to do
$("#profile").html("<\?php print(\"$_SESSION['name'].\" <a href='inc\/logout.inc.php' id='logout'>Logout k2<\/a>\");\?>");
You can't insert PHP code after the script has already been processed.
Either pull it in via ajax, or include the actual PHP output into your javascript.
ie, in page.php
<script>
var sessionName = '<?php echo $_SESSION['name']; ?>';
</script>
then when you need it later
$("#profile").html(sessionName + " Logout k2");
JavaScript is client-side, it simply can't execute your php code.
You have to return something (eg. the username) in the php file you use in your ajax request and use that in your JS.
See the jQuery ajax docs for examples.
You'll need to serve the php code:
$("#profile").load("inc/login-header.inc.php");
login-header.inc.php
<?php
print($_SESSION['name'] . " <a href='inc/logout.inc.php' id='logout'>Logout k2</a>");
?>
The easiest way to send information back from the php script to the javascript, is by using the msg variable in
success: function(msg){
If you just want to send back one string, you just echo that one string in your php file and you will have its value in msg. If there are multiple variables you want to send back, you can package the result in a json object.
So assuming that everything you want to send back is contained in the php array named $output, you do a echo json_encode($output); at the end of your php script to get the whole thing in msg.
that won't work, as the PHP code is never processed.
In login.inc.php try something like this
<?php
if (!loginOK()){
echo "{login:false}";
} else {
echo "{login:true, name:'".$_SESSION['name']."'}";
}
and then on the client
success: function(msg){
if (msg.login){
// stuff
} else {
$("#profile").html(msg.name + $('<a>').attr('href', 'logout.php').html('logout'));
}
}

Jquery vs PHP - load an image into a div

I'm looking for a php script server side that load an image in a div on client side.
first shot:
ajax.php
if((isset($_POST['id'])) && ($_POST['id']=="loadphoto") && (ctype_digit($_POST['idp']))) {
$query=mysql_query("SELECT articleid, photoid FROM articles_photos WHERE id='".$_POST['idp']."'", $mydb);
if(mysql_num_rows($query)!=0){
while($row=mysql_fetch_array($query, MYSQL_NUM)) {
$path="./articles/photos/".$row[0]."/".$row[1];
}
echo $path;
}
}
myjs.js
function loadPhoto(mexid) {
$.ajax({
type: 'POST',
cache: false,
url: './auth/ajax.php',
data: 'idp='+escape(mexid)+'&id=loadphoto',
success: function(msg) {
$('.articleviewphoto1').find("img").each(function(){
$(this).removeClass().addClass('photoarts');
});
$('#'+mexid).removeClass().addClass('photoartsb');
$('#visualizator').html('<img src="'+msg+'" class="photoartb" />');
}
});
return false;
}
Are you looking to host a list of possible images in the PHP file and load different images based on the id you send? If so, you can set:
$Img = $_POST['idp'];
And use a switch statement to pass back the image file path:
switch ($Img){
case (some_value):
echo 'images/some_file.jpg';
break;
case (another_value):
echo 'images/another_file.jpg';
break;
}
Then place the file path in an tag and load that into $('#visualizator').html();
Am I on track at least with what you want? If so, I can flesh the answer out a bit.
I'm assuming the image already exists somewhere and isn't being generated on the fly. In the PHP script, you can access the variables with $_POST['idp'] and $_POST['id']. Do whatever processing you need, and then simply echo the URL. The variable msg in the javascript will be everything echo'd by the PHP script. Then, you could just do this:
$('#visualizator').html('<img src="' + msg + '" />');

Categories