PHP redirection goes wrong - php

I submit all forms of my website to a specific page page form_submition.php, after processing the form data I redirect to another page index.php?page=some page using header function
but in one of my forms that named main_form I get a wrong redirection
if(isset($_POST['form1']))
{
// process form data
header('Location: ../index.php?page=some page')
}
if(isset($_POST['form2']))
{
// process form data
header('Location: ../index.php?page=some page')
}
$to=$_GET['to']
if (isset($_POST['main_form']) ) {
// process form data
}
header("Location: ../index.php?page={$to}&error_loc_{$error_loc}=1&err_msj=" . $err_msj, true, 302);
exit();
but it redirects me to mywebsite.com/folders/form_submitions.php?to=all_p
instead of mywebsite.com/index.php?page=all_p
any ideas?
UPDATE 1
I checked my code a lot, it seems that the header is not redirecting the page at all. the strange thing is that the page at mywebsite.com/index.php?page=all_p gets loaded but the url won't change and the css+js files not loaded because the relative path becomes invalid.
UPDATE 2
Further Checking my code, before submitting the main_form to form_submission.php I open a new window with javascript to print some data. the following is the form:
<form enctype='multipart/form-data' action='./forms/form_submitions.php?to=all_p' onsubmit="return checkfiles('attachfiles')">
.
.
.
<button id="main_form" name="main_form" class="btn btn-primary">Save Changes</button>
</form>
I call the following function when #main_form is clicked:
$("#main_form").on('click', function(event) {
newWin = window.open('printingpage.php?data='+ data);
setTimeout(function () { newWin.print(); }, 500);
});
Here the printing function won't return unless the print preview is closed. I think this creates the problem, because when I remove the newWin.print() function, everything works just fine.
is there any ways to make this printing asynchronous?

remove .. parts in your paths & try.
So the code will be :
if(isset($_POST['form1']))
{
// process form data
header('Location: /index.php?page=some page')
}
if(isset($_POST['form2']))
{
// process form data
header('Location: /index.php?page=some page')
}
$to=$_GET['to']
if (isset($_POST['main_form']) ) {
// process form data
}
header("Location: /index.php?page={$to}&error_loc_{$error_loc}=1&err_msj=" . $err_msj, true, 302);
exit();

Try this. Put your web link in your redirection link.
$data = array(
'page' => $to,
'error_loc_'.$error_loc => 1,
'err_msj' => $err_msj
);
header("Location: http://www.mywebsite.com/index.php?".http_build_query($data), true, 302);
Hope this helps.

Related

PHP calling function with parameters by clicking on HTML div

