How can I do this easily:
$ipp='/(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)([\s\:\-]+[0-9]{2,5})/'; // IP Address
preg_match_all($ipp, $line, $matches);
This matches ip:port in multiple formats. I want to define a second criteria like you would do it at a shell script with (A && B) that only match if the port number is NOT "143" exactly. In the future I would might like to extend this with additional ports like "993", "995" etc.
Thanks
Whenever I have to do a task like that, I create a custom function for it so I could modify it, add - remove parameters, if it needs more functions, I create an object. in that case I will just create a function for that tsak.
function check($ip, $against){
$ipChecked = false;
$againstChecked = false;
//pregmatch statement with the ip, if true, the $ipChecked = true;
//pregmatch $against with the ip, if false then $againstChecked = true;
if ($ipchecked === true && $againstChecked===true)
return true;
else
return false;
}
Feel free to customise that function to add any parameter you want
then use it like this:
$ip = '145.254.021';
$against ='143';
$check = check($ip, $against);
if($check === true){
//Insert code here...
}
Did I understood your question well?
Related
So I'm making a webshop, well, trying to atleast for a course project using WAMP. But when trying to register new users and in the process checking their password against a list of common ones the use of fgets() returns an empty string.
if(empty(trim($_POST["password"]))){
...
} elseif (!checkPassword($_POST["password"])) {
$password_err = "Password to common.";
echo "<script>alert('Password to common.'); location.href='index.php';</script>";
}
The checkPassword() is where the fault lies.
function checkPassword($passwordtocheck) {
$passwordtocheck = strtolower($passwordtocheck);
$common_passwords = fopen("commonpasswords.txt", "r");
while(!feof($common_passwords)) {
$check_against = fgets($common_passwords);
echo "<script>alert('Checking $passwordtocheck against $check_against.'); location.href='index.php';</script>";
if($check_against == $passwordtocheck) {
fclose($common_passwords);
return false;
}
}
fclose($common_passwords);
return true;
}
Lets say that I input the password 12345678 when registering, then the scripted alert will say "Checking 12345678 against ." and send me back to index.php. So it looks like it doesn't succeed in reading the file at all. The commonpasswords.txt is in the same folder as the rest of the files and with a single password on each row.
And there is no problem opening the file to begin with either, if I do this instead:
$common_passwords = fopen("commonpasswords.txt", "a");
fwrite($common_passwords, "test");
'test' will appear at the bottom of the file under the existing words on its own row without a hitch. And this is where I'm at, would appreciate whatever input people can give!
EDIT; I do understand that this probably breaks a ton of good-practice 'rules' in general and regarding security. But the website is not really supposed to function or look good, it just need to barely work so that we can later try and use different methods of attacking it and the connected database.
If you insist on doing this yourself – which I do not recommend – you can simplify things a lot by using the file() function. This returns an array of every line in the file. Then use array_filter(); it runs a callback on each element of the array where you can check if there's a match with your password. If the callback returns false, the element is removed from the array. After that, if you have any elements left you know there was a match.
function checkPassword($pwd) {
$pwd = strtolower($pwd);
$common = file("commonpasswords.txt", FILE_IGNORE_NEW_LINES);
$results = array_filter($common, function($i) use ($pwd) {return $i == $pwd;});
return count($results) === 0;
}
But really, there are dozens of libraries out there to check password strength. Use one of them.
Or, as pointed out in the comment, even simpler array_search:
function checkPassword($pwd) {
$pwd = strtolower($pwd);
$common = file("commonpasswords.txt", FILE_IGNORE_NEW_LINES);
return array_search($pwd, $common) === false;
}
Using PHP 5.6, and will be moving to 7.0 within next 12-18 months on this particular application.
So we have a quite large global config file -- which holds by now close to 100 variables (and each update gets more). As you would expect, this config file is called by every script page in the app, but not all config values are used in all cases -- but for convenience sake, we house them all in the same file.
But I was thinking that perhaps housing the values into functions would be more efficient, but as I am not an architect of the PHP language (or any language), I don't know if using functions is more efficient, less efficient, or pretty much no difference.
So here is an example scenario. In our config file, we have something like this:
$g['user']['enable_username_change'] = true;
$g['user']['enable_image_change'] = true;
$g['user']['display'] = "[LASTNAME], [FIRSTNAME]";
$g['user']['sort_by'] = "[LASTNAME]";
$g['user']['default_locale'] = "english";
$g['user']['profile_page'] = file_get_contents('profile_template.html');
These values are available to all scripts, but only a handful need them. Obviously we access them by just doing something like this:
if ( $g['user']['enable_username_change'] == true ) {
// the code to enable it ...
}
So I was thinking of changing the way this works (if it would create more efficiency) by doing something like this:
function user__getGlobalConfig( $in_param_name ) {
// DEFINE THE VALUES
$g['user']['enable_username_change'] = true;
$g['user']['enable_image_change'] = true;
$g['user']['display'] = "[LASTNAME], [FIRSTNAME]";
$g['user']['sort_by'] = "[LASTNAME]";
$g['user']['default_locale'] = "english";
$g['user']['profile_page'] = file_get_contents('profile_template.html');
if ( isset( $g['user'][$in_param_name] == true ) {
return $g['user'][$in_param_name];
} else {
return false;
}
}
Then we would access it like this:
if ( user__getGlobalConfig('enable_username_change') == true ) {
// the code to enable it ...
}
So it would seem that the file_get_contents() type values would only get read in when function is called, which I believe would be more efficient, but I may be wrong. The other true/false or simple text based values dont seem that they would be a big efficiency gain, but I pose that here -- any science or fact-based reasoning as to why one way would be more efficient than the other?
Thanks.
If you use the function approach, you should code it so it doesn't recreate the array every time, by using a static variable to cache the settings. In particular, you don't want it to call file_get_contents() every time you look up a setting.
function user__getGlobalConfig( $in_param_name ) {
static $g;
if (!isset($g)) {
$g = array();
// DEFINE THE VALUES
$g['user']['enable_username_change'] = true;
$g['user']['enable_image_change'] = true;
$g['user']['display'] = "[LASTNAME], [FIRSTNAME]";
$g['user']['sort_by'] = "[LASTNAME]";
$g['user']['default_locale'] = "english";
$g['user']['profile_page'] = file_get_contents('profile_template.html');
}
if ( isset( $g['user'][$in_param_name] ) ){
return $g['user'][$in_param_name];
} else {
return false;
}
}
I'm trying to create a very simple URL routing, and my thought process was this:
First check all static URLs
Then check database URLs
Then return 404 if neither exists
The static URLs are easy to do of course, but I'm trying to figure out the best way to do dynamic ones. I would prefer not to have to set a static prefix, despite knowing that it would make this a lot easier to code.
This is what I currently have:
$requestURL = $_SERVER['REQUEST_URI'];
if ($requestURL == '/') {
// do stuff for the homepage
}
elseif ($requestURL == '/register') {
// do stuff for registration
}
// should match just "/some-unique-url-here"
elseif (preg_match("/([\/A-Za-z0-9\-]+)/",$requestURL)) {
// query database for that url variable
}
// should match "/some-unique-url/and-another-unique-url"
elseif (preg_match("(^\/[A-Za-z0-9\-]+\/[A-Za-z0-9\-]+)/",$requestURL)) {
// query database for first and second variable
}
else {
// 404 stuff
}
My problem is that if I have "/register" URI, it will match the second elseif statement as well as the regex statement. But I want to avoid having to specifically exclude each static URL from regex statement, such as this:
// should match just "/some-unique-url-here"
elseif ((preg_match("/([\/A-Za-z0-9\-]+)/",$requestURL)) &&
($requestURL !== '/register') &&
($requestURL !== '/')) {
// query database for that url variable
}
What's the easiest way to solve this problem? I'll probably have like 15-20 static URLs, so specifically excluding all of them would be very clunky.
Your problem does not exist. If the first elseif ($requestURL == '/register') matches, all subsequent elseifs on the same level won't get evaluated.
You're already doing it right, just make sure you do the string comparisons (==) first.
On another note, don't reinvent the wheel.
https://github.com/bramus/router
http://toroweb.org/
http://zaphpa.org/
Basically the problem I am having is I need to write this function that can take a URL like www.stackoverflow.com and just return the "com". But I need to be able to return the same value even if the URL has a period at the end like "www.stackoverflow.com."
This is what I have so far. The if statement is my attempt to return the point in the array before the period but I dont think I am using the if statement correctly. Otherwise the rest of the code does exactly what is supposed to do.
<?php
function getTLD($domain)
{
$domainArray = explode("." , $domain);
$topDomain = end($domainArray);
if ($topDomain == " ")
$changedDomain = prev(end($domainArray));
return $changedDomain;
return $topDomain;
}
?>
Don't use a regex for simple cases like that, it is cpu costly and unreadable. Just remove the final dot if it exists:
function getTLD($domain) {
$domain = rtrim($domain, '.');
return end(explode('.', $domain));
}
The end function is returning an empty string "" (without any spaces). You are comparing $topDomain to single space character so the if is not evaluating to true.
Also prev function requires array input and end($domainArray) is returning a string, so, $changedDomain = prev(end($domainArray)) should throw an E_WARNING.
Since end updates the internal pointer of the array $domainArray, which is already updated when you called $topDomain = end($domainArray), you do not need to call end on $domainArray inside the if block.
Try:
if ($topDomain == "") {
$changedDomain = prev($domainArray);
return $changedDomain; // Will output com
}
Here is the phpfiddle for it.
Use regular expressions for something like this. Try this:
function getTLD($domain) {
return preg_replace("/.*\.([a-z]+)\.?$/i", "$1", $domain );
}
A live example: http://codepad.org/km0vCkLz
Read more about regular expressions and about how to use them: http://www.regular-expressions.info/
I need to filter some email address based on the domain name :
Basically if the domain name is yahoo-inc.com, facebook.com, baboo.com .. (and a few others) the function should do something and if the domain is different it should do something else .
The only way I know to do this is to use a pattern/regex with preg_match_all and create cases/conditions for each balcklisted domain (e.g if domain = yahoo-inc) do this elseif (domain == facebook.com ) do this ... etc but I need to know if there is a more simple/concis way to include all the domains that I want to filter in a single variable/array and then apply only 2 conditions (e.g if email is in black list {do something } else {do something else}
Extract the domain portion (i.e. everything after the last '#'), down case it, and then use in_array to check whether it's in your blacklist:
$blacklist = array('yahoo-inc.com', 'facebook.com', ...);
if (in_array($domain, $blacklist)) {
// bad domain
} else {
// good domain
}
Adding on to #Alnitak here is the full code to do what you need
$domain = explode("#", $emailAddress);
$domain = $domain[(count($domain)-1)];
$blacklist = array('yahoo-inc.com', 'facebook.com', ...);
if (in_array($domain, $blacklist)) {
// bad domain
} else {
// good domain
}
Well here's a very simple way to do this, a VALID email address should only ever contain a single # symbol, so aslong as it validation you can just explode the string by # and collect the second segment.
Example:
if (filter_var($user_email, FILTER_VALIDATE_EMAIL))
{
//Valid Email:
$parts = explode("#",$user_email);
/*
* You may want to use in_array if you already have a compiled array
* The switch statement is mainly used to show visually the check.
*/
switch(strtolower($parts[1]))
{
case 'facebook.com':
case 'gmail.com':
case 'googlemail.com':
//Do Something
break;
default:
//Do something else
break;
}
}