Shoutcast Script Does Not Work with Names that Have an Apostrophe - php

Please help me I don't know what to do. Tried urlencode but does not work
UTF-8 does not works. I need the script can read apostrophe for display image but nothing to do I am not a programmer and now I need your help for solve this problem.
<?php
$cover_d = 'http://metalrockpopradio.caramania.com/blackblack.gif';
$sc_url_ip = "69.175.13.131";
$sc_url_port = "8050";
function getNowPlaying($sc_url_ip,$sc_url_port) {
$open = fsockopen($sc_url_ip,$sc_url_port,$errno,$errstr,'.5');
if ($open) {
fputs($open,"GET /7.html HTTP/1.1\nUser-Agent:Mozilla\n\n");
stream_set_timeout($open,'1');
$read = fread($open,200);
$text = explode(",",$read);
if($text[6] == '' || $text[6] == '</body></html>') {
$msg = ' live stream ';
} else {
$msg = $text[6];
}
$text = $msg;
} else {
return false;
}
fclose($open);
return $text;
}
$current_song = getNowPlaying($sc_url_ip,$sc_url_port);
$current_song = iconv('ISO-8859-1', 'UTF-8', $current_song);
$singinfo = explode(" - ",$current_song);
$artist = urlencode($singinfo[0]);
$titel = urlencode(strip_tags($singinfo[1]));
$imgurl = #file_get_contents("http://api.depubliekeomroep.nl /anp/albumart.php?artiest=".$artist."&titel=".$titel."&size=extralarge");
if ($imgurl != "") {
print "<img src=\"" . $imgurl . "\">";
} else {
print "<img src=\"" . $cover_d . "\">";
}
?>

We are talking about ASCII 39 yes? I mean this even works...
<?php
$artist = "Tom Petty";
$title = "I won't back down";
$uri = "http://api.depubliekeomroep.nl/anp/albumart.php?artiest={$artist}&titel={$title}&size=extralarge";
var_dump(file_get_contents($uri));
'https://lastfm-img2.akamaized.net/i/u/300x300/05600d9c77a9288add89fac53d3482e7.png'
(length=82)
Maybe provide an example of the actual string giving you trouble?
While the above works for me it might be dependent on underlying wrapper.
Best practice would be:
$title = urlencode("I won't back down");

Related

PHP Crawler going in Infinite Loop

