Coldfusion to PHP - php

I'm converting an entire site from Coldfusion to PHP. So, expect many question like this. How to write this in PHP:
<cfif cgi.script_name contains "newsletter">

if(stripos($_SERVER['PHP_SELF'],"newsletter") > 0){
should do the exact same. Stripos rather than strpos because coldfusion is case insensitive and a simple compare like ceejayoz would be invalid as that would of course only match a specific file (which however might be desirable in a lot of situations, but isn't the same as your cfml).

The closest equivalent will be something like:
if($_SERVER['PHP_SELF'] == '/newsletter.php') {
// do something
}
There's not always going to be a one-to-one function equivalency between CF and PHP, and more context than you've provided is often going to be important as a result.

The second value added to stripos looks like this:
if(stripos($_SERVER['PHP_SELF'], substr('newsletter', 0))) {
// do something
}

Related

Is there a built-in PHP function to check if a given string is a reserved keyword?

I'm looking at this: https://www.php.net/manual/en/reserved.php
I've made numerous search queries for things like: "php determine if string is reserved keyword".
I find nothing, and I'm starting to seriously sweat. Please don't tell me I'm going to have to code a complicated script to regularly scrape the PHP manual for all these various kinds of reserved keywords and build my own database!
Please let there be a nice, simple function to simply check:
var_dump(is_reserved_php_keyword('if'));
And it gives a true/false.
I went a different way to Andrew and instead went for having PHP figure it out rather than hard coding the list.
function isPhpKeyword($testString) {
// First check it's actually a word and not an expression/number
if (!preg_match('/^[a-z]+$/i', $testString)) {
return false;
}
$tokenised = token_get_all('<?php ' . $testString . '; ?>');
// tokenised[0] = opening PHP tag, tokenised[1] = our test string
return reset($tokenised[1]) !== T_STRING;
}
https://3v4l.org/WA6dr
This has a few advantages:
It doesn't need the list to be maintained as PHP's own parser says what's valid or not.
It's a lot simpler to understand.
Unfortunately, I'm not aware of any built-in function for what you describe. But based on the RegEx pattern you can find among the contributed notes on PHP.net, you can test it like this:
$reserved_pattern = "/\b((a(bstract|nd|rray|s))|(c(a(llable|se|tch)|l(ass|one)|on(st|tinue)))|(d(e(clare|fault)|ie|o))|(e(cho|lse(if)?|mpty|nd(declare|for(each)|if|switch|while)|val|x(it|tends)))|(f(inal|or(each)?|unction))|(g(lobal|oto))|(i(f|mplements|n(clude(_once)?|st(anceof|eadof)|terface)|sset))|(n(amespace|ew))|(p(r(i(nt|vate)|otected)|ublic))|(re(quire(_once)?|turn))|(s(tatic|witch))|(t(hrow|r(ait|y)))|(u(nset|se))|(__halt_compiler|break|list|(x)?or|var|while))\b/";
if(!preg_match($reserved_pattern, $myString)) {
// It is not reserved!
};
It may not be the most elegant-looking piece of PHP code out there, but it gets the job done.
UPDATE: See online demo of function here: https://3v4l.org/CdIjt

Why use an extra set of parenthesis when using PHP boolean test in an IF()?

I'm sorry the title of this question is odd. I couldn't find a good way to word it!
The idea is simple, sometimes you see PHP tests this way:
if (!a_function("something")) { }
Here you can think of it as "if not true". I sometimes see the exact same thing but with extra parenz:
if (!(a_function("something"))) { }
Why does it require the extra parenz after the bang? Don't they both essentially mean if (!true)?
For extra bonus, what are the reasons for the two styles (does this have a name?) and maybe give examples of how they would give alternate results if not used correctly.
update:
Here is an example in a PHP script I'm using, the author is testing environment variables and seems to use the styles interchangeably:
if (!(extension_loaded("iconv"))) { ... }
if (!(extension_loaded("xml"))) { ... }
if (!function_exists("json_encode")) { ... }
if (!ini_get("short_open_tag")) { ... }
I know you can't answer for the programmer here, but why would they be alternating the use of extra parenz when these small functions are right next to each other?
I happen to know that, for example, the return value of ini_get is just the number 1, and the return value of the extension_loaded functions may also just be the number 1, so it seems like there would be no difference. I'm not 100% sure there isn't some other trick to this than simple preference or order of operation.
update 2:
I understand parenz can be used for either clarity, or order of operations, but I'm not convinced it is only personal preference beyond that.
In my example above, everything depends on what is returned by the functions that are being tested.
It's my understanding that by wrapping a statement in parenz, PHP will force it into a bool. But when it's not in parenz, could there be a return value that breaks the code without using the parenz around it to force a bool?
If people say, in my example code above, that there is nothing but personal preference going on, then I'll just have to accept that, but I have my doubts.
the parenthesizes are used in case if there are more than 1 logical operator with different precedence, to indicate that "!" operator must be applied after all other operators have been processed. For example:
if(!($var1 < $var2))
First will be checked if $var1 is less than $var2, and after that will be checked if the result is false.
If use that:
if(!$var1 < $var2)
then firstly will be checked if $var1 is false and the result will be compared to $var2, that simply do not make sense.
It's not required. It's a matter of personal preference. Sometimes you like to have extra parens to be EXTRA certain of how the expression will be evaluated.
if(a or b and c)
is confusing.
if ((a or b) and c)
is much more clear.
if(a or (b and c))
is much more clear.
They both work, but some people might have different opinions on which one is more readable.
Parenthesis are not required in the given case, but they can be if, for example, you also assign a variable at the same time :
if (($myVar = myFunc()) !== false) {
// Doing something with $myVar, ONLY if $var is not false
}
While, in the following case, it will change the logic
if ($myVar = myFunc() !== false) {
// Here $myVar = true or false instead of the wanted value
}
if( !(should_return_trueA() && should_return_trueB())) {
// at least one have returned false
}
esentially is the same as:
if( !should_return_trueA() || !should_return_trueB() ) {
// at least one have returned false
}
It's, in my case, a practice to avoid mistaken/ommited exclamation marks. Useful, when building more complex conditions and looking for all-false or all-true result.

PHP or JQuery function for finding a string containing another string

So I'm busy building a site and trying to test out a sort of filter for certain words but trying to determine which is the best function to use and through what language. I've done a bit of research and in PHP I can use the strpos() function so for example:-
if (strpos($checkstring, 'geordie') !== false) {
$checkstring = 'invalid name';
}
I'm unsure as to whether there is a decent JQuery function that could be used to achieve the same thing. Basically I want to be able to block my friends from using my name or nickname so it would include any and all variations of 'geordie' including lowercase and uppercase as well as getting past it using 'GeoRdie' or something to that affect but also want to stop variations which would be my full nickname 'geordie dave' or 'geordie ****' or even 'geordie dave is a ****'.
I realise that this is probably a bit of a complicated one but there must be a way using perhaps an array of names?
Any help on a function to use would be great and if anyone could possibly give me an example of code that could be used would also be beneficial.
You should probably do it in javascript and in php (client side and server side). The javascript eqivalent of strpos is indexOf. If you only check with javscript, someone could forge a post packet and it would still be accepted by the server. If you are only going to check in one place, make it server side, but for user-friendly-ness, both is preferred.
I think that you should also use PHP strtolower function on $checkstring variable.
In JavaScript, you can use String#indexOf(String) to match exact strings, or RegExp#test(String) for more complicated matching.
if (str.indexOf("geordie") !== -1) {
// `str` contains "geordie" *exactly* (doesn't catch "Geordie" or similar)
}
if (/geordie/i.test(str)) {
// `str` contains "geordie", case-insensitive
}
And I'll second what Alfie said: You can't just do this on the client, because client requests can be spoofed. Client-side validation is purely for making a nice user experience; server-side validation is always required.

PHP: Condition Format - (6 == $var) or ($var == 6)?

I was browsing these PHP Coding Guidelines (a bit outdated but very interesting), and found this:
Condition Format
Always put the constant on the left hand side of an
equality/inequality comparison. For example: if ( 6 == $errorNum ) ...
One reason is that if you leave out one of the = signs, the parser
will find the error for you. A second reason is that it puts the value
you are looking for right up front where you can find it instead of
buried at the end of your expression. It takes a little time to get
used to this format, but then it really gets useful.
I have been using ($var == 6) for years now and the idea of putting them the other way around is horrifying. But as mentioned, this takes a bit time to get used to and is supposed to have clear benefits. We are just writing up standard at our company so if we want to change this, this is the moment to do that. But I'd like to hear if other have experience with this particular format. Any opinions?
EDIT
I am interested in people's experience with making this switch. To me, and most likely to others, this looks like a big change that you need to get used to. But it looks interesting. So the question to those who have switched: can you recommend this change?
6 == $var has a real advantage that $var == 6 does not. There is nothing horrifying about it at all, it just looks different. You should get used to it and use it. In fact, I haven't gotten used to it yet and I forget about it frequently. You really have to think about it and use it since the opposite is so common.
The advantage, in case you didn't know, is to prevent simple syntactical mistakes, thus:
if ($var = 6) {} //weird semantic error
if (6 = $var) {} //parse error

Clarity of using if(count())

In this code fragment:
$results = $this->getAdapter()->fetchAll($query);
if(count($results)) {
// …
}
…do you consider the if(count()) part to be be a well understood idiom, or confusing code. i.e. should it be
if(count($results) > 0)
???
Using a boolean expression with 'if' requires less understanding of a language than using implicit conversions, so I would always prefer the second option (adding "> 0") - at least if this code is meant to be read by others, too. You never know who will maintain your code. The keyword is "clarity" here.
But I must admit I have written many times code with if's using an int expression myself, too, because I like its elegance.
They are doing exactly the same job in this context, and are both easily readable.
I'll just add (just in case) that if you're performing this query only to if(count()), then you should be issuing a SELECT COUNT(*) instead!
The count and the extraneous > comparison are pointless. If you receive an actualy array, then the test should just be:
if ($results) {
That's what scripting languages are for. Abstracting low level details away.
You would only need the count if your fetchAll function returns an ArrayObject or similar. Should your function sometimes return a false for example, then your if (count( is going to fail (because count(false)==1 in PHP).
erm...not realy sure what the purpose of this question is - but the semantics should be self-evident to anyone whom understands PHP
My opinion is that the > 0 check is redundant and unnecessary.
I know other developers who insist that it should be there for clarity, but frankly I can't why -- anyone who can read PHP should be able to discern that they are identical.

Categories