I have the following PHP code that produces an error as the include files don't exist. I have not yet made them but I want to stop errors being produced (not just hidden). Is there anything I can put into my code that says "don't record any errors if the file doesn't exist, just ignore the instruction"
<?php
$PAGE = '';
if(isset($_GET['page'])) {
$PAGE = $_GET['page'];
};
switch ($PAGE) {
case 'topic': include 'topic.php';
break;
case 'login': include 'login.php';
break;
default: include 'forum.php';
break;
};
?>
use file_exists() to check if your file exists or not before calling include;
if (file_exists('forum.php')) {
//echo "The file forum.php exists";
include 'forum.php';
}
//else
//{
// echo "The file forum.php does not exists";
//}
Include the files only if they exist. You can add a check for existing file -
switch ($PAGE) {
case 'topic':
if(file_exists(path_to_file)) {
include 'topic.php';
}
break;
......
};
file_exists()
You seem to be looking for # operator which silences any errors from an expression, you can read more about it here: http://php.net/manual/en/language.operators.errorcontrol.php
Use file_exists() function:
<?php
$PAGE = '';
if(isset($_GET['page'])) {
$PAGE = $_GET['page'];
};
switch ($PAGE) {
case 'topic':
if (file_exists("topic.php")){
include 'topic.php';
}
break;
case 'login':
if (file_exists("login.php")){
include 'login.php';
}
break;
default:
if (file_exists("forum.php")){
include 'forum.php';
}
break;
};
?>
Documentation http://php.net/manual/en/function.file-exists.php
Related
I've a 'template' page which's my 'index.php', it include automatically all the basics stuff like header/footer and in the middle of that : a content page (it's a php script just included).
So, the problem is that when an error is catch in the included script (aka content) it automatically redirect to the original path without all the index stuff (eg. if '/user/login.php' is included and an error occurs, it will automatically redirect to the path of the included file instead of printing it in the index), how can I catch the error directly by the index instead of the script ?
<?php require_once('initializer.inc.php'); //need2be here because of session cache limiter warn ?> <html>
<head>
<?php
include('head_data.inc.php');
?>
</head>
<body>
<?php
include('header.inc.php');
?>
<?php
$page = 'index.php';
if(!isset($_GET['page']))
{
$page = 'home.inc.php';
}
else
{
switch($_GET['page'])
{
case '':
$page = 'home.inc.php';
break;
/**
* USER DEPT
*/
case 'connexion':
$page = 'utilisateur/connexion.inc.php';
break;
case 'moi':
$page = 'utilisateur/moi.inc.php';
break;
case 'mdp-oublie':
$page = "utilisateur/mot-de-passe-oublie.php";
break;
case 'gateway':
$page = 'utilisateur/gateway.inc.php';
break;
case 'panier':
$page = 'utilisateur/panier.inc.php';
break;
/*
* PRODUCTS DEPT
*/
case 'voir':
$page = 'produits/voir.inc.php';
break;
case 'categorie':
$page = 'produits/categorie.inc.php';
break;
case 'test': //just for debugging
$page = 'test.php';
break;
default:
echo '<p>404 Not Found - Cette page n\'existe pas</p>';
}
}
include($page);
?>
<?php
include('footer.inc.php');
?>
</body>
I had a PHP developer create a redirection script that redirects users in specific states to another URL, while letting everyone else visit the website.
The problem is it's redirecting everyone who doesn't match a state listed to the error URL, when it should be letting them visit the site.
I think there's a return missing? What do you guys think?
<?php
ini_set('display_errors',1);
ini_set('display_startup_errors',1);
error_reporting(-1);
require_once '/vendor/autoload.php';
use MaxMind\Db\Reader;
$databaseFile = '/geoip/GeoIP2-City.mmdb';
$ipWhiteList = ['123', '321'];
if(!in_array($_SERVER["REMOTE_ADDR"], $ipWhiteList)) {
$reader = new Reader($databaseFile);
$iso_code = $reader->get($_SERVER["REMOTE_ADDR"])['subdivisions'][0]['iso_code'];
if (!isset($_REQUEST['HTTP_REFERER'])) {
switch($iso_code) {
case NJ:
$url = 'http://example.com';
break;
case DE:
$url = 'http://example.com';
break;
default:
$url = 'http://www.example.com/?=error';
break;
}
$reader->close();
header('Location: '.$url);
die();
} else {
if(strpos($_SERVER['HTTP_REFERER'], "example2.com") > -1) {
echo "You were redirected from ".urldecode($_REQUEST['referer']).", but it is not available in your area (".$iso_code.").";
break;
} else {
echo "Welcome!";
break;
}
}
}
?>
Maybe try loading all the valid values, and checking to make sure it's valid, even if it's not NJ/DE.
if (in_array($state, array('NJ', 'DE'))) {
// Redirect
} elseif (!in_array($states, $all_states_array)) {
// Go to error.
}
The else is implied, in that the script will just continue working. You could structure this several different ways, depending on how much you need to extend it:
if (!in_array($state, $all_states_array)) {
// Error
}
if (in_array($state, array('NJ', 'DE'))) {
// Redirect
}
You could also add all the cases:
case 'DE':
// Do something;
break;
case 'NJ':
// Do soemthing;
break;
case 'PA':
case 'AL':
case 'NY':
case 'OK':
case 'TX':
...
// Valid, but not the right target.
break;
default:
// show error
Try this. If the state is not from NJ or DE, then do nothing.
<?php
ini_set('display_errors',1);
ini_set('display_startup_errors',1);
error_reporting(-1);
require_once '/vendor/autoload.php';
use MaxMind\Db\Reader;
$databaseFile = '/geoip/GeoIP2-City.mmdb';
$ipWhiteList = ['123', '321'];
if(!in_array($_SERVER["REMOTE_ADDR"], $ipWhiteList)) {
$reader = new Reader($databaseFile);
$iso_code = $reader->get($_SERVER["REMOTE_ADDR"])['subdivisions'][0]['iso_code'];
if (!isset($_REQUEST['HTTP_REFERER'])) {
switch($iso_code) {
case NJ:
$url = 'http://example.com';
header('Location: '.$url);
die();
break;
case DE:
$url = 'http://example.com';
header('Location: '.$url);
die();
break;
default:
}
$reader->close();
} else {
if(strpos($_SERVER['HTTP_REFERER'], "example2.com") > -1) {
echo "You were redirected from ".urldecode($_REQUEST['referer']).", but it is not available in your area (".$iso_code.").";
break;
} else {
echo "Welcome!";
break;
}
}
}
?>
EDIT: Very simple, figure it out. Just put an else{} without a } before and that will work for both ifs.
Well I wrote this code and it works ok
if($_REQUEST['pag']){
// Variável da página
$pag = $_REQUEST['pag'];
// Possíveis páginas
if($pag == "registrar"){
include "inc/register.php";
}
if ($pag == "recuperar"){
include "inc/recover.php";
}
}
But what if the user types ?pag=ofksaofkoasdkfkopsd ?
The page won't exist, so I want to include a file if that happens.
Is there a way to make this without using a list or something?
you can do this by switch and that would be better way then if because
The switch statement is similar to a series of IF statements on the same expression. In many occasions, you may want to compare the same variable (or expression) with many different values, and execute a different piece of code depending on which value it equals to. This is exactly what the switch statement is for. (manual )
switch($_REQUEST['pag']){
case "registrar":
include "inc/register.php";
break;
case :"recuperar":
include "inc/recover.php";
break;
default:
//default you want to include
break;
}
i hope you know about the complexity of the code and in your case switch case has less complexity in worst/average case
Try with if with else like
$pag = $_REQUEST['pag'];
// Possíveis páginas
if($pag == "registrar"){
include "inc/register.php";
}
elseif ($pag == "recuperar"){
include "inc/recover.php";
}
else{
include "inc/default.php"
}
Or you can use switch case where you can found default option like
switch($pag)
{
case "register":include "inc/register.php";
break;
case "recuperar":include "inc/recover.php";
break;
default : include "inc/default.php";
}
use if {} else{} or switch case.
You can use nested if else though.
At least give an eye on the docs - http://php.net/manual/en/control-structures.elseif.php
Why don't you want to use an array? That really would be the best way to go IMHO. Adding pages is easier, you get less duplicated code... It would also be trivial to load the array from a config file or DB instead of having it hard-coded in a later stadium. I see only benefits.
$pages = array( "registrar" => "inc/register.php",
"recuperar" => "inc/recover.php" );
$requestedPage = $_REQUEST["pag"];
if(array_key_exists($requestedPage, $pages)){
include $pages[$requestedPage];
}
else {
include "inc/error404.php";
}
some Use the switch command.
switch ($_REQUEST['pag']) {
case 'registrar':
echo "some text or action";
break;
case 'xxx':
echo "some text or action";
break;
case 'xxxx':
echo "some text";
break;
default:
echo "some text";
}
$pag = isset($_REQUEST['pag']) ? $_REQUEST['pag'] : null;
switch($pag) {
case 'registrar':
require 'inc/register.php';
break;
case 'recuperar':
require "inc/recover.php";
break;
default:
// Include your default page
}
In a non-dynamic language like C++ you'll have to use
if() elseif() else to compare non-constant values.
if ($condition1)
{
//code
}
elseif ($condition2)
{
//code
}
elseif ($condition3)
{
//code
}
...
else
{
//this is what happens when no other condition is true
}
switch is a better practice. check #user1752647's answer
Try with the elseif and else
if($pag == "registrar"){
include "inc/register.php";
}elseif($pag == "recuperar"){
include "inc/recover.php";
}else{
... //include a file if the page doesn't exist
}
Or you can do it with a switch
switch($pag){
case "registrar":
include "inc/register.php";
break;
case "recuperar":
include "inc/recover.php";
break;
default:
... //include a file if the page doesn't exist
}
Hope it will help you.
You also can use this code
$pages = array("register", "recover");
if (in_array($_REQUEST["pag"], $pages)) {
include $_REQUEST["pag"].".php";
}
else{
include "default.php";
}
I usually use this code below to include the page that I need into the body of my website to include the page when clicking on a link.
<?php
switch($_GET['page']){
case '1':
if(file_exists('main.php'))
{
include_once('main.php');
break;
}
default:
include_once('main.php');
break;
}
?>
but then I have to change this everytime i add a menu item by adding a case '2' ... etc
and now my question can this be written shorter/dynamically so that i just can add a link without having to change the piece of code everywhere?
ps: i did made it a little bit shorter.. but its still not good enough i think..
i also want to add this: i get my links from a ini file. i place it in there like this:
[navigation]
main.php = "Home"
if (!isset($_GET['page'])) {
$_GET['page'] = 'main.php';
}
switch ($_GET['page']){
case 'main.php':
case 'about.php':
case 'portfolio.php':
case 'tips.php':
$file = $_GET['page'];
break;
default:
$file = '404.html';
}
include_once $file;
is it possible to get this too from the ini file?
Try this:
$page = isset($_GET['page']) ? $_GET['page'] : "main.php";
if( file_exists($page)) include($page);
else include("404.html");
I have setup a new server and copyed my website on to it and the follow dont work (?p=home) includes pages.
Code:
if(isset($HTTP_GET_VARS['p']))
{
$page = $HTTP_GET_VARS['p'];
}
else
{
$page = 'home';
}
switch($page)
{
case 'home':
require('home.php');
break;
case 'login':
require('login.php');
break;
default:
echo('Error: There is no file on this server with that name');
}
On the other webhost it was on it worked fine am think in that it is a php.ini config file need editing can anyone help me?
Use the $_GET array instead of $HTTP_GET_VARS. The latter one is deprecated and probably disabled due to register_long_arrays.
This must do the trick :)
if(isset($_GET['p']))
{
$page = $_GET['p'];
}
else
{
$page = 'home';
}