having a problem here with WordPress. I want to redirect the page to a specific .php file inside a folder (php/adminpage.php) whenever $_SESSION variable is equals to 1. Let's say the session variable is 1:
<?php
if ((isset($_SESSION['login']) && $_SESSION['login'] == '1')) {
header ("Location: php/adminpage.php");
?>
But the browser returns "Not Found". Any ways to get it to work?
UPDATE [SOLVED]: Using the full path works. Thanks to #andrewsi. Working code:
<?php session_start();
if ((isset($_SESSION['login']) && $_SESSION['login'] != '')) {
header ("Location: wp-content/themes/euro/php/adminpage.php");
}
?>
You're using a relative path:
header ("Location: php/adminpage.php");
That will look for a folder below where the current file is, and look for adminpage.php in there.
But WordPress does some funny things with page names and .htaccess, so your current page might not be where you expect it to be; it's generally always better to use a full path, which is a lot less ambiguous:
header("Location: /wp-content/themes/euro/php/adminpage.php");
And don't forget to exit after calling it, too, so code execution stops on the page from which you are redirecting.
Is this an actual URL location?
header ("Location: php/adminpage.php");
To my eyes it seems like a file system path. Because is your local setup at this URL:
localhost
And then this would be the location of that file?
localhost/php/adminpage.php
Also, I would clean up your code like so:
<?php
if (array_key_exists('login', $_SESSION) && isset($_SESSION['login']) && intval($_SESSION['login']) == 1)) {
header("Location: php/adminpage.php");
}
?>
By using array_key_exists you prevent unset index errors & by using intval you are assured there is a numerical value in place.
Related
No idea why this is not working. Here is the code:
if ((isset($_POST['cancel'])) && ($_POST['cancel'] == 'cancel'))
{
header('Location: page1.php');
echo $_POST['cancel'];
}
Instead of redirecting the page, this output's cancel to the webpage. It skipped over the redirect. Why? How can I fix this? page1.php is a real page located in the same folder as the current page. The above code is the very first lines of the php file. Nothing before it. Nothing. Not even whitespace.
This is likely a problem generated by the headers being already sent.
Why
This occurs if you have echoed anything before deciding to redirect. If so, then the initial (default) headers have been sent and the new headers cannot replace something that's already in the output buffer getting ready to be sent to the browser.
Sometimes it's not even necessary to have echoed something yourself:
if an error is being outputted to the browser it's also considered content so the headers must be sent before the error information;
if one of your files is encoded in one format (let's say ISO-8859-1) and another is encoded in another (let's say UTF-8 with BOM) the incompatibility between the two encodings may result in a few characters being outputted;
Let's check
To test if this is the case you have to enable error reporting: error_reporting(E_ALL); and set the errors to be displayed ini_set('display_errors', TRUE); after which you will likely see a warning referring to the headers being already sent.
Let's fix
Fixing this kinds of errors:
writing your redirect logic somewhere in the code before anything is outputted;
using output buffers to trap any outgoing info and only release it at some point when you know all redirect attempts have been run;
Using a proper MVC framework they already solve it;
More
MVC solves it both functionally by ensuring that the logic is in the controller and the controller triggers the display/rendering of a view only at the end of the controllers. This means you can decide to do a redirect somewhere within the action but not withing the view.
I have experienced that kind of issue before and now I'm not using header('Location: pageExample.php'); anymore, instead I'm using javascript's document.location.
Change your:
header('Location: page1.php');
To something like this:
echo "<script type='text/javascript'> document.location = 'page1.php'; </script>";
And what is the purpose of echo $_POST['cancel']; by the way?, just delete that line if what you want is just the redirection. I've been using that <script> every time and it doesn't fail me. :-)
Use #obstart or try to use Java Script
put your obstart(); into your top of the page
if ((isset($_POST['cancel'])) && ($_POST['cancel'] == 'cancel'))
{
header('Location: page1.php');
exit();
}
If you use Javascript Use window.location.href
window.location.href example:
if ((isset($_POST['cancel'])) && ($_POST['cancel'] == 'cancel'))
{
echo "<script type='text/javascript'>window.location.href = 'page1.php';</script>"
exit();
}
I had also the similar issue in godaddy hosting.
But after putting ob_start(); at the beginning of the php page from where page was redirecting, it was working fine.
Please find the example of the fix:
fileName:index.php
<?php
ob_start();
...
header('Location: page1.php');
...
ob_end_flush();
?>
I had similar problem...
solved by adding ob_start(); and ob_end_flush();
...
<?php
ob_start();
require 'engine/vishnuHTML.class.php';
require 'engine/admin/login.class.php';
$html=new vishnuHTML();
(!isset($_SESSION))?session_start():"";
/* blah bla Code
...........
...........
*/
</div>
</div>
<?php
}
ob_end_flush();
?>
Think of ob_start() as saying "Start remembering everything that would normally be outputted, but don't quite do anything with it yet."
ob_end_clean() or ob_flush(), which either stops saving things and discards whatever was saved, or stops saving and outputs it all at once, respectively.
For me also it was not working. Then i try with javascript inside php like
echo "<script type='text/javascript'> window.location='index.php'; </script>";
This will definitely working.
Pekka answered my question in the comments. He didn't post an answer, so I am now. Use the exit() method after the header redirect. For some reason the rest of the code of the page continues to execute after the header() method redirect. When the rest of the code executes, the echo statement is outputted to the page. And you can't redirect using the header function after you output to the page. To avoid rest of the code from executing, use exit(). Thanks Pekka.
UPDATE: When using the web browser Internet Explorer, I have noticed that $_POST['cancel'] is not reliable. I am not exactly sure why this is, but I suspect IE posts additional variables on a form submit, specifically the variable 'cancel' is posted. I solved this by using a variable name other than 'cancel'. The combination of using exit() and a unique variable name is working for me.
Neer to specify exit code here so php not execute further
if ((isset($_POST['cancel'])) && ($_POST['cancel'] == 'cancel'))
{
header('Location: page1.php');
exit(0); // require to exit here
}
Try adding
ob_start();
at the top of the code i.e. before the include statement.
Make Sure that you don't leave a space before <?php when you start <?php tag at the top of the page.
Be very careful with whitespace and other stuff that may affect the "output" already done. I certainly know this but still suffered from the same problem. My whole "Admin.php"-file had some spaces after the closing php-tag ?> down the bottom on the last row :)
Easily discovered by adding...
error_reporting(E_ALL);
...which told me which line of code that generated the output.
Try this, Add #ob_start() function in top of the page,
if ((isset($_POST['cancel'])) && ($_POST['cancel'] == 'cancel'))
{
header('Location: page1.php');
exit();
}
Use the following code:
if(isset($_SERVER['HTTPS']) == 'on')
{
$self = $_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];
?>
<script type='text/javascript'>
window.location.href = 'http://<?php echo $self ?>';
</script>"
<?php
exit();
}
?>
put < ?php tag on the top of your file (starting on frist line of document)
not:
--- Blank space or something ---
<?php
but:
<?php
..your code
header('Location: page1.php');
...
I have the following code in my index.php page:
<?php include("/includes/widgets.php") ?>
And in my widgets.php page:
<?php
header("Location: /");
?>
What I want to achieve with this is to redirect it if the user visits it, but allow it for including.
But I get the following error:
The webpage has a redirect loop
How can I fix/prevent the redirect loop, but still redirect the user and not the server.
Place the widgets.php file in a folder not accessible to HTTP clients. I.e on apache webserver, either put it above your document root (into it's parent) or use .htaccess file to block users from it.
e.g.
deny from all
I think I know what you need :)
Change code index file to next
define("IS_INDEX", true);
include("/includes/widgets.php"
Change code for widgets.php to next
if (!defined("IS_INDEX")) {
header("Location: /");
exit();
}
The issue is you are redirecting back to the same page, which then redirect again, and again, and again.
An easy fix would be to wrap the redirect in an if, and only redirect if they aren't already on the index page; but this is just patching what looks like an architectural problem.
Something like:
if (ltrim($_SERVER['REQUEST_URI'], '/') != 'index.php')
header('Location: index.php');
One way is to check if __FILE__, which is the file loaded, regardless of included or not matches up with the file requested which is in $_SERVER['REQUEST_URI'] (or $_SERVER['PHP_SELF']).
I use this on our development site in a page that is usually included to get the output as debugging.
if(basename($_SERVER['PHP_SELF'])===basename(__FILE__)){
//do some debugging
}
Typically you wouldn't use basename, but this is on a non-public facing development site and the file has a pretty unique name so I'm not worried about the file being included with another file with the same name or anything.
One possible way is to add a parameter to the redirection, e.g.
if (!$_REQUEST['redirect'])
header("Location: /ìndex.php?redirect=1");
That way redirection can happen only once.
Another way is to stop redirection if the user already is on the /. I´d suggest to combine both.
I have a php page which should be included in otherpage but no directly. Lets assume it as 1.php and the other page as 2.php
1.php
<?php
if($_SERVER['REQUEST_URI'] == "/1.php"){
header("Location:2.php");
}
else
{
//some code here
}
?>
2.php
<?php
include("1.php");
?>
this worked well on localhost/1.php and have been redirected to localhost/2.php
but this had made a problem with localhost/1.php?somegetmethod=data I found that anyone can access this page by typing ?something=something at the end of 1.php url. How to change the code which can redirect all url which starts with localhost/1.php
you could check if a substring is at a given position like this
if(strpos($_SERVER['REQUEST_URI'], "/1.php") === 0) {
this checks if the REQUEST_URI starts with /1.php (= is at position 0)
Use $_SERVER['PHP_SELF'] instead of $_SERVER['REQUEST_URI'].
try it:
if($_SERVER['SCRIPT_NAME'] == "/1.php")
$_SERVER['REQUEST_URI'] contains URI of requeted page, in yoour case it's 1.php?somegetmethod=data.
Change code like:
if(strpos($_SERVER['REQUEST_URI'], "/1.php") === 0){
header("Location:2.php");
}else{
//some code here
}
What you often see, for instance in MediaWiki, WordPress and many other such applications, is this:
1.php
if ( !defined( 'YOURAPPCONSTANT' ) ) {
// You could choose to redirect here, but an exit would make just as much
// sense. Someone has deliberately chosen an incorrect url.
echo "Cannot directly call this file.";
exit( 1 );
}
2.php
define('YOURAPPCONSTANT', 'It is defined');
include('1.php');
That way, 2.php is the entry of your application, regardless of the url used to reach it. I think this is a much safer and more flexible way, and it is used so often for a reason.
Is it possible to include a php in a website but when you refer to the website you included, then you'll be redirected. For example:
In index.php we have:
<?php include('http://mydomain.com/aboutme.php') ?>
but if you type http://mydomain.com/aboutme.php then you'll be redirect to index.php.
Is that possible?
Thanks
Yes, it is possible check the requested file name if it is aboutme.php redirect using header
$basename = basename($_SERVER['REQUEST_URI']);
$filename = basename($basename);
if ($filename == "aboutme.php")
{
header('location:index.php');
}
It is possible to do what you want, however because HTTP is stateless you will need to employ some type of state-maintaining device, aka either Cookies or Sessions, or even variables (since you're doing an 'include' from your index..
For instance, at the top of index, before your include you can put:
$fromIndex = true;
And then at the top of your aboutme.php file you can put a simple check:
if(!isset($fromIndex) || !$fromIndex) {
header("Location: index.php");
exit();
}
You may want to consider using a JavaScript redirect.
<script type="javascript">
window.location = "index.php";
</script>
Since the header() function needs to be at the top of the PHP file, it may fail if you're including it in some other file.
I want to check which URL someone is currently on. For example:
if(url=index.php?p=contact) {
echo the code i want to run,
}
else {
do nothing
}
So basically, I want to run a block of code when the user is on index.php?p=contact
The current requested URI path plus query is available in $_SERVER['REQUEST_URI'] and the filename of the processing script in $_SERVER['SCRIPT_FILENAME'].
If you need to check the complete path, see Gumbo's answer. If index.php is only accessible by navigating to that name directly (that is, you know if index.php is being executed the user must've gone to index.php, and you're not using something like URL rewriting), it probably makes much more sense to just check:
if($_GET['p'] == 'contact')
within index.php. If the condition is being reached, index.php is executing and clearly that's the page the user is on
This is what I did (to make it as I want with .htaccess); works for me since I do not have allot of pages to check. I used PHP_SELF:
<?php
if (htmlentities($_SERVER["PHP_SELF"]) === "/.../index.php") { // echo $_SERVER["PHP_SELF"] to see your path ..
header("Location: ./"); // I am using .htaccess, so I only want the page name and exclude ".php" in the address-bar (URL)
die();
} else if (htmlentities($_SERVER["PHP_SELF"]) === "/.../page2.php") {
header("Location: page2"); // I am using .htaccess, so I only want the page name and exclude ".php" in the address-bar (URL)
die();
}
?>