how to forcefully send invalid url queries to 404 page - PHP - php

I have custom 404 page and working fine for pages that does not exist.
But I also want to show 404 page if someone query_string found to be missing/invalid/null from url.
How can I do so?
www.example.com/mypage.php?param1=value1
if(isset($_GET['param1']) && $_GET['param1'] !='')
{
//general code
}
else {
// Here I want to redirect to 404.php
}
also my 404 page is being accessed directly, and I want to prevent it.

I solved this using include, as Marco Mura suggested in his comment.
www.example.com/mypage.php?param1=value1
if(isset($_GET['param1']) && $_GET['param1'] !='')
{
//general code
}
else {
include "404.php";
}

Try to redirect users to 404 page through header() function like this:
www.example.com/mypage.php?param1=value1
if(isset($_GET['param1']) && $_GET['param1'] !='')
{
//general code
}
else {
header('Location: http://www.example.com/404.php');
exit;
}

Related

wp_redirect causes "Cannot modify header information"

I am trying to restrict users who are not logged in from accessing certain pages on the website by adding:
if (!is_user_logged_in()) {
wp_redirect(esc_url(site_url('/')));
exit();
}
But it generates the error
Cannot modify header information.
See screenshot of
Where did you put your code?
Try adding this to your functions.php file.
add_action('init', 'check_for_user_logged_in');
function check_for_user_logged_in()
{
if (!is_user_logged_in()) {
$currentUrl = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$redirectUrl = site_url('/');
if ($currentUrl != $redirectUrl) {
wp_redirect($redirectUrl);
die();
}
}
}
The redirection should be the first thing you send to the user.
Here, you called get_headers() before, which sent the headers to the user and thus you cannot use a redirection afterwards.
Try calling the wp_redirect at the beginning of your file.
<?php
if (!is_user_logged_in()) {
wp_redirect(esc_url(site_url('/')));
exit();
}
// ... Rest of your php file
Just try by adding ob_start before redirect as below
if (!is_user_logged_in()) {
ob_start();
wp_redirect(esc_url(site_url('/')));
exit();
}
Or redirect using javascript as below
<?php if (!is_user_logged_in()): ?>
<script>
window.location.href='your url';
</script>
<?php endif; ?>

Use index.php for login and main content

Currently I have a very basic PHP login system. My index.php file simply checks if a session is set, if it isn't it redirects them to login.php. I see a lot of websites where the same effect is achieved but through the index of the site entirely.
For example, at http://twitter.com if I am not logged in I will land at simply twitter.com. If I am logged in I will also land at twitter.com just with different content. How can I achieve the same effect on my site?
I'm sure this is very basic but it's something I am yet to explore.
Thanks
A simple example how you can handle your welcome/user index.php site:
index.php
require_once('configFile.php'); // session_start();.. and other stuff
if ($logged) {
require_once('userLogedIn/index.php');
} else {
require_once('welcome/index.php');
}
Lots of ways to do this but the below is a primitive example. Assuming your pseudo logic is something like...
if (!$logged_in) {
redirect('login.php');
}
else {
// show page content
}
You can do...
if (!$logged_in) {
include('login.php');
}
else {
include('page-content.php');
}
The includes aren't necessarily required but help to keep it tidy.
First of all answer yourself the question if your index file can contain user supplied stuff. If so DON'T DO IT! The problem are possible attack vectors from that user supplied stuff against your login.
That said let me help you:
<?php
$session_id = session_id();
if (!empty($_COOKIE[$session_id]) && session_start() !== false && isset($_SESSION["user_id"])) {
echo "index page";
}
elseif (isset($_POST["login"])) {
// validate login ...
if ($valid_login === true) {
if (session_status() === PHP_SESSION_ACTIVE) {
session_regenerate_id();
}
else {
session_start();
}
$_SESSION["user_id"] = $user_id;
}
}
else {
echo "login page";
}
?>
I think you get the idea here. We now have a single file taking care of everything.

Understandin PHP 404 redirection related to invalid get request

