PHP Function - Unknown Failure - php

I'm fairly new to coding and just recently started working on integrating functions into my PHP. I am trying to encode and echo an IP address to Google Analytics's. This is what my custom modifier looks like:
pagetracker._setCustomVar(1, "IP", "<?php include function.php; echo remove_numbers_advanced($_SERVER['REMOTE_ADDR']); ?>", 2);
The function file looks like this:
<?
function remove_numbers_advanced($string)
{
$numbers = array();
for($counter =0; $counter <= 10; $counter++) {
$numbers[$counter] = $counter;
$replacements = array("A","7","B","6","C","4","D","3","E","F");
$string = str_replace($numbers, $replacements, $string);
return $string;
}';
echo remove_numbers_advanced($string);
?>
When I isolated the PHP section of my custom variable in an attempt to test it the page throws a 500 error, suggesting to me that there is something wrong with how I have my script set up.
Please bear in mind I am rather new to this so simple terms and examples would help a ton!

There are few errors in your function. The correct function is:
function remove_numbers_advanced($string)
{
$numbers = array();
for($counter =0; $counter <= 10; $counter++)
$numbers[$counter] = $counter;
$replacements = array("A","7","B","6","C","4","D","3","E","F");
$string = str_replace($numbers, $replacements, $string);
return $string;
}
1- You added open curly braces next to for loop but did not close it
2- Also there is " '; " at the closing braces of function. It shouldn't be there.

include function must have a string parameter so put '' around file name
pagetracker._setCustomVar(1, "IP", "<?php include 'function.php'; echo remove_numbers_advanced($_SERVER['REMOTE_ADDR']); ?>", 2);

Related

Encoding a string from php to javascript returns errors

I'm trying to insert a PHP EOT string into a js code and I need to encode it since it has some \n in it. I can't do it with a simple jsonencode because it returns the code with "'s and I don't need them there.
So i tried those two approaches which both return an error:
<?php
$string = $v['survey'];
function escapeJavaScriptText($string)
{
return str_replace("\n", '\n', str_replace('"', '\"', addcslashes(str_replace("\r", '', (string)$string), "\0..\37'\\")));
}
?>
<?php echo escapeJavaScriptText(); ?>
I've also tried:
<?php
$string = $v['survey'];
function javascript_escape($string) {
$new_str = '';
$str_len = strlen($string);
for($i = 0; $i < $str_len; $i++) {
$new_str .= '\\x' . sprintf('%02x', ord(substr($string, $i, 1)));
}
return $new_str;
}
?>
<?php echo javascript_escape(); ?>
Both return:
Missing argument 1 for escapeJavaScriptText() and Undefined variable: string in
But <?php echo $string; ?> returns the code I need (just without the encoding).
What am I missing?
<?php
$string = $v['survey'];
function javascript_escape($string) {
$new_str = '';
$str_len = strlen($string);
for($i = 0; $i < $str_len; $i++) {
$new_str .= '\\x' . sprintf('%02x', ord(substr($string, $i, 1)));
}
return $new_str;
}
?>
<?php echo javascript_escape($string); ?>
It's because of different variable scopes within your function and global code. In PHP, by default, functions don't have access to global variables.
In your case, variable $string, you're trying to use by function javascript_escape, is a global variable. So, you have a few ways to avoid Undefined Variable exception.
1. Use "global" keyword to have acces to global variables inside the function.
After function definition, you just need to specify global variables this way (and remove $string from arguments list):
function javascript_escape() {
global $string;
$new_str = '';
$str_len = strlen($string);
for($i = 0; $i < $str_len; $i++) {
$new_str .= '\\x' . sprintf('%02x', ord(substr($string, $i, 1)));
}
return $new_str;
}
or
function escapeJavaScriptText()
{
global $string;
return str_replace("\n", '\n', str_replace('"', '\"', addcslashes(str_replace("\r", '', (string)$string), "\0..\37'\\")));
}
2. Pass $string as an argument of function call.
If you have a reasons not to use global variables at all, you're able to pass unescaped string each time the function has to be called.
<?php echo javascript_escape($string); ?>
3. Use pre-escaped string.
If you have to use $string encoded by your function multiple times, it'd be a good practice to escape the variable at the beginning of your code and use it without calling escape function every time you need to use this variable:
$escaped_string = javascript_escape($string);
...
<?php echo $escaped_string; ?>
Also, I recommend you to read the official documentation about variable scopes: http://php.net/manual/en/language.variables.scope.php

php outcome of sum multiply with html element

Excuse me if the title isn't completely clear.
but i've got a value that is the outcome of a sum. Called $addCols and a variable that is just html. What i want is to repeat the html with the addCols variable.
$addCols = 4 //for example
$html .= '<div>test</div>';
And i wish to get the following result:
// Result
test
test
test
test
What i've tried:
$result = $addCols * $html;
echo $result;
There is a built-in function for this:
echo str_repeat("<div>test</div>", $addCols);
Documentation
Built-in functions will always be better/faster than manually-coded solutions.
create a for loop, this will post the html code as many times as your variable states giving the requested output.
for($x = 0; $x < $addCols; $x++)
{
echo '<div>text</div>';
}
Just use str_repeat() function in php or run a loop. Use the code below
With str_repeat
$addCols = 4 ;//for example
$html = '<div>test</div>';
echo str_repeat($html, $addCols);
With loop
$addCols = 4; //for example
$html = '<div>test</div>';
for($x = 0; $x < $addCols; $x++)
{
echo $html;
}
With while loop
$html = '<div>test</div>';
$addCols = 4 ;//for example
$x=0;
while($x < $addCols)
{
echo $html;
$x++;
}
Hope this helps you

PHP dynamic string update with reference

Is there any way to do this:
$myVar = 2;
$str = "I'm number:".$myVar;
$myVar = 3;
echo $str;
output would be: "I'm number: 3";
I'd like to have a string where part of it would be like a pointer and its value would be set by the last modification to the referenced variable.
For instance even if I do this:
$myStr = "hi";
$myStrReference = &$myStr;
$dynamicStr = "bye ".$myStrReference;
$myStr = "bye";
echo $dynamicStr;
This will output "bye hi" but I'd like it to be "bye bye" due to the last change. I think the issue is when concatenating a pointer to a string the the pointer's value is the one used. As such, It's not possible to output the string using the value set after the concatenation.
Any ideas?
Update: the $dynamicStr will be appended to a $biggerString and at the end the $finalResult ($biggerString+$dynamicStr) will be echo to the user. Thus, my only option would be doing some kind of echo eval($finalResult) where $finalResult would have an echo($dynamicStr) inside and $dynamicStr='$myStr' (as suggested by Lawson), right?
Update:
$myVar = 2;
$str = function() use (&$myVar) {
return "I'm number $myVar";
};
$finalStr = "hi ".$str();
$myVar = 3;
echo $finalStr;
I'd like for this to ouput: "hi I'm number 3" instead of "hi I'm number 2"...but it doesn't.
The problem here is that once a variable gets assigned a value (a string in your case), its value doesn't change until it's modified again.
You could use an anonymous function to accomplish something similar:
$myVar = 2;
$str = function() use (&$myVar) {
return "I'm number $myVar";
};
echo $str(); // I'm number 2
$myVar = 3;
echo $str(); // I'm number 3
When the function gets assigned to $str it keeps the variable $myVar accessible from within. Calling it at any point in time will use the most recent value of $myVar.
Update
Regarding your last question, if you want to expand the string even more, you can create yet another wrapper:
$myVar = 2;
$str = function() use (&$myVar) {
return "I'm number $myVar";
};
$finalStr = function($str) {
return "hi " . $str();
}
$myVar = 3;
echo $finalStr($str);
This is a little simpler than I had before. The single quotes tell PHP not to convert the $myVar into a value yet.
<?php
$myVar = 2;
$str = 'I\'m number: $myVar';
$myVar = 3;
echo eval("echo(\"$str\");");
?>

PHP create page as a string after PHP runs

I'm stuck on how to write the test.php page result (after php has run) to a string:
testFunctions.php:
<?php
function htmlify($html, $format){
if ($format == "print"){
$html = str_replace("<", "<", $html);
$html = str_replace(">", ">", $html);
$html = str_replace(" ", "&nbsp;", $html);
$html = nl2br($html);
return $html;
}
};
$input = <<<HTML
<div style="background color:#959595; width:400px;">
<br>
input <b>text</b>
<br>
</div>
HTML;
function content($input, $mode){
if ($mode =="display"){
return $input;
}
else if ($mode =="source"){
return htmlify($input, "print");
};
};
function pagePrint($page){
$a = array(
'file_get_contents' => array($page),
'htmlify' => array($page, "print")
);
foreach($a as $func=>$args){
$x = call_user_func_array($func, $args);
$page .= $x;
}
return $page;
};
$file = "test.php";
?>
test.php:
<?php include "testFunctions.php"; ?>
<br><hr>here is the rendered html:<hr>
<?php $a = content($input, "display"); echo $a; ?>
<br><hr>here is the source code:<hr>
<?php $a = content($input, "source"); echo $a; ?>
<br><hr>here is the source code of the entire page after the php has been executed:<hr>
<div style="margin-left:40px; background-color:#ebebeb;">
<?php $a = pagePrint($file); echo $a; ?>
</div>
I'd like to keep all the php in the testFunctions.php file, so I can place simple function calls into templates for html emails.
Thanks!
You can use output buffering to capture the output of an included file and assign it to variable:
function pagePrint($page, array $args){
extract($args, EXTR_SKIP);
ob_start();
include $page;
$html = ob_get_clean();
return $html;
}
pagePrint("test.php", array("myvar" => "some value");
And with test.php
<h1><?php echo $myvar; ?></h1>
Would output:
<h1>some value</h1>
This may not be exactly what you're looking for but it seems you want to build an engine of sorts for processing email templates into which you can put php functions? You might check out http://phpsavant.com/ which is a simple template engine that will let you put in php functions directly into a template file as well as basic variable assignment.
I'm not sure what printPage is supposed to be doing but I would re-write it like this just to make it more obvious because the array of function calls is a bit complicated and I think this is all that is really happening:
function pagePrint($page) {
$contents = file_get_contents($page);
return $page . htmlify($contents,'print');
};
and you might consider getting rid of htmlify() function and use either of the built-in functions htmlentities() or htmlspecialchars()
Seems like my original method may not have been the best way of going about it. Instead of posing a new question on the same topic, figured it was better to offer an alternate method and see if it leads to the solution I am after.
testFunctions.php:
$content1 = "WHOA!";
$content2 = "HEY!";
$file = "test.html";
$o = file_get_contents('test.html');
$o = ".$o.";
echo $o;
?>
text.php:
<hr>this should say "WHOA!":<hr>
$content1
<br><hr>this should say "HEY!":<hr>
$content2
I'm basically trying to get $o to return a string of the test.php file, but I want the php variables to be parsed. as if it was read like this:
$o = "
<html>$content1</html>
";
or
$o = <<<HTML
<html>$content1</html>
HTML;
Thanks!

PHP GET method doesn't work in Xampps

I'm a newbie in PHP and I'm confused about GET method.
Why the $text in the condition of the loop works with Appserv in Windows 7, but when I tried this code with Xampps on Mac it won't work I've to use for($i=0; $i<strlen($_GET['text']); $i++) instead.
At first, I understand that after I used isset($_GET['text']) so next time I just use only $text, but now I'm confused.
<? $color = array("#FFCCFF", "#FFCCCC", "#FFCC99", "#FF99FF", "#FF99CC",
"#FF9999", "#FF66FF", "#FF66CC", "#FF6699", "#FF6666");
if (isset($_GET['text'])) {
for($i=0; $i<strlen($text); $i++) {
$j = $i%10 ?>
<font color=<?= $color[$j]?>><? echo "$text[$i]"; ?></font>
}
} else {
echo "Empty String";
} ?>
The problem is solved by many of your help.
<?php $color = array("#FFCCFF", "#FFCCCC", "#FFCC99", "#FF99FF", "#FF99CC",
"#FF9999", "#FF66FF", "#FF66CC", "#FF6699", "#FF6666");
if( isset($_GET['text'])) {
$text = $_GET['text'];
for( $i=0; $i<strlen($text); $i++) {
$j = $i%10;
echo "<font color=$color[$j]>$text[$i]</font>";
}
} else
echo "Empty string";
?>
btw I'm trying to use HTML + PHP only because I want to practice with HTML before go in deep with CSS.
The actual answer to your question, if $text is working as an alias for $_GET['text'] is probably that your Windows server is configured with register_globals set to on, which would mean that anything passed over in your query string would be turned into the appropriate variable.
ie. ?awesome=true == $awesome = 'true'
This is bad. Disable register_globals at the offending side, and use $_GET['text'] to access your data.
Your code would look better a little something like this:
<?php
$color = array("#FFCCFF", "#FFCCCC", "#FFCC99", "#FF99FF", "#FF99CC",
"#FF9999", "#FF66FF", "#FF66CC", "#FF6699", "#FF6666");
if (isset($_GET['text'])) {
$text = $_GET['text'];
for($i=0; $i < strlen($text); $i++) {
$j = $i % 10; ?>
<span style="color: <?= $color[$j] ?>"><?= htmlentities($text[$i]); ?></span>
<?php }
} else {
echo "Empty String";
}
?>
Note that I have tidied up your code and made it slightly more sane/safe. htmlentities is used to stop XSS vulns that could come from this, despite being unlikely due to splitting the string. You were mixing up <?php echo .. ?> and <?= .. ?> for some reason, despite them being the exact same thing. Also, don't use <font>.
You said this:
At first, I understand that "after I used isset($_GET['text']) so next time I just use only($text), but now I'm confused.
If you know you're mixing them, why are you doing it? If you're checking for $_GET['text'] being set, then it's only logical that you would use that for access also.
Okay, why are you dropping in and out of PHP every line? It is allowed to have more than one line of PHP at a time, you know!
$_GET['text'] is a variable. Accessing it does nothing special, but it is special in that you can access it regardless of scope (it is superglobal). Referring to is as $text only works if the autoregister globals setting is enabled, which is not recommended for various reasons.
So, your code should look like:
<?php
$color = array(".....");
if( isset($_GET['text'])) {
$l = strlen($_GET['text']);
for( $i=0; $i<$l; $i++) {
$j = $i%10;
echo "<span style=\"color: ".$color[$j].";\">".$text[$i]."</span>";
}
}
else echo "Empty string";
?>
I also took the liberty of updating your HTML out of the last milennium.
You should initialize $text variable first, something like this:
$text = $_GET['text'];
This should work without any problems.
I'm still unsure as to what you're doing, but:
$colours = array("#FFCCFF", "#FFCCCC", "#FFCC99", "#FF99FF", "#FF99CC", "#FF9999", "#FF66FF", "#FF66CC", "#FF6699", "#FF6666");
if (isset($_GET['text'])) {
$text = $_GET['text'];
for ($i = 0; $i < strlen($text); $i++) {
$j = $i%10;
echo "<span style='color: {$colours[$j]}'>{$text[$i]}</span>";
}
}
else {
echo 'No text';
}

Categories