PHP - Problem Using/reaching Included Function?
Hey!
I have a small code where I want to check if one variable matches the other when the other is sent through a function. The function, for practical reasons, is included with a separate PHP-file. And I cant seem to apply a variable to the function which processes the other variable. Its really wierd to me. Here is the code for the main PHP-file: Code: [Select] <?php include 'function.php'; $unformatted = "FORMATTING AY ..."; $formatted1 = "formattingay..."; $formatted2 = test_format($unformatted); if ($formatted1 == $formatted2) { echo "Success, formatted!"; } else { echo "Fail, unformatted."; } ?> And here is the code for "function.php": Code: [Select] <?php function test_format($var) { strtolower(str_replace(array(" "), array(""), $var)); } ?> Does anybody have a clue to why this simply wont work? Any answers and help is highly appreciated! Similar TutorialsSo, I feel like I am running up against some beginner's problem. So I am hoping this should be an easy fix. I have had a bit of trouble finding the right search terms to find a fix for this, so I am sorry ahead of time if there is already a post on this, please point me towards it. I am running PHP 4.4.9 and MySQL client API 4.1.22, in case that is of use. I can get the following to work and provide the appropriate output. Note in this first case that the connection info is in the same file as the call to it. <?php // set database access information define ('DB_USER', "*****"); define ('DB_PASSWORD', "*****"); define ('DB_HOST', "localhost"); define ('DB_NAME', "content"); // database connection protocol $dbc = mysql_connect (DB_HOST, DB_USER, DB_PASSWORD) or die ('Could not connect to MySQL: Error #' . mysql_errno() . ' - ' . mysql_error()); mysql_select_db (DB_NAME) or die ('Could not connect to MySQL: Error #' . mysql_errno() . ' - ' . mysql_error()); $query = "SELECT content_element_title FROM content_main"; $result = mysql_query ($query); while ($row = mysql_fetch_array ($result, MYSQL_ASSOC)) { echo ("<p>" . $row[content_element_title] . "</p>"); } unset($dbc); ?> My problem is, however, that when I separate the connection info into a separate file, I have been having problems. I think I got past the method calling the connection info not being able to see it, but now it isn't returning anything - should be returning "<p>" . $row[content_element_title] . "</p>", for which there are three rows in the db. Here is what the two files look like separated: kinnect.php <?php // set database access information define ('DB_USER', '*****'); define ('DB_PASSWORD', '*****'); define ('DB_HOST', 'localhost'); define ('DB_NAME', 'content'); //// database connection protocol $dbc = mysql_connect (DB_HOST, DB_USER, DB_PASSWORD) or die ('Could not connect to MySQL: Error #' . mysql_errno() . ' - ' . mysql_error()); mysql_select_db (DB_NAME, $dbc) or die ('Could not connect to MySQL: Error #' . mysql_errno() . ' - ' . mysql_error()); ?> file.php <?php require_once ("correctpathto/kinnect.php"); $query = "SELECT content_element_title FROM content_main"; $result = mysql_query ($query, $dbc); while ($row = mysql_fetch_array ($result, MYSQL_ASSOC)) { echo ("<p>" . $row[content_element_title] . "</p>"); } unset($dbc); ?> So what am I doing wrong? I am getting these error messages now. Warning: mysql_query(): supplied argument is not a valid MySQL-Link resource in /Users/max/Sites/rdbase-llc/preliminary/connecttroubleshoot.php on line 18 Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource in /Users/max/Sites/rdbase-llc/preliminary/connecttroubleshoot.php on line 20 Thanks ahead of time for any help! Code: [Select] $date = date('m-d-y'); $ip = $_SERVER['REMOTE_ADDR']; mysql_query("INSERT INTO users VALUES ($username, $password, 0, $ip, $date)") or die(mysql_error()); Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '.60.116, 03-06-11)' at line 1 I'm not sure why I get this error. :/ This topic has been moved to Other Web Server Software. http://www.phpfreaks.com/forums/index.php?topic=318962.0 I have a while loop in a script that is running for a very long time due to the large values that are passing through it. Below is the link to the pastebin code and code embedded in this forum. Loop Statement Snipet if (!$user_class->invincible) { if (!$defender->invincible) { while ($yourhp > 0 && $theirhp > 0) { $damage = round($defender->moddedstrength) - $user_class->moddeddefense; $damage = ($damage < 1) ? 1 : $damage; if (!$wait) { $yourhp = $yourhp - $damage; ++$number; $log[] = $number . ": " . $defender->formattedname . " hit you for " . prettynum($damage) . " damage using their " . $defender->weaponname . ". <br />"; } else $wait = 0; if ($yourhp > 0) { $damage = round($user_class->moddedstrength) - $defender->moddeddefense; $damage = ($damage < 1) ? 1 : $damage; $theirhp = $theirhp - $damage; ++$number; $log[] = $number . ": " . "You hit " . $defender->formattedname . " for " . prettynum($damage) . " damage using your " . $user_class->weaponname . ". <br />"; } } $log = array_slice($log, -10, 10, true); foreach($log as $text) echo $text; } else $yourhp = 0; } else $theirhp = 0;
My issue is that $yourhp and $theirhp can be in the 100's of thousands causing this to loop half a million plus times. I was curious if there was a way to only show the first few lines and last few lines of this but still retain the increment value that's created? Thanks so much in advance. NICON Hi, Im in trouble with a script. Mainly the problem is that the declared value is not reachable. lets sai i have main.php file where i declare that $user_id = '22'; and then i include a file that needs to get that value to work include('somescript.php'); now when i go over to the somescript.php i write at the top that print $user_id; and i get nothing. What am i doing wrong? Does a Session's scope carry over to included files? Let's say I have a file "index.php" and it has a Session. If "index.php" includes a file called "header.inc.php", does the scope of the Session in "index.php" carry over to the included header? For instance, could I check $_SESSION['LoggedIn'] in "header.inc.php"? Debbie Hello: I have this code in an included file: myNav.php Code: [Select] function spLeftMenu() { $spLeftMenu = " <p> <div id=\"myLeftNavPaper\"> <img src=\"images/sidePaperTop.png\" alt=\"\" /> <div id=\"myLeftNavPaper2\"> echo \". $mySideBarPageData .\" </div> <img src=\"images/sidePaperBottom.png\" alt=\"\" /> </div> </p> "; return $spLeftMenu; } I can not get: Code: [Select] echo \". $mySideBarPageData .\" To display the results on this page: Page.php Code: [Select] <html> ... <?php echo spLeftMenu(); ?> ... </html> What am I missing ?? Hi All, I'm trying to secure my web app which is currently in development, and came across this issue. I have a header.php and footer.php page which are included to every page, with the content in the middle. The problem is, if you visit header.php then it displays the header, with some blank text. What is the best way to protect this - i.e., if visited directly, it re-directs to index.php etc. My initial thought is to set a $happylink on each page and in the header and footer, checking basically doing the following if (isset($happylink) && !empty($happylink)) { blah blah; } else { Header("Location: index.php"); } Would that be the best way? Is there something easier? Hy! I have 3 files: file 1 (index.php) includes 2 files: file2.php and file3.php File2.php contains $aditionalStuff and in file3.php I want to use $aditionalStuff, but it wont work (like it wasn't initialized). How can I make this work? index.php include "file2.php"; include "file3.php"; file2.php $aditionalStuff = 'some stuff'; file3.php echo $aditionalStuff; Thanks! Hi, I'm trying to write myself a tiny MVC framework and having some trouble: Code: [Select] <?php class One { public function main ( ) { $var = 'Hello'; include ( 'file.php' ); } } ?>file.php: Code: [Select] <?php echo $var; ?>This doesn't work. Is there any way without setting that variable to global, to reach it like that? I hope that subject made sense! I have a page where I want to generate page-specific keywords automatically. Actually I have some general keywords stored in a text file and then I add the page-specific ones after those. The problem is, however, solely caused by the keywords I pull from my text file. A "1" is added to my list of keywords. Consider a news page like so: news.php // ... <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta name="keywords" content="<?php require('php/generateKeywordList.php'); ?>" /> </head> // ... And then generateKeywordList.php // I have omitted the part with the page-specific keywords, because it is not what causes the problem (commented it all out) set_include_path('/mypath/'); $str = require_once('includes/websiteKeywords.txt'); echo $str; // For some reason, the number 1 is added at the end of this string websiteKeywords.txt (it doesn't matter what I put in there) Code: [Select] these, are, my, keywords, for, my, website In my meta tag, the above would be displayed as: Code: [Select] these, are, my, keywords, for, my, website1 I then tried to make a simple php page like this $keywords = require('includes/websiteKeywords.txt'); echo $keywords; ... and it worked. At the moment I have absolutely no idea where the number 1 comes from. So, basically if I include the keywords directly from the text file into my meta tag, it displays fine. If I make a simple php page where I echo out the keywords from the text file, it displays fine. But if I include my php script, which echos the keywords, into my meta tag, the number 1 is added at the end of the string. Am I completely missing something here or is this extremely strange? Thanks for any help! I understand that this is a header error but i still do not know how to fix it. I am trying to create a login box that is in the top right corner of my site. Once the user uses it to log in they need to be redirected to the account page. i include the login_box.php file in the appropriate div. however the file uses header("Location: account.php"); to redirect the user. because this file is included after the header i receive Warning: Cannot modify header information - headers already sent by (output started at C:\xampp\htdocs\index.php:17) in C:\xampp\htdocs\layout_inc\login_box.php on line 76 What would be the correct way to do this. My code is bellow. Thank you in advance <?php //Forms posted if(!empty($_POST)) { $errors = array(); $username = trim($_POST["username"]); $password = trim($_POST["password"]); $remember_choice = trim($_POST["remember_me"]); //Perform some validation //Feel free to edit / change as required if($username == "") { $errors[] = lang("ACCOUNT_SPECIFY_USERNAME"); } if($password == "") { $errors[] = lang("ACCOUNT_SPECIFY_PASSWORD"); } //End data validation if(count($errors) == 0) { //A security note here, never tell the user which credential was incorrect if(!usernameExists($username)) { $errors[] = lang("ACCOUNT_USER_OR_PASS_INVALID"); } else { $userdetails = fetchUserDetails($username); //See if the user's account is activation if($userdetails["Active"]==0) { $errors[] = lang("ACCOUNT_INACTIVE"); } else { //Hash the password and use the salt from the database to compare the password. $entered_pass = generateHash($password,$userdetails["Password"]); if($entered_pass != $userdetails["Password"]) { //Again, we know the password is at fault here, but lets not give away the combination incase of someone bruteforcing $errors[] = lang("ACCOUNT_USER_OR_PASS_INVALID"); } else { //Passwords match! we're good to go' //Construct a new logged in user object //Transfer some db data to the session object $loggedInUser = new loggedInUser(); $loggedInUser->email = $userdetails["Email"]; $loggedInUser->user_id = $userdetails["User_ID"]; $loggedInUser->hash_pw = $userdetails["Password"]; $loggedInUser->display_username = $userdetails["Username"]; $loggedInUser->clean_username = $userdetails["Username_Clean"]; $loggedInUser->remember_me = $remember_choice; $loggedInUser->remember_me_sessid = generateHash(uniqid(rand(), true)); //Update last sign in $loggedInUser->updateLastSignIn(); if($loggedInUser->remember_me == 0) $_SESSION["userCakeUser"] = $loggedInUser; else if($loggedInUser->remember_me == 1) { $db->sql_query("INSERT INTO ".$db_table_prefix."Sessions VALUES('".time()."', '".serialize($loggedInUser)."', '".$loggedInUser->remember_me_sessid."')"); setcookie("userCakeUser", $loggedInUser->remember_me_sessid, time()+parseLength($remember_me_length)); } //Redirect to user account page header("Location: account.php"); die(); } } } } } if(!isUserLoggedIn()) {?><form name="newUser" action="<?php echo $_SERVER['PHP_SELF'] ?>" method="post"> <table> <tr> <td> <label>Username:</label> </td> <td> <input type="text" name="username" /> </td> </tr> <tr> <td> <label>Password:</label> </td> <td> <input type="password" name="password" /> </td> </tr> <tr> <td> <label> </label> <input type="submit" value="Login" class="submit"/> </td> <td> <input type="checkbox" name="remember_me" value="1" /> <label style="font-size:12px">Remember Me?</label> </td> </tr> </table> <div style="text-align:center;"> <a href="register.php" class="info">Register</a> | <a href="forgot-password.php" class="info">Forgot Password?</a> </div> </form><?php } else{?><h1>Welcome <?php echo $loggedInUser->display_username; ?> </h1> <br/> <a href="account.php" class="info">Dashboard</a> | <a href="logout.php" class="info">Logout</a><?php } ?> I have obviouslt done something wrong for I get the following errors/warnings when running a simple script:- Warning: include(/var/www/www.stockton.co.za/doc/kiosk/includes/body-background.inc) [function.include]: failed to open stream: Permission denied in /var/www/www.stockton.co.za/doc/kiosk/MostRecent.php on line 10 Warning: include() [function.include]: Failed opening '/var/www/www.stockton.co.za/doc/kiosk/includes/body-background.inc' for inclusion (include_path='/var/www/www.stockton.co.za/doc/kiosk/includes') in /var/www/www.stockton.co.za/doc/kiosk/MostRecent.php on line 10 Warning: include(includes/error-handler.inc) [function.include]: failed to open stream: Permission denied in /var/www/www.stockton.co.za/doc/kiosk/MostRecent.php on line 11 Warning: include() [function.include]: Failed opening 'includes/error-handler.inc' for inclusion (include_path='/var/www/www.stockton.co.za/doc/kiosk/includes') in /var/www/www.stockton.co.za/doc/kiosk/MostRecent.php on line 11 Warning: include(includes/get-input.inc) [function.include]: failed to open stream: Permission denied in /var/www/www.stockton.co.za/doc/kiosk/MostRecent.php on line 12 Warning: include() [function.include]: Failed opening 'includes/get-input.inc' for inclusion (include_path='/var/www/www.stockton.co.za/doc/kiosk/includes') in /var/www/www.stockton.co.za/doc/kiosk/MostRecent.php on line 12 Fatal error: Call to undefined function mssql_connect() in /var/www/www.stockton.co.za/doc/kiosk/MostRecent.php on line 14 this from the code :- Code: [Select] <?php ini_set('include_path', dirname(__FILE__) .'/includes'); // require_once(dirname(__FILE__) . "/includes/body-background.php"); include(dirname(__FILE__) .'/includes/body-background.inc'); include('includes/error-handler.inc'); include('includes/get-input.inc'); Please tell me what I have done wrong. This with Apache2 on Ubuntu 10.4 and php 5.3. I have created a script (single file) that works fine when testing it alone, but when included it doesn't and rest of page is blank. What could cause this? Is this because of some "mismatch" between the queries, variables used on the included file and the existing file? Say I have... Code: [Select] <? echo("do something"); include("include_file.php"); echo("do something else"); ?> include_file.php Code: [Select] <? $a_$string = "a string"; echo($a_string); ?> I have put an error in the include_file.php an extra $ in the variable name. The first script would kick up an error that there is a problem with file include_file.php as line 3 or what ever the line may be. How can I have it so I can choose what the error message is, say a cryptic code and the line number without having the file names show as this is showing up my hidden includes folder and the file name which means that someone may try to visit this page alone and this can cause security issues. Adding in extra lines to every file to see if it is being use correctly a bit like sessions is not an option although I have looked at it as I have houndreds of files to alter in this case. I have just tried this instead of the top script but I does not show the secret code on error Code: [Select] <? echo("top"); @include("dummy.php") or die("secreterrorcode123"); echo("bottom"); ?> Hi, My issue here is that I cant get my if/else statement to work on my secondary page. I include my secondary page (fine.php) from my index page. However, I have an if/else statement in fine.php that keeps reverting back to the index.php and, therefore, outputs the else statement (404.php) here is the if/else on index.php (these links work fine): <?php if($_SERVER['QUERY_STRING']=='/index.php' || $_SERVER['QUERY_STRING']=='') { include 'port.php'; } elseif (isset($_GET['pos'])){ include 'pos.php'; } elseif (isset($_GET['web'])){ include 'web.php'; } elseif (isset($_GET['fine'])){ include 'fine.php'; } else {include '404.php';} here is the if/else on my secondary page (fine.php). These links are supposed to alert the if/else in the next table cell. However, they instead alert the if/else in index.php. <td><br/> <a href="?backset"><img src="fine/thumbs/x-backset.jpg" border="0"></a><br/><br/> <a href="?backside"><img src="fine/thumbs/x-backside.jpg" border="0"></a><br/><br/> <a href="?bannerprint"><img src="fine/thumbs/x-bannerprint.jpg" border="0"></a><br/><br/> <a href="?chopu"><img src="fine/thumbs/x-chopu.jpg" border="0"></a><br/><br/> </td> <td><br/> <div id="DivPiece" align="left"> <?PHP if (isset($_GET['backset'])){ include 'fine/backset.php'; } elseif (isset($_GET['backside'])){ include 'fine/backside.php'; } elseif (isset($_GET['bannerprint'])){ include 'fine/bannerprint.php'; } elseif (isset($_GET['chopu'])){ include 'fine/chopu.php'; } ?> </div> </td> How can I get the links on the secondary page to only alert the if/else statement on that page, and BLOCK the if/else statement on index.php from seeing them? I still want to use the query string though. Thanks! I have a snippet of code like this below. If I have it directly on my page, it works fine. But if I move this snippet of code into an include file and use "require_once('thefile.php');", the code no longer works properly. How is that possible? FYI, this snippet is in the middle of a for loop on the regular page. Maybe you can't use includes when in a loop? I don't know. Makes no sense that it works when on the page, but not when included using require once. Any thoughts how this could be possible? I imagine there is some rule with include files that I'm missing??? This is the code and I don't think it matters exactly what its doing so I won't bother you with that. This is how it looks on the page itself... Code: [Select] if ($type=="one") { $_SESSION['cluenum']=1; //so clue #1 begins as the selected clue echo "<script type='text/javascript'>document.getElementById('clue1').style.border = '1px solid red';</script>"; //sets the styling on clue #1 $allcode = "onclick='setnumber($i);'"; } else { // type must be equal to all, so don't do anything special $allcode=""; } This is how it looks in the include file... Code: [Select] <?php if ($type=="one") { $_SESSION['cluenum']=1; //so clue #1 begins as the selected clue echo "<script type='text/javascript'>document.getElementById('clue1').style.border = '1px solid red';</script>"; //sets the styling on clue #1 $allcode = "onclick='setnumber($i);'"; } else { // type must be equal to all, so don't do anything special $allcode=""; } ?> This topic has been moved to Miscellaneous. http://www.phpfreaks.com/forums/index.php?topic=332865.0 Hello, In m script, I need to get the content of another php file as a string, including the content of all the files which are included in it and in lower levels. Any idea how to do it? I tried output buffer+include but it doesn't get the content of the included files. Thanks I have a very weird problem. On my website i have a script that takes random pages and displays them on the homepage. It works without a problem on its own but when i have it included in the homepage using include('webmaster fav.php'); i get this error: Warning: Cannot use a scalar value as an array in /mnt/w0210/d28/s25/b02a8bb2/www/webmaster fav.php on line 18 and this error: Warning: array_unique() [function.array-unique]: The argument should be an array in /mnt/w0210/d28/s25/b02a8bb2/www/webmaster fav.php on line 20 and this error: Warning: array_unique() [function.array-unique]: The argument should be an array in /mnt/w0210/d28/s25/b02a8bb2/www/webmaster fav.php on line 21 and this error: Warning: Cannot use a scalar value as an array in /mnt/w0210/d28/s25/b02a8bb2/www/webmaster fav.php on line 23 I am kindof new to php but i think its a good script and it works without errors when it isn't included on the homepage it works. what could be the problem? heres the code: <?php $directory = "/mnt/w0210/d28/s25/b02a8bb2/www/data/"; //the list of pages i want to be random on the site $directory = (!strstr($directory,"*") || $directory =="./" ) ? $directory."*" : $directory; //Checks if the wildcard operator is present, and if not it adds it by default at the end; $files = glob($directory); //Yes, it was that easy to get all the files; $size=sizeof($files); for($i=0;$i<sizeof($files) ; $i++){ //Loop through the files and adds to array; $fp = fopen($files[$i],"r"); $contents[$i]=fgets($fp,999); fclose($fp); } for($x=0;$x<15;$x++){ $numb[$x]=rand(1, sizeof($files)); } $x=count($numb)-count(array_unique($numb)); $num = array_unique ($numb); for($q=0;$x<15;$x++){ $numb[$x]=rand(1, sizeof($files)); } //$imploded = implode(" ", $contents); //get rid of spaces //$newcontent=explode("~", $imploded); // sort into chucks so i can display the data. for($i=0;$i<15; $i++){ $number=$num[$i]; if($contents[$number]==""||$contents[$number]==" "||$contents[$number]==null){ } else{ echo "<li>"; $replacedcontent=str_replace(' ', '-',$contents[$number]); echo "<br/><a href='games/$replacedcontent'>"; $newrcontent=str_replace('-', ' ',$replacedcontent); echo "<img src='$newrcontent.jpg' border='2'></img>"; echo "<br/>$newrcontent</a></li>"; } } ?> i copied and pasted it from many sites examples so thats why some comments are weird... but basically it gets all the data files. reads the title and puts them in an array, then chooses some random ones and puts them in with their image so they can be displayed on the homepage. |