Ok, am using traditional php, no frameworks, nothing, I am using simple procedural way, now my question is I was searching for a while but am not getting an answer to my question, I am not using .htaccess files as of now, but I really need to understand how 404 error works? I am having a website, where I show post's related to category, say category=php, so I pass this as a get request
$_GET['category'] == 'php';
Now currently what am doing is something like this :
$pocategory = $_GET['category'];
if($pocategory == 'php' || $pocategory == 'javascript') {
//Then show related posts
} else {
header('Location:404.php');
exit;
}
I mean I just want php and javascript as valid request's value, rest I want to redirect to 404 but am not understanding how to do it so I did this way, what if am having more than 50 categories? I cant list them all in this if condition, Inshort how to detect whether the given get request value is invalid or not..
Any help will be much appreciated.
.htaccess is the way to do this.
ErrorDocument 404 index.php?404
that line will tell apache what file to load. The example above calls the main index.php script.
add something like this to the top of your index.php file:
$error_404 = isset($_GET["404"]) ? true : false;
now you can detect if you have a 404 error request. $error_404 will be true, so why not add a simple function:
function error_404($error_404)
{
if($error_404 == true)
{
// do some error stuff here, like set headers, and some text to tell your visitor
}
}
now just call your function:
error_404($error_404);
best to do that immidiatley after the get handler:
error_404($error_404)
$error_404 = isset($_GET["404"]) ? true : false;
or combine the two into one line:
error_404($error_404 = isset($_GET["404"]) ? true : false);
to address the question, add this to the relevant script:
$pocategorys_ar = array("php","javascript");
if (!in_array($pocategory, $pocategorys_ar))
{
error_404(true);
}
Make sure it has access to the error_404() function.
You could put all categories inside an array like this:
$pocategories = array
(
'php',
'javascript'
);
if (in_array($pocategory, $pages))
{
// ...
}
else
{
header('Location:404.php');
}
Another thing you could do is creating a html/php file for every category and do it like so
if (is_file('sites/' . $popcategory . '.php')
{
include('sites/' . $popcategory . '.php');
}
else
{
header('Location:404.php');
}

Redirect to referer url in codeigniter

In messaging system of my project when you get a message from a user you a email alert saying that the another user has sent a message to view the message click here (i.e the url of message) So if the user is not logged in to system he gets redirect to login page and after login it should get back to the referer url. I have made a basecontoller in core folder and extending the CI_controller the authenticating code is as follows.
function authenticate($type = 'user')
{
if($type == 'user')
{
if($this->user_id)
{
// user is logged in. check for permissions now
}
else
{
// user isnt logged in. store the referrer URL in a var.
if(isset($_SERVER['HTTP_REFERER']))
{
$redirect_to = str_replace(base_url(),'',$_SERVER['HTTP_REFERER']);
}
else
{
$redirect_to = $this->uri->uri_string();
}
redirect('user/login?redirect='.$redirect_to);
exit;
}
}
if($type == 'admin')
{
if($this->session->userdata('admin_id') && $this->session->userdata('user_type') ==5)
{
// Admin is logged in
}
else
{
redirect('admin/login');
exit;
}
}
}
The referer url is "http://example.com/project/pm/view_conversation?id=11"
now the problem is I am getting referer url till view_conversation and not able to get the id part.
Any suggestion ?
Thank you.
This can help:
CI 2+
https://www.codeigniter.com/userguide2/libraries/user_agent.html
CI 3+
http://www.codeigniter.com/userguide3/libraries/user_agent.html
Below solution is for Codeigniter version 3
$this->load->library('user_agent');
if ($this->agent->is_referral())
{
echo $this->agent->referrer();
}
UPDATE: interesting and useful information on how to obtain referrer information with the same user_agent library
https://www.tutorialandexample.com/user-agent-class/
How about just
redirect($_SERVER['HTTP_REFERER']);
Using php's $_SERVER global variable.
This worked for me!
Put that code in your Login Controler
function index() {
$this->load->library('user_agent'); // load user agent library
//Set session for the referrer url
$this->session->set_userdata('referrer_url', $this->agent->referrer() );
}
After Login Redirection Code
// user is authenticated if referrer is there
if( $this->session->userdata('referrer_url') ) {
//Store in a variable so that can unset the session
$redirect_back = $this->session->userdata('referrer_url');
$this->session->unset_userdata('referrer_url');
redirect( $redirect_back );
}
Because you have double question mark in the url, the browser ignores the url part after the second one. Use urlencode for you redirect part, like so:
redirect('user/login?redirect='.urlencode($redirect_to));
I've tested it out and it works this way.
By default CI is configured to ignore the query part of the URL (the part after the '?').
See: http://codeigniter.com/user_guide/general/urls.html

Redirect if page is linked to directly javascript or php?

I need some javascript or php code to detect if user has linked directly to me site's page so I can then redirect it to the homepage.
Is this possible?
Check is the the host of your server is in the http_referer (it is the last url visited by the user).
function is_direct_link() {
return (!empty($_SERVER['HTTP_REFERER']) && stripos($_SERVER['HTTP_REFERER'], $_SERVER['HTTP_HOST']) === false);
}
if (is_direct_link()) {
header('location: http://www.google.com');
exit();
}
<?php
$referrer = $_SERVER['HTTP_REFERER'];
// see if they are visiting from another website
if (!empty($referrer) && stripos($referrer, 'mydomain.com') === false)
{
// redirect them to the main site
header('Location: http://mydomain.com/');
// stop php from going further
exit;
}
Something like that is (i think) what you're looking for.
If the referrer is empty, this will redirect to the home page:
<?php
if(!empty($_SERVER['HTTP_REFERER']) && stripos($_SERVER['HTTP_REFERER'], 'example.com') header("Location: example.com");
?>
Note that the referrer is not bulletproof by any stretch but it does the basic job.

Categories