I am trying to make a delete button which I'll be able to delete some user from my database but main thing how to call PHP function with clicking on some div etc..
<div class="cross" onclick='<?php deleteUser("Nickname")?>'>X</div>
<?php
function deleteUser($username) {
//... code
}
?>
Html can't directly call php, it can do a separate call to load the same page, with the action.
<?php
function deleteUser($username){}
if($_GET['action'] == "delete")
{
deleteUser($_GET['username']);
}
?>
<a class="cross" href='?action=delete&username=NickName'>X</a>
The reason for this is because PHP runs on the server, BEFORE anything is sent to the browser. So it requires another page load to run the function by clicking something. It is possible to use javascript and AJAX calls to send a call to a php script without reloading the main page. Just look into Jquery's post or ajax features.
You cannot call a PHP function that resides on the server by just clicking on a div that exists on the client browser.
You need to trigger a Javascript event (using e.g. jQuery), that will call a function on the server (e.g. through AJAX), that after checking the parameters are correct and the user has the right of calling it will do what you seek.
There are ready-made frameworks that would allow you to do that.
Otherwise (after including jQuery in your HTML page) you can do something like,
<div class="cross" id="deleteUserButton" data-user="nickname">X</div>
<script type="text/javascript">
$('#deleteUserButton').on('click', function() {
let nick = $(this).attr('data-user');
$.post('/services/delete.php',
{
cmd: 'delete',
user: nick
}).then( reply => {
if (reply.status === 'OK') {
alert("User deleted");
}
});
<?php
$cmd = $_POST['cmd'];
switch($cmd) {
case 'delete':
$user = $_POST['user'];
if (deleteUser($user)) {
$reply = [ 'status' => 'OK' ];
} else {
$reply = [ 'status' => 'failure', 'message' => 'Doh!' ];
}
break;
...
header('Content-Type: application/json;charset=UTF-8');
print json_encode($reply);
exit();

PHP log out with AJAX call

I have a logout function that looks like this.
if ($_GET["argument"]=='logOut'){
if(session_id() == '') {
session_start();
}
session_unset();
session_destroy();
$host = $_SERVER['HTTP_HOST'];
$extra = 'index.php';
header("Location: http://$host/$extra");
exit;
}
My problem is that, If I inspect the page and look at the Network preview and response, it looks 'fine'.
There are two php files listed that was processed.
http://localhost:5000/inc/mainScripts.php?argument=logOut
which is where the function is located.
and http://localhost:5000/index.php
Which is where i would like to be redirected.
The Response tab in the Network of the inspect page area in chrome
contains the full login html page login.php but in the browser it remains in the same place. Like the header command has never been called.
What Am I doing wrong?
HTML AJAX call to this function:
$("#logout_btn").click(function() {
$.ajax({
url: './inc/mainScripts.php?argument=logOut'
})
});
SOLUTION
AJAX
$("#logout_btn").click(function() {
$.ajax({
url: './inc/mainScripts.php?argument=logOut',
success: function(data){
window.location.href = data;
}
});
});
PHP
if ($_GET["argument"]=='logOut'){
if(session_id() == '') {
session_start();
}
session_unset();
session_destroy();
$host = $_SERVER['HTTP_HOST'];
$link = "http://$host/index.php";
echo $link;
}
Try this instead.
if( isset($_GET['argument']) && $_GET['argument'] == 'logOut' && !empty( session_id() ) ) {
session_destroy();
header("Location: http://" . $_SERVER['HTTP_HOST'] . "/index.php");
exit;
}
Edit: If you're using AJAX, it'd be easier to send the url from your php script back to your javascript and redirect from there.
You are probably running into the same common problem that many people run into when people first start to program in PHP.
Calls to header() only works when there are NO previous HTML output generated. If there are any HTML output generated, even just a single space, calls to header() will fail. To get around this problem, use functions such as ob_start() and ob_end_flush().

what does a question mark mean before a php form action

<form action="?login" method="POST">
<button>Login with Google</button>
</form>
I have seen many different actions for a form action that must usually point to a php file ro ... but what does the ?login mean
more information : This is from the openid library and after the button is clicked it goes to a google allow page! and after our login is complete the button will not be shown! what does this mean ?
After the answers I know what the ?login does but why doesen't the button be shown after the login has completed ???
Full code :
<?php
require 'openid.php';
try {
# Change 'localhost' to your domain name.
$openid = new LightOpenID('localhost');
if(!$openid->mode) {
if(isset($_GET['login'])) {
$openid->identity = 'https://www.google.com/accounts/o8/id';
header('Location: ' . $openid->authUrl());
}
?>
<form action="?login" method="post">
<button>Login with Google</button>
</form>
<?php
} elseif($openid->mode == 'cancel') {
echo 'User has canceled authentication!';
} else {
echo 'User ' . ($openid->validate() ? $openid->identity . ' has ' : 'has not ') . logged in.';
}
} catch(ErrorException $e) {
echo $e->getMessage();
}
This is a query string parameter. It means that the form should be submitted to the current script url, but a ?login parameter should be appended
The script than sends a redirect header to send the user to the google login page.
It is just the part of the (relative) URL that indicates the start of a query string.
As the others said, it means that your form will be submited to the actual page with the query parameter appended.
If you are on page example.com/login.php and you submit this form, it will be sent at the page example.com/login.php?login which is useful if, for example you want to validate the input before redirecting to another page.
See what is ? in url
A short example would be something like
if(isset($_REQUEST['login'])){
// validate the login form
// if the form is valid, redirect to the logged in page
// else show any type of error message
}
// The regular page in itself displayed the same as before the form submitting
// with an added error message if needed
this means submitting the form on the same PHP script with additional query string. e.g if the form file name is abc.php then after submit URL become abc.php?login where you can get login in GET

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.

Redirect to original page after logging in (Codeigniter)

The entire website requires a user to login before viewing the page. If the user is not logged in, he gets redirected to the login/registration page.
Problem: When a user that is not logged in types in a url like http://www.domain.com/listings/1234 , he will be shown that page, but with a darkened page that prevents the user from interacting with the page (jQuery stuff, not a problem here), and a popup modal box with a link to the (Tank Auth) login page http://www.domain.com/login.
After logging in from the login page, the user will be redirected back to the usual page one gets after logging in, ie: http://www.domain.com but that page is passed the variable 1234.
In short: I want the user that has not logged in and has entered the website at http://www.domain.com/listings/1234 to NOT be redirected to http://www.domain.com/login yet, but instead remain on http://www.domain.com/listings/1234 and be shown a modal box with a link to the login page http://www.domain.com/login where if he logins in, he will be redirected back to http://www.domain.com/ instead of the usual page he gets after login and be passed the variable 1234.
How can this be done using Codeigniter?
This is what I have now:
Listings controller
function index(listing_id) {
$this->load->module('auth');
if(!$this->auth->tank_auth->is_logged_in()) {
redirect('login');
}
// Some calls to database etc here...
$this->load->view('listings', $data);
}
There are several ways that your question can be accomplished. Hopefully this solution would give some ideas on how to accomplish this.
The solution below uses jquery ui dialog to display the modal and jquery .ajax to handle the login form submission.
Conditionally put this code at the bottom of you page before the </body> tag if the user is not logged in.
<?php if($this->auth->tank_auth->is_logged_in()){ ?>
<div id="dialog-wrap" class="modal" >
<?php echo $this->load->view('login_form'); ?>
</div>
<script>
$('#dialog-wrap').modal({
modal: true,
autoOpen: true,
});
$('#login-form').submit(function(){
//use .ajax to submit login form and check credentials.
$.ajax({
type: 'POST',
url: <?php echo base_url(); ?>"login.php",
data: "username="+$('username').val()+'&password='+$('password').val(),
dataType: 'json',
success: function(returnData){.
if(returnData.status){
//close modal box
}else {
//display message that login failed.
}
}
});
});
</script>
?>
Your ajax login controller
function login(){
//Use tank auth to validate login information.
if(authentication is successful) {
$return_data = array(
'status' => true,
'msg' => 'Login Successful'
);
}else {
$return_data = array(
'status' => false,
'msg' => 'Login failed'
);
}
//Use echo instead of return when you are sending data back to an jquery ajax function.
echo json_encode($data);
}
If you do it this way then you won't have to rely on codeigniter redirects everything will be handled through ajax.
I hope this gives you an idea of how to handle this.

Categories