This is the whole crawler code that I am trying to build. This code is a single domain crawler. But it has a big problem, when I checked the database it was saving some of the links again and again, which creates an infinite loop. I want to solve this problem without using my database because checking each link for a presence in my database will make this crawler slow. How can I do that? + If you have any suggestions to make it faster?
<?php
include_once('ganon.php');
ini_set('display_errors', '1');
function gethost($link)
{
$link = trim($link, '/');
if (!preg_match('#^http(s)?://#', $link))
{
$link = 'http://' . $link;
}
$urlParts = parse_url($link);
$domain = preg_replace('/^www\./', '', $urlParts['host']);
return $domain;
}
function store($raw, $link)
{
$html = str_get_dom($raw);
$title = $html('title', 0)->getPlainText();
$con = #mysqli_connect('somehost', 'someuser', 'somepassword', 'somedatabase');
if (!$con)
{
echo "Error: " . mysqli_connect_error();
exit();
}
$query = "INSERT INTO `somedatabase`.`sometable` (`title`, `url`) VALUES ('$title', '$link');";
mysqli_query($con, $query);
mysqli_close($con);
echo $title."<br>";
}
function crawl_save_crawl($target)
{
$curl = curl_init($target);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
$result = curl_exec($curl);
if(curl_errno($curl))
{
echo 'Curl error: ' . curl_error($curl);
}
curl_close($curl);
$dom = str_get_dom($result);
foreach($dom('a') as $element)
{
$href = $element->href;
if (0 !== strpos($href, 'http'))
{
$path = '/' . ltrim($href, '/');
if (extension_loaded('http'))
{
$href = http_build_url("http://www.".gethost($target), array('path' => $path));
}
else
{
$parts = parse_url("http://www.".gethost($target));
$href = $parts['scheme'] . '://';
if (isset($parts['user']) && isset($parts['pass']))
{
$href .= $parts['user'] . ':' . $parts['pass'] . '#';
}
$href .= $parts['host'];
if (isset($parts['port']))
{
$href .= ':' . $parts['port'];
}
$href .= dirname($parts['path'], 1).$path;
}
}
if (gethost($target) == gethost($href))
{
crawl_save_crawl($href);
}
}
store($result, $target);
}
$url=$_GET['u'];
crawl_save_crawl($url);
?>
In your crawl_save_crawl() function, you could store the links you've already visited and therefore stop the code going back to them. Using a static variable isn't ideal, but in such a limited piece of code it serves the purpose it was intended for (to hold it's value across calls).
This doesn't stop it searching things other pages have searched, but stops it looping in itself.
function crawl_save_crawl($target)
{
static $alreadyDone = null;
if ( $alreadyDone == null ) {
$alreadyDone = [$target];
}
In the first loop, this will add the current reference in as this would previously have caused it to be missing.
Then before you call the same routing, you can test if it's already been checked...
$visit = trim(str_replace(["http://","https://"], "", $href), '/');
if (in_array($visit, $alreadyDone) === false &&
gethost($target) == gethost($href))
{
$alreadyDone[] = $visit;
crawl_save_crawl($href);
}
This may still look as though it's visiting the same page, but as your logic sometimes creates a href with 'www.' at the start, this may be different than without it. So when ccrawling stackoverflow, this means there is stackoverflow.com and www.stackoverflow.com.

PHP Telegram Bot (editMessageText & editReplyMarkup)

I am Kevin and these days I'm having problems with the functions editMessageText and editReplyMarkup. This is my code and I don't know where is the problem.
This is my code:
<?php
$botToken = "XXXXXXXXX:XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
$website = "https://api.telegram.org/bot".$botToken;
$FilejSon = file_get_contents("php://input");
$FilejSon = json_decode($FilejSon, TRUE);
$FirstName = $FilejSon["message"]["chat"]["first_name"];
$UserChatId = $FilejSon["message"]["chat"]["id"];
$Message = $FilejSon["message"]["text"];
$MessageID = $FilejSon["message"]["message_id"];
$CallBackID = $FilejSon["callback_query"]["from"]["id"];
$CallBackData = $FilejSon["callback_query"]["data"];
$what = ["callback_query"]["message"]["inline_message_id"];
$document = "http://media.giphy.com/media/109Ku3hdapZJle/giphy.gif"; //It's just a funny image
//Emoji
$phone = json_decode('"\uD83D\uDCF2"');
$list = json_decode('"\uD83D\uDCCB"');
$money = json_decode('"\uD83D\uDCB0"');
$postbox = json_decode('"\uD83D\uDCEE"');
$sos = json_decode('"\uD83C\uDD98"');
$link = json_decode('"\uD83D\uDD17"');
$jSonCodeKeyboard = '&reply_markup={"inline_keyboard":[[{"text":"1","url":"https://core.telegram.org/bots/api"}],[{"text":"2","url":"https://www.google.it"}],[{"text":"4","switch_inline_query_current_chat":"try"}],[{"text":"5","url":"https://www.google.it"},{"text":"'.$link.'%20Link%20'.$link.'","url":"http://botkevin.altervista.org/Bot/Nuovo_documento_di_testo.txt"}],[{"text":"6","callback_data":"Press"}]]}';
$jSonCodeKeyboard1 = '&reply_markup={"inline_keyboard":[[{"text":"Indietro","callback_data":"Ok"}]]}';
switch ($Message){
case '/start':
$msg = "Hello $GLOBALS[FirstName] $GLOBALS[MessageID] $GLOBALS[UserChatId] $GLOBALS[what].\n";
sendMessage($UserChatId, $msg, $jSonCodeKeyboard);
break;
case '/prova':
sendFile($UserChatId, $document);
break;
case '/prova1':
$msg = "worked $GLOBALS[MessageID]";
sendMessage($UserChatId, $msg, $jSonCodeKeyboard1);
break;
default:
if (callback($FilejSon)){
if ($CallBackData == "Press"){
sendMessage($CallBackID, "gg", $jSonCodeKeyboard1);
}
else if($CallBackData == "Ok")
{
$msg = "Edited";
Edit($CallBackID, $MessageID, $msg);
Edit1($CallBackID, $MessageID, $jSonCodeKeyboard1);
}
}
$msg = "Unrecognized command.";
sendMessage($UserChatId, $msg);
break;
}
function sendMessage($chat_id, $text, $LayoutKey){
if($LayoutKey==""){
$url = $GLOBALS[website]."/sendMessage?chat_id=".$chat_id."&text=".urlencode($text);
file_get_contents($url);
}
else{
$url = $GLOBALS[website]."/sendMessage?chat_id=".$chat_id."&text=".urlencode($text).$LayoutKey;
file_get_contents($url);
}
}
function sendFile($chat_id, $file){
$url = $GLOBALS[website]."/sendDocument?chat_id=".$chat_id."&document=".$file; //Gif,Pdf e Zip
file_get_contents($url);
}
function Edit($chat_id, $msgID, $text){
$url = $GLOBALS[website]."/editMessageText?chat_id=".$chat_id."&message_id=".$msgID."&text=".urlencode($text);
file_get_contents($url);
}
function Edit1($chat_id, $msgID, $LayoutKey){
$url = $GLOBALS[website]."/editMessageReplyMarkup?chat_id=".$chat_id."&message_id=".$msgID.$jSonCodeKeyboard1;
file_get_contents($url);
}
function callback($getUpdate){
return $getUpdate["callback_query"];
}?>
I've searched everywhere a solution but either were in another programming language or used a library and more, I'm not very good at php so i would like a basic thing like my code.
I would like to do that when I click on the inline keyboard of the first message that sends the bot by doing "/ start", clicking a button can modify the message and the inline keyboard without sending other messages clogging the chat.
(already checked https://core.telegram.org/bots/api)

Comparing URL strings in PHP

I'm trying to use the query from a GET url to determine the content of a page.
This is what I have (sentences edited for clarity):
<?php
//decalre variables
$title ='';
$welcome = '';
$params = '';
$params = $_SERVER['QUERY_STRING'];
echo $_SERVER['QUERY_STRING'];
echo $params;
if ($params='') {
header('start.html') ;
} else {
if ($params === "selection=republic") {
//echo $params;
//echo 'Republic';
$title = "Private";
$welcome = "Our .";
$signoff = "The Republic will strike back!";
}
else if ($params === "selection=rebels") {
//echo $params;
//echo 'Rebels';
$title = "Comrade";
$welcome = "Hey comrade, welcome to the Underground Network!";
$declaration="You see,o's!";
$signoff = "Rebel!!";
}
else if ($params === "selection=robots"){
//echo $params;
//echo 'Robots';
$title = "Bit";
$welcome = "Our data ";
$declaration="Knowledge w.";
$signoff = "ed now.";
}
else {
echo 'There was an error - please go back.';
}
}
The first echo shows the correct URL, but the comparison gets stuck at the third option.
Help!
This comes from the triple = sign, that compares the value and the type. You should see the difference here.
I suggest you only use two equals and by the way, you could ease your code by using the $_GET['selection'] variable instead:
<?php
//decalre variables
$title ='';
$welcome = '';
$params = '';
$params = $_SERVER['QUERY_STRING'];
echo $_SERVER['QUERY_STRING'];
echo $params;
if (!isset($_GET['selection']) { // Check whether selection is set
header('start.html') ;
} else {
if ($_GET['selection'] == "republic") {
//echo $params;
//echo 'Republic';
$title = "Private";
$welcome = "Our .";
$signoff = "The Republic will strike back!";
}
else if ($_GET['selection'] == "rebels") {
//echo $params;
//echo 'Rebels';
$title = "Comrade";
$welcome = "Hey comrade, welcome to the Underground Network!";
$declaration="You see,o's!";
$signoff = "Rebel!!";
}
else if ($_GET['selection'] == "robots"){
//echo $params;
//echo 'Robots';
$title = "Bit";
$welcome = "Our data ";
$declaration="Knowledge w.";
$signoff = "ed now.";
}
else {
echo 'There was an error - please go back.';
}
}
There are way better ways of parsing the query string than $SERVER['QUERY_STRING'], specifically you can use $_GET to access a specific parameter. Example: www.example.com?name=Dave&age=30...
to get the name, you can do $_GET['name'] and it will return Dave. I think a better way to do this would be something like:
$selection = $_GET['selection'];
if (empty($selection)) {
header('start.html') ;
}
else {
$vars = array(
'republic'=>array('title'=>'Private', 'welcome'=> 'Our .', 'declaration'=>'', 'signoff' => 'The Replublic will strike back'),
'rebels'=>array('title'=>'Comrade', 'welcome' => "Hey comrade, welcome to the Underground Network!", 'declaration'=>"You see,o's!",'signoff' => "Rebel!!"),
'robots'=>array('title'=>'Bit', 'welcome'=>'Our data', 'declaration'=>'Knowlegge W', 'signoff'=>'Ed now')
);
list($title, $welcome, $declaration, $signoff) = $vars[$selection];
}

Executing a PHP script from within nested batch scripts

I'm trying to rewrite our Windows FTP server configuration script that was created for IIS and now we're trying to get something similar working for Filezilla Server.
The structure goes like this, we have a batch file which is a for loop of another batch file, so we can batch configure our FTP websites. This batch file I'm currently trying to get working contains a line of code to execute a PHP script to set up the FTP username and password in Filezilla as well as doing a few other neat things.
Now, running CreateIIStmp.bat var1 var2 works just fine. But executing the BatchCreateIIS.bat seems to skip the execution of the php script, or the php script fails. (I'm just looking into how I put in some error handling into the PHP script to catch any error and display it, but I'm not a (PHP) developer/coder so I'll be updating this when I figure it out.)
Here's a stripped down version of what I'm talking about:
The initial batch file BatchCreateIIS.bat:
#Echo off
for /f %%X in (NewWebsiteEntries.txt) do start cmd.exe /c "CreateIIStmp.bat %%X %%X"
echo ...
echo *** BATCH PROCESS HAS BEEN COMPLETED ***
pause
The CreateIIStmp.bat:
# echo off
C:\php5\php-win.exe -f filezilla-user-script.php -- %1 %2
pause
#echo on
The NewWebsiteEntries.txt:
somedomain.com ftpuname
somedomain2.net ftpuname2
The filezilla-user-script.php:
<?php
$xmlfolder = 'C:/Program Files (x86)/FileZilla Server/';
$xmlfilename = 'FileZilla Server.xml';
$ftpRoot = 'C:/inetpub/wwwroot/';
$ftpDocumentation = 'C:/Documentation ftp server/';
$xmlfile = $xmlfolder . $xmlfilename;
$xmlbackupfile = $xmlfolder . #date("Y-m-d-H-i-s") . '_FileZilla_Server.xml';
// Copy Config for backup
createXMLbackup($xmlfile,$xmlbackupfile);
//Load XML file
$xml = simplexml_load_file($xmlfile);
$msg = "Allowed usernames: 20 characters out of a...z A...Z 0...9 _ \n\nPlease input username (Ctrl+C to quit)";
// Copy Config for backup before each change, too.
createXMLbackup($xmlfile,$xmlbackupfile);
echo "\n\n";
$input = ($argv[2]);
echo "\n";
//echo 'Userinput: ' . $input . "\n";
$isvalid = isUserID($input);
//var_dump($isvalid);
if($isvalid)
{
$ftpUserFolder = $ftpRoot . ($argv[1]);
if ((file_exists($ftpUserFolder) && is_dir($ftpUserFolder)))
{
echo "The directory $ftpUserFolder exists.\nPlease select another user name.\n";
}
else
{
//echo "The directory $ftpUserFolder does not exist\n";
if(!check_user_exists($xml,$input))
{
echo "Adding user $input...\n";
if (!mkdir($ftpUserFolder))
{
die("Could not create directory $ftpUserFolder \n");
}
else
{
echo "Directory $ftpUserFolder created.\n";
}
$password = generatePassword();
//echo 'Password: ' . $password . "\n";
$user = $xml->Users->addChild('User');
$user->addAttribute('Name', $input);
$option = $user->addChild('Option', md5($password));
$option->addAttribute('Name', 'Pass');
$option = $user->addChild('Option');
$option->addAttribute('Name', 'Group');
$option = $user->addChild('Option', '0');
$option->addAttribute('Name', 'Bypass server userlimit');
$option = $user->addChild('Option', '0');
$option->addAttribute('Name', 'User Limit');
$option = $user->addChild('Option', '0');
$option->addAttribute('Name', 'IP Limit');
$option = $user->addChild('Option', '1');
$option->addAttribute('Name', 'Enabled');
$option = $user->addChild('Option', 'none');
$option->addAttribute('Name', 'Comments');
$option = $user->addChild('Option', '0');
$option->addAttribute('Name', 'ForceSsl');
$filter = $user->addChild('IpFilter');
$filter->addChild('Disallowed');
$filter->addChild('Allowed');
$permissions = $user->addChild('Permissions');
$permission = $permissions->addChild('Permission');
$permission->addAttribute('Dir', str_replace("/","\\",$ftpUserFolder));
$option = $permission->addChild('Option', '1');
$option->addAttribute('Name', 'FileRead');
$option = $permission->addChild('Option', '1');
$option->addAttribute('Name', 'FileWrite');
$option = $permission->addChild('Option', '0');
$option->addAttribute('Name', 'FileDelete');
$option = $permission->addChild('Option', '1');
$option->addAttribute('Name', 'FileAppend');
$option = $permission->addChild('Option', '1');
$option->addAttribute('Name', 'DirCreate');
$option = $permission->addChild('Option', '0');
$option->addAttribute('Name', 'DirDelete');
$option = $permission->addChild('Option', '1');
$option->addAttribute('Name', 'DirList');
$option = $permission->addChild('Option', '1');
$option->addAttribute('Name', 'DirSubdirs');
$option = $permission->addChild('Option', '1');
$option->addAttribute('Name', 'IsHome');
$option = $permission->addChild('Option', '0');
$option->addAttribute('Name', 'AutoCreate');
$speed = $user->addChild('SpeedLimits');
$speed->addAttribute('DlType', '1');
$speed->addAttribute('DlLimit', '10');
$speed->addAttribute('ServerDlLimitBypass', '0');
$speed->addAttribute('UlType', '1');
$speed->addAttribute('UlLimit', '10');
$speed->addAttribute('ServerUlLimitBypass', '0');
$speed->addChild('Download');
$speed->addChild('Upload');
$rv = $xml->asXML($xmlfile);
//echo $rv . "\n";
if(!$rv)
{
die('SimpleXML could not write file');
}
//$newentry = $xml->addChild('element', iconv('ISO-8859-1', 'UTF-8', $write));
//The DOM extension uses UTF-8 encoding. Use utf8_encode() and utf8_decode()
//to work with texts in ISO-8859-1 encoding or Iconv for other encodings.
//make human readable, parse using DOM function
//otherwise everything will be printed on one line
if( !file_exists($xmlfile) ) die('Missing file: ' . $xmlfile);
else
{
$dom = new DOMDocument("1.0","ISO-8859-1");
//Setze die Flags direkt nach dem Initialisieren des Objektes:
$dom->preserveWhiteSpace = false;
$dom->formatOutput = true;
//$dl = #$dom->load($xmlfile); // remove error control operator (#) to print any error message generated while loading.
$dl = $dom->load($xmlfile); // remove error control operator (#) to print any error message generated while loading.
if ( !$dl ) die('Error while parsing the document: ' . $xmlfile);
//echo $dom->save($xmlfile) . "\n";
if(!$dom->save($xmlfile))
{
die('DOMDocument could not write file');
}
}
//Create documentation
$docuFile = $ftpDocumentation . $input . '.txt';
//echo $docuFile . "\n";
$docuString = "Username: " . $input . "\n";
$docuString = $docuString . "Password: " . $password . "\n";
$docuString = $docuString . "Folder: " . str_replace("/","\\",$ftpUserFolder) . "\n";
$docuString = $docuString . "Date: " . #date("d.m.Y") . "\n";
// $docuString = $docuString . "\n";
// $docuString = $docuString . "Direct link:\n";
// $docuString = $docuString . "ftp://" . $input . ":" . $password . "#ftp.yourcompany.com";
$handleDocuFile = fopen($docuFile, "wt");
if(!$handleDocuFile)
{
die('Could not fopen docu file');
}
$rv = fwrite($handleDocuFile, $docuString);
if(!$rv)
{
die('Could not fwrite docu file');
}
// Close xml file
$rv = fclose($handleDocuFile);
if(!$rv)
{
die('Could not fclose docu file');
}
echo "Documentary file written.\n";
$ftpExecutable = "\"C:\\Program Files (x86)\\FileZilla Server\\FileZilla server.exe\" /reload-config";
$command = $ftpExecutable;
$last_line = system($command, $retval);
echo ("Filezilla reloaded, user active.\n");
echo ("Close Notepad to add another user or quit.\n");
$command = "C:\\Windows\\System32\\notepad.exe $docuFile";
$last_line = system($command, $retval);
}
else
{
echo "Username $input already exists...\n";
}
}
}
else
{
echo "Username $input is invalid\n";
}
function check_user_exists($xml,$username)
{
$children=$xml->Users->children();
foreach($children as $child)
{
if ($child->getName()=='User')
{
foreach($child->attributes() as $attributes )
{
if(trim($attributes) == trim($username))
{
echo "Username $username already exists... \n";
return true;
}
}
}
}
return false;
}
function isUserID($username)
{
//return preg_match('/^\w{2,20}$/', $username);
return preg_match('/^[A-Za-z0-9][A-Za-z0-9]*(?:_[A-Za-z0-9]+)*$/', $username);
}
function isValid($str)
{
//return !preg_match('/[^A-Za-z0-9.#\\-$]/', $str);
return !preg_match('/[^A-Za-z0-9\_\-]/', $str);
}
function getInput($msg)
{
fwrite(STDOUT, "$msg: ");
$varin = trim(fgets(STDIN,20));
return $varin;
//$input = fgets($fr,128); // read a maximum of 128 characters
}
function createXMLbackup($xmlfile,$xmlbackupfile)
{
// Copy Config for backup
$rv = copy($xmlfile,$xmlbackupfile);
if(!$rv)
{
die('Problem creating xml backup file');
}
echo "\nBackup file created\n";
}
function generatePassword ($length = 15)
{
// start with a blank password
$password = "";
$possible = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
// we refer to the length of $possible a few times, so let's grab it now
$maxlength = strlen($possible);
// check for length overflow and truncate if necessary
if ($length > $maxlength)
{
$length = $maxlength;
}
// set up a counter for how many characters are in the password so far
$i = 0;
// add random characters to $password until $length is reached
while ($i < $length)
{
// pick a random character from the possible ones
$char = substr($possible, mt_rand(0, $maxlength-1), 1);
// have we already used this character in $password?
if (!strstr($password, $char))
{
// no, so it's OK to add it onto the end of whatever we've already got...
$password .= $char;
// ... and increase the counter by one
$i++;
}
}
// done!
return $password;
}
?>
I've looked around and there are some places that suggest using # in front of calling in PHP so: #C:\php5\php-win.exe -f filezilla-user-script.php -- %1 %2 but that doesn't work, and I can see that my script does work, just not in this nested form.
Maybe there's an approach to this problem that I'm missing? Or something that I don't know about executing scripts in nested batch scripts?
In your BatchCreateIIS.bat, when you use this:
start cmd.exe /c "CreateIIStmp.bat %%X %%X"
the parent cmd.exe will not wait for each instance of CreateIIStmp.bat (and child processes) to finish. Since you seem to be writing to the same XML file, it is likely that the DOM that get written last persists. Instead try this:
call "CreateIIStmp.bat %%X %%X"

Fatal error: Function name must be a string in public_html/install/index.php on line 1296

Warning: Please contact support about failure in /public_html/install/index.php on line 1295
Fatal error: Function name must be a string in /public_html/install/index.php on line 1296
Okay so I did bad at explaining the whole thing. So Basically I'm trying to install Boonex Dolphin 7.0.6 (Social Networking CMS) on my Web site. I installed all the files correctly. I went to the install page. Went to the second page where I had to make all the files Writable. Once I made all the files Writable I went on to the next page called "Paths". And this is where it gave me the error above. The file has over 1483 Lines. Here is the Code Below.
Where it says $func = create_function("", $funcbody); Thats Line 1295
Lines 1281 - 1350
function printInstallError($sText) {
$sRet = (strlen($sText)) ? '<div class="error">' . $sText . '</div>' : '';
return $sRet;
}
function createTable($arr) {
$ret = '';
$i = '';
foreach($arr as $key => $value) {
$sStyleAdd = (($i%2) == 0) ? 'background-color:#ede9e9;' : 'background-color:#fff;';
$def_exp_text = "";
if (strlen($value['def_exp'])) {
$funcbody = $value ['def_exp'];
$func = create_function("", $funcbody);
$def_exp = $func();
if (strlen($def_exp)) {
$def_exp_text = " <font color=green>found</font>";
$value['def'] = $def_exp;
} else {
$def_exp_text = " <font color=red>not found</font>";
}
}
$st_err = ($error_arr[$key] == 1) ? ' style="background-color:#FFDDDD;" ' : '';
$ret .= <<<EOF
<tr class="cont" style="{$sStyleAdd}">
<td>
<div>{$value['name']}</div>
<div>Description:</div>
<div>Example:</div>
</td>
<td>
<div><input {$st_err} size="30" name="{$key}" value="{$value['def']}" /> {$def_exp_text}</div>
<div>{$value['desc']}</div>
<div style="font-style:italic;">{$value['ex']}</div>
</td>
</tr>
EOF;
$i ++;
}
return $ret;
}
function rewriteFile($sCode, $sReplace, $sFile) {
$ret = '';
$fs = filesize($sFile);
$fp = fopen($sFile, 'r');
if ($fp) {
$fcontent = fread($fp, $fs);
$fcontent = str_replace($sCode, $sReplace, $fcontent);
fclose($fp);
$fp = fopen($sFile, 'w');
if ($fp) {
if (fputs($fp, $fcontent)) {
$ret .= true;
} else {
$ret .= false;
}
fclose ( $fp );
} else {
$ret .= false;
}
} else {
$ret .= false;
}
return $ret;
}
If you need more code please let me know so I can help also thanks for reading this ^_^ and re helping as well. I also tried what the last person said with the adding "$a" and ";" but it did not help. Just got me more errors.
What can be stored in $value['def_exp']?
As it is your create_function call is not returning a value. Or so it seems. I did a simple mock up to show an example:
$funcbody = 'hello';
$func = create_function('$a', 'return $a;');
$def_exp = $func($funcbody);
This works as expected. Depending on what is in $funcbody you either need to add a ; after it IE:
$func = create_function('$a', $funcbody . ';');
A return before it and ; after it:
$func = create_function('$a', 'return ' . $funcbody . ';');
Or pass it as a parameter as I did in the first example. Not sure which you require, as I do not know what is stored in the $value['def_exp'] but hopefully that gets you rolling.
create_function() is probably failing. try
var_dump( $func );
if its false, then that is why and you should look at $funcbody

Categories