How to set a default page id? - php

I am trying to display content depending on page id, however when I add nothing to the url, so just index.php I get an error saying that $p is not defined, how can I give this var a default value that's outside the switch case?
<?php
$p = $_GET['p'];
switch ($p) {
case 1:
$content1 = new login();
$content = $content1->displayLogin();
break;
case 2:
echo "ID is 2";
break;
case 3:
echo "ID is 3";
break;
default:
$content1 = new dbconnection();
$content = $content1->displayTable();
}

I understand that you want to make $p have a default value if $_GET['p'] is not defined.
You can do it like this:
$p = isset($_GET['p']) ? $_GET['p'] : 'defaultValue';
or, if you're on PHP 7:
$p = $_GET['p'] ?? 'defaultValue';

Replace:
$p = $_GET['p'];
With:
$p = !empty($_GET['p']) ? $_GET['p'] : default_id_value_here;

You can do the following:
$p = $_GET['p'] ?? <default value>; // e.g 1 or 3 etc.
Read more about it at this question: PHP syntax question: What does the question mark and colon mean?

Related

Why won't my switch statement generate the correct results?

I am using a condition and a switch to determine some default values for a few variables, but I am not getting the results that I expect.
When the link is clicked, I expect to execute the first case in the switch, but the desired variables are not overwritten.
This is my code that are into my index.php:
$titulo = '';
$keywords = '';
$descricao = '';
$post = empty($_GET['post']) ? '' : $_GET['post'];
$pagina = empty($_GET['p']) ? 'home' : $_GET['p'];
if (empty($post)) {
switch ($pagina):
case 'posts/myFile':
$titulo = 'this variable doesnot change the value on this file';
$keywords = 'this variable doesnot change the value on this file';
$descricao = 'this variable doesnot change the value on this file';
break;
case 'privacidade':
$titulo = 'Privacidade ';
break;
case 'ultimasnoticias':
$titulo = 'Ultimas Noticias';
break;
default:
$titulo = 'Home';
$pagina = 'home';
endswitch;
} else {
$titulo = 'Post';
}
My current results are:
$_GET["post"] = "myFile";
$titulo = "Post";
$keywords = "";
$descricao = "";
$pagina = "home";
My desired results are:
$_GET["post"] = "myFile";
$titulo = 'this variable doesnot change the value on this file';
$keywords = 'this variable doesnot change the value on this file';
$descricao = 'this variable doesnot change the value on this file';
$pagina = "home";
Why am I not able to update the variables using the first case statement?
Edit:
enter image description here
This is the code that are into my index.php to the nav bar:
<nav>
<ul>
<li>Início</li>
<li>Últimas Notícias
<li>Contato</li>
</ul>
</nav>
When you load index.php?post=myFile, you are generating the following element in the $_GET superglobal array:
$_GET = array ("post" => "myFile");
Then $post = empty($_GET['post']) ? '' : $_GET['post']; declares $post = "myFile".
This means that if (empty($post)) { evaluates to false (because it is not empty, it is myFile) and the switch-case block is ignored.
The else condition is executed. $titulo = 'Post';
Now, if you want the switch-case block to be executed, you must:
Change if (empty($post)) { to if (!empty($post)) {.
As for future trouble you may have within the switch-case block, make sure that you are identically matching the value for $pagina when writing each case. If you aren't sure about what values you are working with or what is being executed, just add echoes in each case to clarify.
I say this because posts/myFile is not the same string as myFile.
After more discussion about other hyperlinks, I'll recommend changing the default value for $pagina and extending the if logic to be more inclusive.
$pagina = empty($_GET['p']) ? '' : $_GET['p']; // I changed 'home' to ''
if ($post != '' || ($post == '' && $pagina != '')) { // I changed the logic

How to Concacenate $_SERVER['REQUEST_METHOD'] to a string

This is my code,
## GET REQUEST POSTING TO PAGE ( /example.php?name=something )##
## Expected Output : something
$var = '$_'.strtoupper($_SERVER['REQUEST_METHOD']);// concatenating with '$_'
var_dump($var."['name']");
echo '--<br>';
var_dump($var['name']);
echo '--<br>';
print_r($var."['name']"); //not working
echo '--<br>';
print_r($var['name']); //not working
Any idea how to make this work ? what is the correct way ?
Use double $
$var = "_" . $_SERVER['REQUEST_METHOD'];
var_dump($$var);
But this is "dirty hack"
For good code use if or switch for init variable.
switch($_SERVER['REQUEST_METHOD']) {
case "POST":
$var = $_POST;
break;
case "GET":
default:
$var = $_GET;
break;
}

Dynamically output the page title with php

I am trying to output the page title dynamically. I am using induces and this script is withing the header.php the goal is to output the header dynamically using a case/switch statement. here is my code:
<?php $title ;
switch($_SERVER['PHP_SELF']) {
case '/index.php':
$title = 'Home';
break;
case '/about.php':
$title = 'About';
break;
case '/services.php':
$title = 'Services';
break;
case '/portfolio.php':
$title = 'Portfolio';
break;
case '/staff.php':
$title = 'Staff';
break;
case '/contact.php':
$title = 'Contact us';
break;
} ?> <title><?php echo $title ?></title>
I am getting a error telling me my variable $title is not defined?
What i am doing wrong?
In your first line, you have
<?php $title ;
This $title ; shouldn't be there.
And, as Kailash Ahirwar already mentioned, it's always a good idea to provide a default value for your $title:
switch($_SERVER['PHP_SELF']) {
[...]
default:
$title = "Default title goes here";
}
Try to define $title before switch:
$title = "";
in $_SERVER global array, $_SERVER[PHP_SELF] contains full path of file like
/project_name/index.php or /project_name/about.php or /project_name/services.php
Here project_name is name of your project.
replace
case '/index.php'
case '/about.php'
case '/services.php'
....
to
case '/project_name/index.php'
case '/project_name/about.php'
case '/project_name/services.php'
.....
& also initialize $title in start of php file.
<?php $title = "";
switch ($_SERVER['PHP_SELF']) {
case '/project_name/index.php':
$title = 'Home';
break;
case '/project_name/about.php':
$title = 'About';
break;
case '/project_name/services.php':
$title = 'Services';
break;
case '/project_name/portfolio.php':
$title = 'Portfolio';
break;
case '/project_name/staff.php':
$title = 'Staff';
break;
case '/project_name/contact.php':
$title = 'Contact us';
break;
}
?>
for testing purposes
print_r($_SERVER);
and check for $_SERVER(PHP_SELF) value.
The code looks basically fine though you are missing a "default" block to catch anything that is not caught by any of the "case" statements.
though a beginner in php, i sorted this out on my own, and it is very simple and logical, consider title as string and it is initially empty one write on top $title = "";
when including header in home page just after inclusion write the value of title(reassigning value of variable)

Unable to set session under switch/case condition

I am unable to set session for $_SESSION['next'] under switch/case condition, while $_SESSION['user_id'] works perfectly before the condition. The script run into each condition of switch/case condition and redirect without setting $_SESSION['next']. Is there any specific reason why it fails to work? How to solve this?
require_once ('../src/facebook.php');
require_once ('../src/fbconfig.php');
//Facebook Authentication part
$user_id = $facebook->getUser();
if ($user_id <> '0' && $user_id <> '') {
session_start();
$_SESSION['user_id'] = $user_id;
switch((isset($_GET['page']) ? $_GET['page'] : '')){
case 'abc';{
$_SESSION['next'] = 'AAA';
echo "<script>top.location.href = 'https://www.example.com/xxx/'</script>";
exit;}
case 'def';{
$_SESSION['next'] = 'BBB';
echo "<script>top.location.href = 'https://www.example.com/xxx/'</script>";
exit;}
case 'ghi';{
$_SESSION['next'] = 'CCC';
echo "<script>top.location.href = 'https://www.example.com/xxx/'</script>";
exit;}
default;{
echo "<script>top.location.href = 'https://www.example.com/xxx/'</script>";
exit;}
}
} else {
echo "<script>top.location.href = 'https://www.example.com/xxx/'</script>";
exit;
}
Your switch is all wrong. Read the manual and try this:
<?php
switch ((isset($_GET['page']) ? $_GET['page'] : '')){
case 'abc':
$_SESSION['next'] = 'AAA';
echo "<script>top.location.href = 'https://www.example.com/xxx/'</script>";
break;
case 'def':
$_SESSION['next'] = 'BBB';
echo "<script>top.location.href = 'https://www.example.com/xxx/'</script>";
break;
case 'ghi':
$_SESSION['next'] = 'CCC';
echo "<script>top.location.href = 'https://www.example.com/xxx/'</script>";
break;
default:
echo "<script>top.location.href = 'https://www.example.com/xxx/'</script>";
break;
}
You're using exit in your switch, which (unless you want your script to end at the switch) is a no-no. Instead, you have to use the break keyword.
You also use semicolons and curly braces for each case.
case 'ghi';{ ... }
NO! Proper usage is
case 'ghi':
.
.
.
break;
Update: I just noticed you use this line:
if ($user_id <> '0' && $user_id <> '') { ... }
What is <> doing in PHP code? The "standard" operator for "not equals" is != in PHP. Use it correctly or no one will want to use your code.
Second update: You never set $_SESSION['next'] in your default case. It's very likely that your switch is always going to the default case. This would cause the behavior you're experiencing.
I suggest:
if (($user_id != '0') && ($user_id != ''))
(parentheses, and the != operator)
and also a DRYer switch:
$page = array_key_exists('page', $_GET) ? $_GET['page'] : '';
switch ($page) {
case 'abc':
$next = 'AAA';
$loc = 'https://www.example.com/xxx/';
break;
case 'def':
$next = 'BBB';
$loc = 'https://www.example.com/yyy/';
break;
... // and so on
}
if (isset($next)) {
$_SESSION['next'] = $next;
// If it does not work, you have problems with your session ID, maybe?
}
// I find this syntax easier
print <<<SCRIPT
<script type="text/javascript">
top.location.href = '$loc';
</script>
SCRIPT;
exit();

Help with a simple switch statement

I need to find the value of a variable and use it to add a class to a div, based on a switch statement.
For example, my variable is $link and if $link has google.com IN IT at all, I need $class to equal 'google', if $link as yahoo.com IN IT at all, $class then needs to equal 'yahoo'
So, I need something like this, but I'm not sure how/or if to use preg_match or something to check and see if the $link variable has the value we are looking for in it - see 'case' text below:
switch ($link) {
case 'IF link has Google.com in it':
$class = 'google';
break;
case 'IF link has Yahoo.com in it':
$class = 'yahoo';
break;
default:
# code...
break;
}
OR if there is a better way to do this, please let me know :D
Also, I'm good with using an IF ELSE statement as well..
Thanks
You want an IF-statement, not a switch statement
I think preg_matchis not necessary here.stripos is enough for it.
$url = $link->hits;
$pos_google = stripos($url,'google.com');
$pos_yahoo = stripos($url,'yahoo.com');
if($pos_google !== false)
{
$class = 'google';
}
elseif($pos_yahoo !== false)
{
$class = 'yahoo';
}
else
{
#code
}
Seems it could be simpler:
if(ereg("google", $link)){
$class = "google";
}else if(ereg("yahoo", $link)){
$class = "yahoo";
}else{
$class = "";
}

Categories