hi i have many session values in my project and i use the syntext for session is
$_SESSION['username'] = $somevalue;
this things is implemented in may pages around 2000 pages. now i want to replace this thing to
$_SESSION['username'] = (string)$somevalue
in all the pages simultaneously. how can i do this in dreamwaver. please help me. there are many different session values used in my pages.
Is there any way to convert all session values into string simultaneosly.
i mean any regex method like $_SESSION[.] = (string) like this. or any other method. please tell me .
Thanks.
It depends of what version of PHP you have. For >=5.3, use Peter's version, for <5.3, use
function stringify($item)
{
return (string)$item;
}
$_SESSION = array_map('stringify', $_SESSION);
array_map function is probably what you are looking for:
$_SESSION = array_map(function($item) { return (string)$item; }, $_SESSION);
PHP 5.3 is required for anonymous function, in earlier versions you have to pass function name as first argument.
Just in case you want it in your 2000 code files instead of converting the values at runtime in your script: Don't know if Dreamweaver supports regex search and replace and what the backreference chars are. But try replacing this
\$_SESSION\['[^']+'\]\s*=\s*
with this:
$0(string)
The $0 is the backreference to the matched pattern. If that doesn't work, try \0 or \\0 instead.
Related
[EDIT] I am placing the comment I entered near the bottom of this post to, hopefully avoid further down votes.
This was a pretty basic question stemming from my misunderstanding of what exactly $_REQUEST is. My understanding was that it was an index that referenced $_POST and $_GET (and $_COOKIE). However, I found that $_REQUEST is, itself, an array, so I simply changed the variables in $_REQUEST. Not an optimal solution, but a solution, nonetheless. It has the added advantage that the $_GET variables, with the apostrophes still there, are available. Perhaps not the best practice, but please note before you down vote that I have very little control over this data - coming in from one API and going out to another.
I have an API currently in use. We have a problem with some customers sending apostrophes in the URL. My question is how best to strip the apostrophes within the URL array. Perhaps using array_walk or something similar?
So that $_REQUEST[Customer] == "O'Henry's"
Becomes $_REQUEST[Customer] == "OHenrys"
EDIT: Judging from some of the answers here, I believe I need to explain a little better. This is an API that is already written and is the preliminary interface for another AS400 API. I have nothing to do with building the URL. I am receiving it. All I am concerned about is removing the apostrophes, without changing any other code. So the best way is to go through the array. In the body of the code, the variable references are all using $_REQUEST[]. I COULD go in and change those to $_GET[] if absolutely necessary but would rather avoid that.
This Works
foreach($_REQUEST as $idx => $val)
{
$_REQUEST[$idx] = str_replace("'" , '' , $val);
}
However, I am a little leery of using $_REQUEST in that manner. Does anyone see a problem with that. (Replacing $_REQUEST with $_GET does not work)
For some use cases, it might make sense to store a "clean" or "pretty" version of the name. In that case, you may want to standardize to a case and have a whitelist of characters rather than a blacklist consisting of just single quotes. Use a regex to enforce this, perhaps similar to this one:
preg_replace("/[^[:alnum:][:space:]]/u", '', $string);
If you do that, consider if it is necessary to differentiate between different customers named O'Henrys, O'Henry's, OHenrys, O'henry's, and so on. Make sure your constraints are enforced by the app and the database.
The array_walk_recursive function is a reasonable way to hit every item in an array:
function sanitize(&$item, $key)
{
if (is_string($item)) {
// apply whitelist constraints
}
}
array_walk_recursive($array, 'sanitize');
It's hard to tell without more context, but it seems possible you may be asking the wrong question / solving the wrong problem.
Remember that you can almost always escape "special" characters and render them a non-issue.
In an HTML context where a single quote might cause problems (such as an attribute value denoted by single quotes), escape for HTML using htmlspecialchars or a library-specific alternative:
<?php
// some stuff
$name = "O'Henry's";
?><a data-customer='<?=htmlspecialchars($name, ENT_QUOTES|ENT_HTML5);?>'>whatever</a><?php
// continue
For JavaScript, encode using json_encode:
<?php
// some stuff
$name = "O'Henry's";
?><script>
var a = <?=json_encode($name);?>
alert(a); // O'Henry's
</script>
For SQL, use PDO and a prepared statement:
$dbh = new PDO('mysql:host=localhost;dbname=whatever', $user, $pass);
$name = "O'Henry's";
$stmt = $dbh->prepare("INSERT INTO REGISTRY (name) VALUES (:name)");
$stmt->bindParam(':name', $name);
$stmt->execute();
For use in a URL query string, use urlencode:
<?php
// some stuff
$name = "O'Henry's";
?>whatever<?php
// continue
For use in a URL query path use rawurlencode:
<?php
// some stuff
$name = "O'Henry's";
?>whatever<?php
// continue
Libraries and frameworks will provide additional ways to escape things in those and other contexts.
If you want them removing altogether as an illegal character:
<?php foreach($myArray as $idx => $val){
$myArray[$idx] = str_replace("'" , '' , $val);
}
?>
However this shouldn't be your solution to SQL Inserts etc.. Better off using mysqli::real_escape_string OR prepared statements
This was a pretty basic question stemming from my misunderstanding of what exactly $_REQUEST is. My understanding was that it was an index that referenced $_POST and $_GET (and $_COOKIE). However, I found that $_REQUEST is, itself, an array, so I simply changed the variables in $_REQUEST. Not an optimal solution, but a solution, nonetheless. It has the added advantage that the $_GET variables, with the apostrophes still there, are available. Not the best practice, though.
EDIT:
Reading the edits you made on your question, the best solution for you is str_replace(). But no need to loop through your array, the 3rd parameter can be an array !
This will strip apostrophes of every item in $foo:
$foo = [
"O'Henry's",
"D'Angleterre"
];
$foo = str_replace("'", "", $foo);
If you really need to remove the apostrophes use str_replace():
$foo = "O'Henry's";
$foo = str_replace("'", "", $foo);
// OUTPUT: OHenrys
If you can keep them, you better encode them. urlencode() may be a way to do:
$foo = urlencode($foo);
// OUTPUT: O%27Henry%27s
If you build this URL from an array you could use http_build_query():
$foo = [
'Customer' => "O'Henry's"
];
$foo = http_build_query($foo);
// OUTPUT: Customer=O%27Henry%27s
I am having to do:
$sourceElement['description'] = htmlspecialchars_decode($sourceElement['description']);
I want to avoid that redundant mention of the variable name. I tried:
htmlspecialchars_decode(&$sourceElement['description']);
and
call_user_func('htmlspecialchars_decode', &$sourceElement['description']);
That did not work. Is this possible in PHP? Call a function on a variable?
You could create your own wrapper function that takes the variable by reference:
function html_dec(&$str) {$str = htmlspecialchars_decode($str);}
Then call:
html_dec($sourceElement['description']);
The correct solution would be to include that "redundant" variable mention. It's far more readable, and far less confusing that way.
$sourceElement['description'] = htmlspecialchars_decode($sourceElement['description']);
Your way of thinking is good though, you're thinking how to shorten your code, like a true lazy programmer =)
It depends on function. htmlspecialchars_decode() returns the result, it doesn't modify the original variable. And you can do nothing about it.
Most functions in PHP are immutable in mature, i.e. they don't modify the arguments you pass into them. This has a few advantages, one of them being able to use their return value in expressions without side effects.
Here's a generic wrapper you could use to mimic mutable behaviour for any function that takes a single argument:
function applyFn(&$s, $fn)
{
return $s = $fn($s);
}
applyFn($sourceElement['description'], 'htmlspecialchars_decode');
applyFn($sourceElement['description'], 'trim'); // trim string
Mileage may vary :)
Just a simple question. I have a contact form stored in a function because it's just easier to call it on the pages I want it to have.
Now to extend usability, I want to search for {contactform} using str_replace.
Example:
function contactform(){
// bunch of inputs
}
$wysiwyg = str_replace('{contactform}', contactform(), $wysiwyg);
So basically, if {contactform} is found. Replace it with the output of contactform.
Now I know that I can run the function before the replace and store its output in a variable, and then replace it with that same variable. But I'm interested to know if there is a better method than the one I have in mind.
Thanks
To answer your question, you could use PCRE and preg_replace_callback and then either modify your contactform() function or create a wrapper that accepts the matches.
I think your idea of running the function once and storing it in a variable makes more sense though.
Your method is fine, I would set it as a $var if you are planning to use the contents of contactform() more than once.
It might pay to use http://php.net/strpos to check if {contact_form} exists before running the str_replace function.
You could try both ways, and if your server support it, benchmark:
<?php echo 'Memory Usage: '. (!function_exists('memory_get_usage') ? '0' : round(memory_get_usage()/1024/1024, 2)) .'MB'; ?>
you may want to have a look at php's call_user_func() more information here http://php.net/call_user_func
$wysiwyg = 'Some string and {contactform}';
$find = '{contactform}';
strpos($wysiwyg, $find) ? call_user_func($find) : '';
Yes, there is: Write one yourself. (Unless there already is one, which is always hard to be sure in PHP; see my next point.)
Ah, there it is: preg_replace_callback(). Of course, it's one of the three regex libraries and as such, does not do simple string manipulation.
Anyway, my point is: Do not follow PHP's [non-]design guidelines. Write your own multibyte-safe string substitution function with a callback, and do not use call_user_func().
I have part of a query string that I want to make a replacement in. I want to use preg_replace but am kind of hung up on the regex.
Can someone please help? What I need replaced are the GET vars.
Here is the string:
bikeType=G&nikeNumber=4351
PHP has a convenient function to parse query strings: parse_str(). You might want to take a look at that or provide more details as your question isn't exactly clear.
You can use parse_str as was mentioned already.
In addition, if you want to put them back into a query string you can use http_build_query
Example:
parse_str('bikeType=G&nikeNumber=4351', $params);
$params['bikeType'] = 'F';
$params['nikeNumber'] = '1234';
echo http_build_query($params, '', '&');
Output
bikeType=F&nikeNumber=1234
Please note that you should not use parse_str without the second argument (or at least not with some consideration). When you leave it out, PHP will create variables from the query params in the current scope. That can lead to security issues. Malicious users could use it to overwrite other variables, e.g.
// somewhere in your code you assigned the current user's role
$role = $_SESSION['currentUser']['role'];
// later in the same scope you do
parse_str('bikeType=G&nikeNumber=4351&role=admin');
// somewhere later you check if the user is an admin
if($role === "admin") { /* trouble */ }
Another note: using the third param for http_build_query is recommended, because the proper encoding for an ampersand is &. Some validators will complain if you put just the & in there.
I am very curious on how to do this. I want a PHP script to look at the string after the URL link and echo the value.
For example, if I entered:
"http://mywebsite.com/script.php?=43892"
the script will echo the value 43892. I have seen this in most websites, and I think it will be a very useful to have in my application.
Thanks,
Kevin
You mean, something like
http://mywebsite.com/script.php?MyVariable=43892
? Variables provided at the end of the URL like that are available in the $_GET array. So if you visited the above URL and there was a line on the page that said
echo $_GET['MyVariable'];
then 43892 would be echoed.
Do be aware that you shouldn't trust user input like this - treat any user input as potentially malicious, and sanitise it.
echo filter_var($_SERVER['QUERY_STRING'], FILTER_SANITIZE_NUMBER_INT);
The sanitation is because in your example the query string is =43892, not 43892. The filter used "remove[s] all characters except digits, plus and minus sign".
Don't you mean http://mywebsite.com/script.php?43892 ?
You can either use apache URL rewriting or try to extract all entries from $_GET and look a the one which looks like a number or simply doesn't have a value.
Try manually parsing the URL like this
$geturl = $_SERVER['REQUEST_URI'];
$spliturl = explode("?",$geturl);
$get
= explode("=",$spliturl[0]);
echo $get[1];
:)
Before I really answer your question, I just have to say that most sites - at least that I have seen - actually use ?43892, with the =. This is also much easier than using it with = in my opinion.
So, now to the actual answer. You can simply extra the query string usingĀ $_SERVER['QUERY_STRING'].
An example:
User requests index.php?12345:
<?php
echo $_SERVER['QUERY_STRING'];
?>
Output:
12345
Note that you can also use something like
<?php
if(substr($_SERVER['QUERY_STRING'], 0, 1) == '=') {
$query_string = substr($_SERVER['QUERY_STRING'], 1);
}else{
$query_string = $_SERVER['QUERY_STRING'];
}
echo $query_string;
to support ?=12345 as well as 12345, with the same result. Note also that ?=12345 would not be available as $_GET[''] either.
The way you usualy use query parameters is by assigning them like http://mywebsite.com/script.php?var1=123&var2=234
Then you will be able to access them by $_GET['var1'] and $_GET['var2'] in your PHP script
I'de recommand parse-url for this. The documentation contains all you (I think) need.