I am working on a script that calls a third party api, which needs a valid server hostname. Any of these format should be allowed, for example:
server.domain.com
server1.domain.com
something.domain.com
123456x.domain.tld
etc...
So, I have put together the following script to sanitize the server's hostname (in the event user inputs an invalid entry):
$server_hostname = 'test';
if (IsValidHostname($server_hostname))
{
switch (substr_count($server_hostname, '.'))
{
case 1:
$server_hostname = 'server.'. $server_hostname;
break;
case 0:
$server_hostname = 'server'. time() .'.default-domain.com';
break;
}
}
else
{
$server_hostname = 'server'. time() .'.default-domain.com';
}
var_dump($server_hostname);
function IsValidHostname($hostname)
{
// Src: http://stackoverflow.com/a/4694816
return (preg_match("/^([a-z\d](-*[a-z\d])*)(\.([a-z\d](-*[a-z\d])*))*$/i", $hostname)
&& preg_match("/^.{1,253}$/", $hostname)
&& preg_match("/^[^\.]{1,63}(\.[^\.]{1,63})*$/", $hostname)
);
}
The script appears to work. If an invalid hostname is supplied, it auto-generates a random one. Here are few test cases:
test -> server1451385708.default-domain.com
test.com -> server.test.com
123-test.com -> server.123-test.com
adam.test.com -> adam.test.com
e-v-e.test.com -> e-v-e.test.com
server12.test.co.uk -> server12.test.co.uk
However, I am not sure this is quite perfect yet. Here's a test that failed:
test.co.uk -> test.co.uk
I would prefer the outcome to be the following, when tld has 2 parts (e.g. co.uk):
test.co.uk -> server.test.co.uk
Any ideas on how I can achieve this?
Like this, this just covers the case that there are two ".":
if (IsValidHostname($server_hostname))
{
switch (substr_count($server_hostname, '.'))
{
case 1:
case 2:
$server_hostname = 'server.'. $server_hostname;
break;
case 0:
$server_hostname = 'server'. time() .'.default-domain.com';
break;
}
}
else
{
$server_hostname = 'server'. time() .'.default-domain.com';
}
or like this, which adds the info regardless of the number of ".":
if (IsValidHostname($server_hostname))
{
switch (substr_count($server_hostname, '.'))
{
case 0:
$server_hostname = 'server'. time() .'.default-domain.com';
break;
default:
$server_hostname = 'server.'. $server_hostname;
break;
}
}
else
{
$server_hostname = 'server'. time() .'.default-domain.com';
}
This is what I have settled on for now, let me know if there is a better way of doing it:
// Sanitize server's hostname
$serverHostname = strtolower(trim($server['hostname']));
if ($this->IsValidHostname($serverHostname)) {
switch (substr_count($serverHostname, '.')) {
case 1:
case 2:
if (substr($serverHostname, 0, 7) !== 'server.')
$serverHostname = uniqid() .'.'. $serverHostname;
break;
case 0:
$serverHostname = uniqid() .'.default-domain.com';
break;
}
} else {
$serverHostname = uniqid() .'.default-domain.com';
}
Related
I have this simple function to convert the number of comments of an user to types of members.
function checkMemberN($numMessages){
$n= $numMessages;
switch ($n) {
case ($n<50): $type="New"; break;
case ($n>=50 && $n<250):$type="Frequent";break;
case ($n>=250 && $n<1000): $type="Master";break;
default: $type="undefinded";
}
return $type;
}
echo checkMemberN(0);
It looks like it doesn't recognize zero (0), because when I put 1 or a higher number it retrieves the correct user type. What am I doing wrong?
When you use switch, the first case which returns a value equal to the given one is selected. In this case, your argument (zero) is a false-y value. That's why the first case that returns false is chosen: "Frequent".
To fix it, you can do this:
if ($n<50) {
$type = "New";
} else if ($n>=50 && $n<250) {
$type = "Frequent";
} else if ($n>=250 && $n<1000) {
$type = "Master";
} else {
$type = "undefined";
}
If you still want to use switch, you can change the argument to true:
switch (true) {
case ($n<50): $type="New"; break;
case ($n>=50 && $n<250):$type="Frequent";break;
case ($n>=250 && $n<1000): $type="Master";break;
default: $type="undefinded";
}
Here, the first case which returns true will be used.
I am trying to convert this simple set of else statement into a more easily readable switch;
$parts_arr = explode('.', $_SERVER['SERVER_NAME']);
if (in_array('dev', $parts_arr)) {
DEFINE('APP_ENV', "dev");
} else if (in_array('staging', $parts_arr)) {
DEFINE('APP_ENV', "staging");
} else if (in_array('local', $parts_arr)) {
DEFINE('APP_ENV', "local");
} else {
DEFINE('APP_ENV', "live");
}
However I have completely drawn a blank. I can't use a foreach loop and use the string as the case as APP_ENV cannot be redefined.
You may only check the whole server name.
switch($_SERVER['SERVER_NAME']) {
case 'mysite.com':
case 'www.mysite.com':
DEFINE('APP_ENV', "live");
break;
case 'dev.mysite.com':
DEFINE('APP_ENV', "dev");
break;
case 'staging.mysite.com':
DEFINE('APP_ENV', "staging");
break;
case 'mylocalhost.local':
DEFINE('APP_ENV', "local");
break;
default:
exit;
}
You can't turn it into switch-case structure unless you're doing string comparaison.
Maybe something like this :
$str = array_pop(explode('.', $_SERVER['SERVER_NAME']));
switch($str)
{
case 'dev' :
DEFINE('APP_ENV', "dev");
break;
// en so on
}
Sunil Pachlangia's solution won't work because he is comparing an array and a string
<?php
$parts_arr = explode('.', $_SERVER['SERVER_NAME']);
switch (true) {
case in_array('dev', $parts_arr):
DEFINE('APP_ENV', "dev");
break;
case in_array('staging', $parts_arr):
DEFINE('APP_ENV', "staging");
break;
case in_array('local', $parts_arr):
DEFINE('APP_ENV', "local");
break;
default:
DEFINE('APP_ENV', "live");
break;
}
I think I'd tend to shy away from splitting strings and analysing array elements, as #Almo-Do commented Be specific in some kind of config file.
$environments = array(
'localhost' = > 'local'
, 'staging.mysite.com' > 'staging'
// etc - see? now you can comment some out
//, 'mysite.com' => 'live'
);
Then simply
define ('APP_ENV', $environments[$_SERVER['SERVER_NAME']]);
Or even be a bit more defensive prior to that, something like :
if (!array_key_exists($environments[$_SERVER['SERVER_NAME'])) die('suitable msg');
So I have this commands handling:
$message = the entered message.
public function handleCommands($message, $username)
{
//Variables we're going to use
$space = strpos($message, ' '); # The first space.
$command = trim(substr($message, 1, $space)); # The command after the slash
$name = substr($message, $space + 1); # The name after the command.
switch ($command)
{
case 'ban':
$this->ban($name, $username);
break;
case 'prune':
$this->prune($username);
break;
case '':
echo 'Please use a command!';
break;
case 'test':
try
{
$this->test($name);
}
catch (exception $r)
{
echo $r->getMessage();
}
break;
}
}
This basically will check for the command.
$command = the entered word after the slash ( " / " ).
Can you see
case '':
This basically checks if there is no command after the slash.
Question: I want the system to check aswell, if the command exists in the cases.
For example:
user wrote:
/hello
But that command doesn't exists, considering we only have case 'ban', case 'prune', case 'test' and case ''.
there is no case 'hello', so it will throw an error.
Is there a function that does this sort of thing? How can I do this?
I believe what you're looking for is a default: case.
Example:
<?php
switch ($i) {
case 0:
echo "i equals 0";
break;
case 1:
echo "i equals 1";
break;
case 2:
echo "i equals 2";
break;
default:
echo "i is not equal to 0, 1 or 2";
}
?>
EDIT:
Fixed version of problem that was chatted about: http://privatepaste.com/bd34e7e63b
Use the case default:
switch ($command)
{
case 'ban':
$this->ban($name, $username);
break;
case 'prune':
$this->prune($username);
break;
case '':
echo 'Please use a command!';
break;
case 'test':
try
{
$this->test($name);
}
catch (exception $r)
{
echo $r->getMessage();
}
break;
default:
echo "That command does not exist.";
}
I'm try to send a value to a PHP file, but when I check, this value became null.
I send the value by: user_login.php?p_action=New_User
The code of user_login.php is:
require("include/session_inc.php");
require("include/user_handling_inc.php");
require("include/db_inc.php");
start_Session(false, false);
switch ($p_action) {
case 'Login': {
$l_flag = verify_User($p_in_username, $p_in_password);
if ($l_flag == "Not_Found") {
$l_flag = "New_User";
}
break;
}
case 'Save_Profile': {
$l_flag = "Save_Profile";
break;
}
case 'New_User':
$l_flag = "New_User";
break;
case 'Create_New_User':
$l_flag = "Create_New_User";
}
switch ($l_flag) {
case 'New_User': {
include "include/user_new_inc.php";
break;
}
case 'Save_Profile': {
load_User_Data(" username = '$p_in_username' ", false);
include "include/user_profile_save_inc.php";
break;
}
case 'Wrong_Password':
echo "Wrong Pass";
break;
case 'OK':
load_User_Data(" username = '$p_in_username' ", true);
store_User_Cookie($g_userdata->user_id);
include "include/user_profile_inc.php";
break;
case 'Create_New_User':
$l_user_id = create_New_User ($p_in_username, $p_in_email, 'Y');
if ($l_user_id != -1) {
store_User_Cookie($l_user_id);
echo "Success !! <br><br> \n";
echo "<a href\"/index.php\"> Back to Main </a>";
}
break;
}
First your code isn't correct please read more about using Switch here
second to access to any variable came from url you can use Global variable $_GET or $_REQUEST
and you can read more about them from here and here
and this is your code after fixing it please try to run it
<?php
require("include/session_inc.php");
require("include/user_handling_inc.php");
require("include/db_inc.php");
start_Session(false, false);
$p_action=$_GET["p_action"];
switch ($p_action) {
case 'Login':
$l_flag = verify_User($p_in_username, $p_in_password);
if ($l_flag == "Not_Found") {
$l_flag = "New_User";
}
break;
case 'Save_Profile':
$l_flag = "Save_Profile";
break;
case 'New_User':
$l_flag = "New_User";
break;
case 'Create_New_User':
$l_flag = "Create_New_User";
break;
}
switch ($l_flag) {
case 'New_User':
include "include/user_new_inc.php";
break;
case 'Save_Profile':
load_User_Data(" username = '$p_in_username' ", false);
include "include/user_profile_save_inc.php";
break;
case 'Wrong_Password':
echo "Wrong Pass";
break;
case 'OK':
load_User_Data(" username = '$p_in_username' ", true);
store_User_Cookie($g_userdata->user_id);
include "include/user_profile_inc.php";
break;
case 'Create_New_User':
$l_user_id = create_New_User ($p_in_username, $p_in_email, 'Y');
if ($l_user_id != -1) {
store_User_Cookie($l_user_id);
echo "Success !! <br><br> \n";
echo "<a href\"/index.php\"> Back to Main </a>";
}
break;
}
?>
you need to make the code like this friend
switch ($_GET["p_action"]) {
case 'Login': {
$l_flag = verify_User($p_in_username, $p_in_password);
if ($l_flag == "Not_Found") {
$l_flag = "New_User";
}
that well give you the value of the get!!!
Use $_GET to get your parameter.
Sometimes $_REQUEST is preferable since it access both get & post data.
2nd thing never trust the user input so you must use addslashes(); or real_escape_string() function to prevent attacks on the system.
So Code would be like this :
$var = addslashes($_GET['p_action']);
switch($p) {
case 'Login':
$l_flag = verify_User($p_in_username, $p_in_password);
if ($l_flag == "Not_Found") {
$l_flag = "New_User";
}
break;
"OTHER CASES HERE"
}
Notice that : Don't add { } for CASE. Read syntax for switch
here.
I am using latest version of TCPDF inorder to generate my PDF files and it is working fine
the problem where I stuck is I want to display file attachment annotation pane by default as it opens when user clicks on attachment image ...
I have tried the following :
$pdf->SetDisplayMode($zoom, $layout, $mode='UseAttachments');
but its not working.
Tell me how it is possible please ....
In my version of TCPDF, SetDisplayMode function looks like this:
public function SetDisplayMode($zoom, $layout='SinglePage', $mode='UseNone') {
if (($zoom == 'fullpage') OR ($zoom == 'fullwidth') OR ($zoom == 'real') OR ($zoom == 'default') OR (!is_string($zoom))) {
$this->ZoomMode = $zoom;
} else {
$this->Error('Incorrect zoom display mode: '.$zoom);
}
switch ($layout) {
//layout is set here
}
//page mode
switch ($mode) {
case 'UseNone': {
$this->PageMode = 'UseNone';
break;
}
case 'UseOutlines': {
$this->PageMode = 'UseOutlines';
break;
}
case 'UseThumbs': {
$this->PageMode = 'UseThumbs';
break;
}
case 'FullScreen': {
$this->PageMode = 'FullScreen';
break;
}
case 'UseOC': {
$this->PageMode = 'UseOC';
break;
}
case '': {
$this->PageMode = 'UseAttachments';
break;
}
default: {
$this->PageMode = 'UseNone';
}
}
}
Take a look at the last case. It will set a PageMode to "UseAttachments", but it looks to be defined in wrong way. Instead of case 'UseAttachments': there is case '':.
So, try to change your code to this:
$pdf->SetDisplayMode($zoom, $layout, '');