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();
Related
I have an old script that uses the variable $action and then the switch statement. My problem is that in PHP 5. 7 I must declare the variable before it is used - so what do I declare the value to be for a variable that switches?
if(isset($pwd) && ($action == "login") &&
($pwd == $admin_password))
{
$admintest = 1;
$cookie_value = base64_encode("jmkads:$pwd");
// 86400 secs is 24 hours
setcookie("jmkads",$cookie_value, time()+86400);
}
else if(isset($jmkads)) {
$cookie_value = base64_decode($jmkads);
$cookie_value = explode(":", $cookie_value);
if(($cookie_value[0] == "jmkads") &&
($cookie_value[1] == $admin_password))
{
$admintest = 1;
}
}
if(!$admintest) {
Login_Page();
exit;
}
$db = connect_to_db();
if($db == 0) {
echo "Unable to connect to database, check if the MySQL".
" server is active and the settings of ad_config.php".
" are correct.\n";
}
else {
switch($action) {
case "add_client":
Page_Header("Add Client");
add_client();
break;
case "add_client2":
Page_Header("Add Client");
insert_client_data();
break;
and so on and so forth (there are many options) - I just wanted to show enough of the script so it was clear.
In your case, that variable would be declared as a string since your cases are matching strings.
This is the button
<a href="index.php?p=contact">contact<a>
This is the php script:
<?php
$p = isset($_GET['p']);
if($p == "artist")
{
include 'artist.php';
}
if($p == "contact")
{
include 'contact.php';
}
if($p == "releases")
{
include 'releases.php';
}
if($p == "downloads")
{
include 'downloads.php';
}
else
{
include 'home.php';
}
?>
So my script should include contact.php when I hit the button, but instead of including only contact.php it includes all php files. (this happens also with the other buttons).
Right now your $p variable equals true (this is what isset returns).
Change $p = isset($_GET['p']); to $p = $_GET['p']; and you'll be good
Even better:
$p = isset($_GET['p']) ? $_GET['p'] : false;
in this case you're secured against p being null
EDIT:
There is also another issue with your code - last else statement. It is always true when $p is different than downloads. So either you change every if to else if like this:
if($p == 'artist')
{
include 'artist.php';
}
else if($p == 'contact')
{
include 'contact.php';
}
(...)
else
{
include 'home.php';
}
or change this to switch statement:
switch($p)
{
case 'artist':
include 'artist.php';
break;
(...)
default:
include 'home.php';
}
isset($_GET['p']) returns true or false, so the code comparing $p to some strings will always return true and run the code inside the if block.
Change $p = isset($_GET['p']) simply to $p = $_GET['p']
To make this (more) reusable, you should alter your script a bit. Create a simple whitelist, check it the parameter is allowed, and if yes, include the $_GET['p']'s value directly:
$allowed = false;
if (isset($_GET['p']))
{
switch $_GET['p'] {
case 'contact':
$allowed = true;
break;
case 'artist':
$allowed = true;
break;
// and so on for all your IFs
}
if ($allowed === true) {
include $_GET['p'].'.php'
}
else
{
die('illegal parameter found')
}
}
I am building a search engine and webcrawler using PHP, and i would like to detect the language of a website, how would i detect the language of a page by:
Checking the URL for https://twitter.com/?lang=jap
if that is not set then i would like to:
Check the URL https://www.google.co.jp/
if i still can't find anything then i would to set default to English
the code i have so far for scraping pages is:
function crawl($url){
$html = file_get_html($url);
if($html && is_object($html) && isset($html->nodes)){
$weblinks[]=$url;
foreach($html->find('a') as $element) {
global $weblinks;
$link = $element->href;
$base_url = parse_url($url, PHP_URL_HOST);
if(substr($link,0,7)=="http://"){
$link = $link;
}else if(substr($link,0,8)=="https://"){
$link = $link;
}else if(substr($link,0,2)=="//"){
$link = substr($link, 2);
}else if(substr($link,0,1)=="#"){
$link = $html;
}else if(substr($link,0,7)=="mailto:"){
$link = "";
}else if(substr($link,0,11)=="javascript:"){
$link = "";
}else{
if(substr($link, 0, 1) != "/"){
$link = $base_url."/".$link;
}else{
$link = $base_url . $link;
}
}
if(substr($link, 0, 7) != "http://" && substr($link, 0, 8) != "https://" && $link != ""){
if(substr($url, 0, 8) == "https://"){
$link = "https://".$link;
}else{
$link = "http://".$link;
}
}
if(!in_array($link, $weblinks)){
$weblinks[]=$link;
}
}
$html->clear();
}else{
}
}
function info($weblinks){
foreach($weblinks as $link) {
$linkhtml = file_get_html("$link");
if($linkhtml && is_object($linkhtml) && isset($linkhtml->nodes)){
$titleraw = $linkhtml->find('title',0);
$title = $titleraw->innertext;
$des = $linkhtml->find("meta[name='description']",0)->content;
//detect language here
echo "<tr><td>".$title."</td><td>".$link."</td><td>".$des."</td></tr>";
$sql = mysql_query("INSERT into web once");
$title = "";
$des = "";
$linkhtml->clear();
}
}
}
To get the language from ?lang=:
$url = 'www.domain.org?lang=IT';
$url_parts = parse_url($url);
$lang = parse_str($url_parts['lang']);
You should then validate this with a switch/case statement and a list of languages that you support, like this:
switch ($lang) {
case 'EN':
//language is English
break;
case 'IT':
//language is Italian
break;
case 'FR':
//language is French
break;
default:
//?lang query was empty, or contained an unsupported language
$lang = FALSE;
} //end switch
After that, you can use this logic to determine whether you need to check the URL for the language:
if ($lang == FALSE) {
//code to determine language from TLD
}
Hopefully this will help get you started, although this is a big can of worms you're opening up. There are other things you need to check in order to be certain of the language of a website in addition to what you've mentioned. One of them is the language meta tag, which is like this: <meta name="language" content="english"> and goes in the head of the webpage, though not all websites use it.
Some multilingual websites, like mine, use a subdomain like http://it.website.com or http://fr.website.com
Others use query strings that are different from ?lang=. So you'll need to do a significant amount of research to cover all your bases.
I have a problem, I can't get the result of my code. When I try to debug the code. I using IF statement in my code.
It's just simple, example : if kelas(based on user_id login) = 1, then redirect it to kelas1.php, if kelas = 2, the redirect to kelas 2, else no have a kelas.
Here it's my code :
<?php
session_start();
if(!isset($_SESSION['user_id'])) {
header('Location: form_login_siswa.html');
}
$user_id = $_SESSION['user_id'];
include ("config.php");
$query = "SELECT kelas FROM t_siswa WHERE user_id = '$user_id'";
$hasil = mysql_query($query);
while ($data = mysql_fetch_array($hasil)) {
$kelas = $data['kelas'];
if($kelas = 1) {
include ("kelas1.php");
}
if($kelas = 2) {
include ("kelas2.php");
} else {
echo "Tidak ada kelas";
}
}
?>
Anyone, please help to solve the problem.
Appreciated with your helps.
Thank you.
You're missing an else and also not using the correct operator for comparison.
Also, switch around the comparison so that the first value is always a valid value.
if(1 == $kelas)
{
include ("kelas1.php");
}
else if(2 == $kelas)
{
include ("kelas2.php");
}
else
{
echo "Tidak ada kelas";
}
$kelas = 1
is assignment
$kelas == 1
is comparison
if($kelas = 1)
should be
if($kelas == 1)
Try using == instead of = . The "=" is an assignment operator and the expression gets the value of the right operand.
if($kelas == 1)
{
include ("kelas1.php");
}
if($kelas == 2)
{
include ("kelas2.php");
}
else
{
echo "Tidak ada kelas";
}
Also, the statement will always echo "Tidak ada kelas"; if ($kelas == 1). Was this intentional?
In your if statements using == for testing comparison rather than single = which is for assignment
Take a look at the elsif structure.
while ($data = mysql_fetch_array($hasil)) {
$kelas = $data['kelas'];
if($kelas == 1) {
include ("kelas1.php");
} elseif($kelas == 2) {
include ("kelas2.php");
} else {
echo "Tidak ada kelas";
}
}
Or the switch structure:
while ($data = mysql_fetch_array($hasil)) {
switch($data['kelas']){
case 1:
include ("kelas1.php");
break;
case 2:
include ("kelas2.php");
break;
default:
echo "Tidak ada kelas";
}
}
I'm attempting to optimise the following PHP If/Else statement. Could I rewrite the code to make use to case and switch, or should I leave it as it is, or what?
Code:
if(empty($_GET['id'])){
include('pages/home.php');
}elseif ($_GET['id'] === '13') {
include('pages/servicestatus.php');
}elseif(!empty($_GET['id'])){
$rawdata = fetch_article($db->real_escape_string($_GET['id']));
if(!$rawdata){
$title = "";
$meta['keywords'] = "";
$meta['description'] = "";
}else{
$title = stripslashes($rawdata['title']);
$meta['keywords'] = stripslashes($rawdata['htmlkeywords']);
$meta['description'] = stripslashes($rawdata['htmldesc']);
$subs = stripslashes($rawdata['subs']);
$pagecontent = "<article>" . stripslashes($rawdata['content']) . "</article>";
}
include("includes/header.php");
echo $pagecontent;
if(!$rawdata){
error_404();
}
}
Thanks
I hate switch statements, but its personal preference to be honest. As far as further optimization i'd suggest taking a look at some form of assembly language. It will give you some general ideas on how to make conditional statements more efficient. That is, it will give you a different out look on things.
if(!empty($_GET['id']))
{
if($_GET['id'] == '13')
{
include('pages/servicestatus.php');
}
else
{
$rawdata = fetch_article($db->real_escape_string($_GET['id']));
if (!$rawdata) {
$title = "";
$meta['keywords'] = "";
$meta['description'] = "";
} else {
$title = stripslashes($rawdata['title']);
$meta['keywords'] = stripslashes($rawdata['htmlkeywords']);
$meta['description'] = stripslashes($rawdata['htmldesc']);
$subs = stripslashes($rawdata['subs']);
$pagecontent = "<article>" . stripslashes($rawdata['content']) . "</article>";
}
include("includes/header.php");
echo $pagecontent;
if (!$rawdata) {
error_404();
}
}
}
else
{
include('pages/home.php');
}
switch would be appropriate if you had several discrete values for $_GET['id'] that you were checking for.
One suggestion I can make for the sake of readability is that
} elseif (!empty($_GET['id'])) {
only needs to be
} else {
Well i don't think it's necessary to switch to a swith
but you could change
} elseif (!empty($_GET['id'])) {
to just
}else{
You may want to look into breaking up your code into a MVC form; that would make it much easier to maintain your code. At least put the last clause into another file, probably called default.php and include it. Also, you might create an array of id => file key/value sets, lookup the id, and include the file.
if (isset($_GET['id'])) {
$pages = array(
0 => 'home.php',
13 => 'servicestatus.php'
);
if (isset($pages[$_GET['id']])) {
include('pages/' . $pages[$_GET['id']]);
} else {
include('pages/default.php');
}
}
Yes, switch is evaluate once, is efficient than if elseif,
and is easier to maintain with this given structure
switch ($_GET['id'])
{
case 13: ... break;
case 0 : ... break;
default: ... break;
}
I dont know, if you should, or should not, but here I wouldnt. The main reason is, that there is at least one statement, you can omit, and then, you will have just a if-elseif-else-Statement
if (empty($_GET['id'])) { /* code */ }
elseif ($_GET['id'] === '13') { /* code */ }
elseif (!empty($_GET['id'])) { /* code* }
is the same as
if (empty($_GET['id'])) { /* code */ }
elseif ($_GET['id'] === '13') { /* code */ }
else { /* code* }
In the block after that, the statement if(!$rawdata) is also duplicated.