PHP - Cannot Redeclare Previously Declared Function
I'm receiving a cannot redeclare function error. I have a functions.php pack that I only require_once once.
require_once 'functions.php'; require_once 'classes.php'; A little further into the code I conditionally require another php file. require_once 'dataentry.php'; It appears that when the require_once 'dataentry.php' line is hit, I receive this redeclare error. I do not call any include or require in dataentry.php. The first function in my function pack throws this error, and when I comment it out, the next function throws the error. Im appalled as to the reasoning for this error. Any Thoughts? Similar TutorialsHi all, I have this structure of two functions: function get_string_between($string, $start, $end){ $string = " ".$string; $ini = strpos($string,$start); if ($ini == 0) return ""; $ini += strlen($start); $len = strpos($string,$end,$ini) - $ini; return substr($string,$ini,$len); } function normaliza($text){ function entre($string, $start, $end){ $string = " ".$string; $ini = strpos($string,$start); if ($ini == 0) return ""; $ini += strlen($start); $len = strpos($string,$end,$ini) - $ini; return substr($string,$ini,$len); } foreach (count_chars($text, 1) as $i => $val) { if(chr($i)=='<'){ $totaltag = $val; } } for($u=0; $u <= $totaltag; $u++){ $parsed = entre($text, "<", ">"); $text = str_replace('<'.$parsed.'>',"",$text); } return $text; } The I passed a text named $data throught both functions and I got the correct return: $status = get_string_between($data, 'Inativo', 'CNPJ'); $status = normaliza($status); echo $status.' '; Just after, I passed the same folowing text throught the same both functions: $cnpj = get_string_between($data, 'CNPJ', 'Grau'); $cnpj = normaliza($status); echo $cnpj.' '; And I got this error: Cannot redeclare entre() (previously declared in C:\Users\entidade.php:47) in C:\Users\entidade.php on line 47 Why? I thougth this kind strange because it didin't gave the same error for the function get_string_between. Thanks danilo jr. Fatal error: Cannot redeclare limitatexto() (previously declared in funciones.php:4) in funciones.php on line 12 <?php function limitatexto( $texto, $limite ) - Line 4 { if( strlen($texto)>$limite ) { $texto = substr( $texto,0,$limite ); } return $texto; } Line 12 Hi All, My appologies in advance. I am pretty sure that this has probably been answered before by someone...but for the life of me I carn't find the answer in any forums. My basic question is this. Can you create an object at the beginning of a script, and then call its methods from within functions? I have coded the following: <?php ///import classes to use require "booking_form_gui.php"; $booking = new booking_form_gui(); function _booking_form($form_state){ ///$booking = new booking_form_gui(); return $booking -> date_selection(); <----------this line causes the error I guess } The problem is that when I run this code, I get an error message similar to the following: Fatal error: Call to a member function date_selection() on a non-object in /var/www/drupal_6/sites/default/modules/booking_system/booking_form/booking_form.module on line 127 Anyone any ideas how I could get round this? Thanks, Mark. Here is the code: // Count files function filecount($FolderPath) { $filescount = 0; // Open the directory $dir = opendir($FolderPath); // if the directory doesn't exist return 0 if (!$dir){return 0;} // Read the directory and get the files while (($file = readdir($dir)) !== false) { if ($file[0] == '.'){ continue; } //if '.' it is a sub folder and call the function recursively if (is_dir($FolderPath.$file)){ // Call the function if it is a folder type $filescount += filecount($FolderPath.$file.DIRECTORY_SEPARATOR); } else { // Increment the File Count. $filescount++; } } // close the directory closedir($dir); return $filescount; } function getfilenames($location) { // create an array to hold directory list $results = array(); // create a handler for the directory $handler = opendir($location); // open directory and walk through the filenames while ($file = readdir($handler)) { // if file isn't this directory or its parent, add it to the results if ($file != "." && $file != "..") { $results[] = $file; } } // tidy up: close the handler closedir($handler); // done! return $results; } function readfile($file) { $fh = fopen('./Data/' . $file, 'r'); $data = fread($fh, filesize($file)); fclose($fh); return $data; } Now, when I try to get the text from a textfile via the function readfile I get this error: Quote Fatal error: Cannot redeclare readfile() in ***Path\FileManagement.php on line 62 Whats wrong? Regards Worqy Hi there, I have a local server set up on my computer which I have used before and it worked flawlessly. It is running apache with PHPand mySQL set up as services. Recently I attempted to copy a project I have worked on at school onto my server. I have the database up and running, however when I try to run a PHP file it gives me the error: Quote Fatal error: Cannot redeclare getText() in C:\Server\htdocs\projects\tournament\includes\functions.php on line 20 When I rename that function (which I know is not being redeclared) I get a browser error: Quote This webpage is not available. The webpage at http://localhost/projects/tournament/index.php might be temporarily down or it may have moved permanently to a new web address. More information on this error Below is the original error message Error 101 (net::ERR_CONNECTION_RESET): Unknown error. Has anybody else experienced this error and have a solution to fix it? My guess is that it has to do with the function gettext() being available on this machine but not on the machine at school, however I thought PHP was case sensitive? Gooday Coders. Im using php 5.4 with xampp 1.8. Each time I run this script "add+stock.php", the script jumps to line 240 saying header is already defined. Thus referring to the session headers. What can I do to get rid of these header errors?
add_stock.php
<?php include_once("init.php"); ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>NIC - Add Stock Category</title> <!-- Stylesheets --> <link href='http://fonts.googleapis.com/css?family=Droid+Sans:400,700' rel='stylesheet'> <link rel="stylesheet" href="css/style.css"> <link rel="stylesheet" href="js/date_pic/date_input.css"> <link rel="stylesheet" href="lib/auto/css/jquery.autocomplete.css"> <!-- Optimize for mobile devices --> <meta name="viewport" content="width=device-width, initial-scale=1.0"/> <!-- jQuery & JS files --> <?php include_once("tpl/common_js.php"); ?> <script src="js/script.js"></script> <script src="js/date_pic/jquery.date_input.js"></script> <script src="lib/auto/js/jquery.autocomplete.js "></script> <script> /*$.validator.setDefaults({ submitHandler: function() { alert("submitted!"); } });*/ $(document).ready(function() { $("#supplier").autocomplete("supplier1.php", { width: 160, autoFill: true, selectFirst: true }); $("#category").autocomplete("category.php", { width: 160, autoFill: true, selectFirst: true }); // validate signup form on keyup and submit $("#form1").validate({ rules: { name: { required: true, minlength: 3, maxlength: 200 }, stockid: { required: true, minlength: 3, maxlength: 200 }, cost: { required: true, }, sell: { required: true, } }, messages: { name: { required: "Please Enter Stock Name", minlength: "Category Name must consist of at least 3 characters" }, stockid: { required: "Please Enter Stock ID", minlength: "Category Name must consist of at least 3 characters" }, sell: { required: "Please Enter Selling Price", minlength: "Category Name must consist of at least 3 characters" }, cost: { required: "Please Enter Cost Price", minlength: "Category Name must consist of at least 3 characters" } } }); }); function numbersonly(e){ var unicode=e.charCode? e.charCode : e.keyCode if (unicode!=8 && unicode!=46 && unicode!=37 && unicode!=38 && unicode!=39 && unicode!=40 && unicode!=9){ //if the key isn't the backspace key (which we should allow) if (unicode<48||unicode>57) return false } } </script> </script> </head> <body> <!-- TOP BAR --> <?php include_once("tpl/top_bar.php"); ?> <!-- end top-bar --> <!-- HEADER --> <div id="header-with-tabs"> <div class="page-full-width cf"> <ul id="tabs" class="fl"> <li><a href="dashboard.php" class="dashboard-tab">Dashboard</a></li> <li><a href="view_sales.php" class="sales-tab">Sales</a></li> <li><a href="view_customers.php" class=" customers-tab">Customers</a></li> <li><a href="view_purchase.php" class="purchase-tab">Purchase</a></li> <li><a href="view_supplier.php" class=" supplier-tab">Supplier</a></li> <li><a href="view_product.php" class="active-tab stock-tab">Stocks / Products</a></li> <li><a href="view_payments.php" class="payment-tab">Payments / Outstandings</a></li> <li><a href="view_report.php" class="report-tab">Reports</a></li> </ul> <!-- end tabs --> <!-- Change this image to your own company's logo --> <!-- The logo will automatically be resized to 30px height. --> <a href="#" id="company-branding-small" class="fr"><img src="<?php if(isset($_SESSION['logo'])) { echo "upload/".$_SESSION['logo'];}else{ echo "upload/NIC.png"; } ?>" alt="Point of Sale" /></a> </div> <!-- end full-width --> </div> <!-- end header --> <!-- MAIN CONTENT --> <div id="content"> <div class="page-full-width cf"> <div class="side-menu fl"> <h3>Stock Management</h3> <ul> <li><a href="add_stock.php">Add Stock/Product</a></li> <li><a href="view_product.php">View Stock/Product</a></li> <li><a href="add_category.php">Add Stock Category</a></li> <li><a href="view_category.php">view Stock Category</a></li> <li><a href="view_stock_availability.php">view Stock Available</a></li> </ul> </div> <!-- end side-menu --> <div class="side-content fr"> <div class="content-module"> <div class="content-module-heading cf"> <h3 class="fl">Add Stock </h3> <span class="fr expand-collapse-text">Click to collapse</span> <div style="margin-top: 15px;margin-left: 150px"></div> <span class="fr expand-collapse-text initial-expand">Click to expand</span> </div> <!-- end content-module-heading --> <div class="content-module-main cf"> <?php //Gump is libarary for Validatoin if(isset($_POST['name'])){ $_POST = $gump->sanitize($_POST); $gump->validation_rules(array( 'name' => 'required|max_len,100|min_len,3', 'stockid' => 'required|max_len,200', 'sell' => 'required|max_len,200', 'cost' => 'required|max_len,200', 'supplier' => 'max_len,200', 'category' => 'max_len,200' )); $gump->filter_rules(array( 'name' => 'trim|sanitize_string|mysql_escape', 'stockid' => 'trim|sanitize_string|mysql_escape', 'sell' => 'trim|sanitize_string|mysql_escape', 'cost' => 'trim|sanitize_string|mysql_escape', 'category' => 'trim|sanitize_string|mysql_escape', 'supplier' => 'trim|sanitize_string|mysql_escape' )); $validated_data = $gump->run($_POST); $name = ""; $stockid = ""; $sell = ""; $cost = ""; $supplier = ""; $category = ""; if($validated_data === false) { echo $gump->get_readable_errors(true); } else { $name=mysql_real_escape_string($_POST['name']); $stockid=mysql_real_escape_string($_POST['stockid']); $sell=mysql_real_escape_string($_POST['sell']); $cost=mysql_real_escape_string($_POST['cost']); $supplier=mysql_real_escape_string($_POST['supplier']); $category=mysql_real_escape_string($_POST['category']); $count = $db->countOf("stock_details", "stock_name ='$name'"); if($count>1) { $data='Dublicat Entry. Please Verify'; $msg='<p style=color:red;font-family:gfont-family:Georgia, Times New Roman, Times, serif>'.$data.'</p>';// ?> <script src="dist/js/jquery.ui.draggable.js"></script> <script src="dist/js/jquery.alerts.js"></script> <script src="dist/js/jquery.js"></script> <link rel="stylesheet" href="dist/js/jquery.alerts.css" > <script type="text/javascript"> jAlert('<?php echo $msg; ?>', 'NIC'); </script> <?php } else { if($db->query("insert into stock_details(stock_id,stock_name,stock_quatity,supplier_id,company_price,selling_price,category) values('$stockid','$name',0,'$supplier',$cost,$sell,'$category')")) { $db->query("insert into stock_avail(name,quantity) values('$name',0)"); $msg=" $name Stock Details Added" ; header("Location: add_stock.php?msg=$msg"); }else echo "<br><font color=red size=+1 >Problem in Adding !</font>" ; } } } if(isset($_GET['msg'])){ $data=$_GET['msg']; $msg='<p style=color:#153450;font-family:gfont-family:Georgia, Times New Roman, Times, serif>'.$data.'</p>';// ?> <script src="dist/js/jquery.ui.draggable.js"></script> <script src="dist/js/jquery.alerts.js"></script> <script src="dist/js/jquery.js"></script> <link rel="stylesheet" href="dist/js/jquery.alerts.css" > <script type="text/javascript"> jAlert('<?php echo $msg; ?>', 'NIC'); </script> <?php } ?> <form name="form1" method="post" id="form1" action=""> <table class="form" border="0" cellspacing="0" cellpadding="0"> <tr> <?php $max = $db->maxOfAll("id", "stock_details"); $max=$max+1; $autoid="SD".$max.""; ?> <td><span class="man">*</span>Stock ID:</td> <td><input name="stockid" type="text" id="stockid" readonly maxlength="200" class="round default-width-input" value="<?php echo $autoid; ?>" /></td> <td><span class="man">*</span>Name:</td> <td><input name="name"placeholder="ENTER CATEGORY NAME" type="text" id="name" maxlength="200" class="round default-width-input" value="<?php echo $name; ?>" /></td> </tr> <tr> <td><span class="man">*</span>Cost:</td> <td><input name="cost" placeholder="ENTER COST PRICE" type="text" id="cost" maxlength="200" class="round default-width-input" onkeypress="return numbersonly(event)" value="<?php echo $cost; ?>" /></td> <td><span class="man">*</span>Sell:</td> <td><input name="sell" placeholder="ENTER SELLING PRICE" type="text" id="sell" maxlength="200" class="round default-width-input" onkeypress="return numbersonly(event)" value="<?php echo $sell; ?>" /></td> </tr> <tr> <td>Supplier:</td> <td><input name="supplier" placeholder="ENTER SUPPLIER NAME" type="text" id="supplier" maxlength="200" class="round default-width-input" value="<?php echo $supplier; ?>" /></td> <td>Category:</td> <td><input name="category" placeholder="ENTER CATEGORY NAME" type="text" id="category" maxlength="200" class="round default-width-input" value="<?php echo $category; ?>" /></td> </tr> <tr> <td> </td> <td> </td> </tr> <tr> <td> </td> <td> <input class="button round blue image-right ic-add text-upper" type="submit" name="Submit" value="Add"> (Control + S) <td align="right"><input class="button round red text-upper" type="reset" name="Reset" value="Reset"> </td> </tr> </table> </form> </div> <!-- end content-module-main --> </div> <!-- end content-module --> </div> <!-- end full-width --> </div> <!-- end content --> <!-- FOOTER --> <div id="footer"> <p>Any Queries email to <a href="mailto:sridhar.NIC@gmail.com?subject=Stock%20Management%20System">sridhar.NIC@gmail.com</a>.</p> </div> <!-- end footer --> </body> </html> Hi, Basically I am going to give a short description to my problem with pseduo and comments (-->), there is too much to paste all my code he basically include(config.php) --> database connection include(global.php) --> class is instantiated here as $p ($p is GLOBAL) --> I print_r the $p value here, and it shows (debugging) switch() case x: include file.php; break; --> but when I try to access it or print_r it here (here being within the file.php), via the file that has been included above "include file.php", it does not see it. I have to re-declare the $p variable with the class, within the included file. any tips as how to solve this please; I dont see why it wouldnt see it, since all the file is that I am including is an HTML file with a few PHP lines, which checks if a user has permission: if(!$p->check()) redirect("index.php"); I don't understand why "if(isSet($_GET['sid'])) " works before it is declared in the variable name(" $name = $_GET['sid'];"). 1. How does php store the date in this get statement? 2. Is GET an array? Code: [Select] if(isSet($_GET['sid'])) { echo "<h2>Exercise</h2>"; $name = $_GET['sid']; $timein = time(); $quest=1; $nextquest=2; } else { echo "<h2>Enter Student Number:</h2>"; $quest=0; $nextquest=0; } Dear all, I am new to the forums, with a hope that somebody can point me in the right direction. I am coding a new photo website, and am doing it with PHP to maximize my flexibility. In essence I want to have a set of gallery folder on the server, and the site reads off these folders and automatically generates the required galleries. My PHP code is below, along with a detail of the exact problem: <?php $main = "Collections/"; # Location of galleries $big = "Large/"; # Location of big versions (subdir within each gallery) $i = 0; #Gallery Iterator #Searching for galleries & Checking only for directories (save them im $galleries array) $tempgalleries = scandir($main); foreach ($tempgalleries as $gallery_iterate) { if (!is_dir($gallery_iterate)) { $galleries[]=$gallery_iterate; } } #Iterating galleries. Collecting each gallery's images (saving in $GalleryImages.$i). This creates an image array for each $galleries[$i] for($i=0; $i<=sizeof($galleries)-1; $i++) { #Making the title nice (from the the directory names) $GalleryTitles[$i] = str_replace('_',' ', $galleries[$i]);; $temp_gallery = opendir($main.$galleries[$i]); #Checking for Images and storing in array if valid while (false !== ($image = readdir($temp_gallery))) { if ($image != "." && $image != ".." && $image != rtrim($big,"/") && strstr($image,'.jpg')) { ${$GalleryImages_.$i}[] = $image; } } #Sorting the images numerically natsort(${$GalleryImages_.$i}); closedir($temp_gallery); } #Better location for the buttons!! #Printing the galleries and all the html required for naming, separation, etc.. This is also an iteration for($i=0; $i<=sizeof($galleries)-1; $i++) { echo('<div class="galleries_hidden" id="gallery_'.$i.'"><hr><br><div class="Gallery_Title"><b><i><big>'.$GalleryTitles[$i].'</big></i></b></div><br>'); $folder=$galleries[$i]; foreach(${$GalleryImages_.$i} as $thumb_image) { echo '<a href="'.$main . $folder .'/'. $big . 'large_'. $thumb_image . '" rel="lightbox['.$folder.']" title="'.$folder.'"><img src="' . $main . $folder .'/'. $thumb_image. '" alt="'.$folder.'" class="Gallery_Image" /></a>'; } echo('</div>'); } #Making the buttons to cycle the galleries for($i=0; $i<sizeof($galleries); $i++) { echo('<input type="button" id="gallery_'.$i.'" value="Show '.$GalleryTitles[$i].'" onclick="showgallery(');echo("'gallery_".$i."');");echo('" /><br><br>'); } ?> I have managed to make each aspect work, exept one. The last portion, as commented: #Making the buttons to cycle the galleries for($i=0; $i<sizeof($galleries); $i++) { echo('<input type="button" id="gallery_'.$i.'" value="Show '.$GalleryTitles[$i].'" onclick="showgallery(');echo("'gallery_".$i."');");echo('" /><br><br>'); } This piece of code generates buttons which shows one gallery, and hides the rest. This is done by changing the classes of the divs from "galleries_visible" to "galleries_hidden", as applicable. This is done using a javascript declared in the header as follows: Code: [Select] <script type="text/javascript"> function showgallery(id) { var divall = document.getElementsByTagName("div"); var i=0; for (i=0;i<divall.length;i++) { if(divall[i].className == "galleries_visible") { divall[i].className = "galleries_hidden"; } var showdiv = document.getElementById(id); showdiv.className = "galleries_visible"; return false; } </script> When I have the button-generating php code below the gallery-generating php code, then the javascript seems to work, by showing and hiding respective galleries. These galleries and their litebox viewer all work normally. However, when putting the button-creator php above the gallery-generator php, then the buttons appear as normal, and the javascript runs, but it cannot find the div with the id it searches for: Code: [Select] var showdiv = document.getElementById(id); showdiv.className = "galleries_visible"; I am confused. The PHP code makes several arrays which stores all the file and folder information, and these arrays are read by the button-generator irrespective of its position (I know this because the buttons are generated based on the content of non-empty arrays). Why can't the javascript change the gallery-containing divs when they are below the button-containing div? Any help is greatly appreciated, I just cant seem to find whats wrong! Kind regards, Frederik Newb here trying to build a form that works with ints to count how many red shirts die in a classic episode of star trek (exercise to get better with forms and ints). I have an error which reads as '7 Error message: Undefined index: rsTot'. I have tried a few things and read that setting it(casting it?) as a float was the safest way to work with the int, however each thing i've attempted results in some sort of error so after a day of reading and trying i'm very confused and hoping for an answer I can understand here.
I have read through stackOverflow for an answer but not seen one which i can understand and apply that speaks to the problem i'm having of initially entering and process a number as an int which i can later do some math on.
error can be seen he http://zephir.seattlecentral.edu/~jstein11/itc250/z14/w03c0102_OOPform/w03c0102_OOPform.php
<?php //w03c0102_OOPform require '../inc_0700/config_inc.php'; #provides configuration, pathing, error handling, db credentials //END CONFIG AREA ---------------------------------------------------------- $rsTot = (float)$_POST['rsTot'];// float more forgiving int $rsSurvived = (float)$_POST['rsSurvived']; $rsSum = $rsTot - $rsSurvived; $rsRatio = 0; # Read the value of 'action' whether it is passed via $_POST or $_GET with $_REQUEST if(isset($_REQUEST['act'])){$myAction = (trim($_REQUEST['act']));}else{$myAction = "";} switch ($myAction) {//check 'act' for type of process case "display": # 2)Display user's name! showName(); break; default: # 1)Ask user to enter their name showForm(); } function showForm() {# shows form so user can enter their name. Initial scenario get_header(); #defaults to header_inc.php ?> <script type="text/javascript" src="<?=VIRTUAL_PATH;?>include/util.js"></script> <script type="text/javascript"> function checkForm(thisForm) {//check form data for valid info if(empty(thisForm.YourName,"Field Empty, please fill out")){return false;} return true;//if all is passed, submit! } </script> <p align="center"><?=smartTitle();?></p> <h3 align="center">Star Trek Classic</h3> <h2 align="center">Death-Shirt Calculator</h2> <form action="<?=THIS_PAGE;?>" method="post" onsubmit="return checkForm(this);"> <p align="center">Classic Star Trek Episode Name<br /> <input type="text" name="epName" /><br /><br /> Esitmated number of officers with red shirts<br /> <input type="text" name="rsTot" /><br /><br /> Esitmated number of officers with red shirts<br /> to actually survive the episode<br /> <input type="int" name="rsSurvived" /><br /><br /> <input type="submit" value="Go!"> </p> <input type="hidden" name="act" value="display" /> </form> <?php get_footer(); #defaults to footer_inc.php } function showName() {#form submits here we show entered name get_header(); #defaults to footer_inc.php if(!isset($_POST['epName']) || $_POST['epName'] == '') {//data must be sent feedback("No form data submitted"); #will feedback to submitting page via session variable myRedirect(THIS_PAGE); } if(!ctype_alnum($_POST['epName'])) {//data must be alphanumeric only feedback("Only letters and numbers are allowed. Please re-enter your name."); #will feedback to submitting page via session variable myRedirect(THIS_PAGE); } $epSubmitted = strip_tags($_POST['epName']);# strip data entered echo '<h3 align="center">' . smartTitle() . '</h3>'; echo '<p align="center">Episode Name: <b>' . $epSubmitted . '</b><br />'; echo '<p align="center">Total Red Shirts Appearing: <b>' . $rsTot . '<br />'; echo 'Red Shirts Still Breathing at End of Episode: <b>' . $rsSurvived . '<br />'; echo 'Red Shirt Episode Survival Ratio: <b>' . $rsRatio . '</b>!</p>'; echo '<p align="center"><a href="' . THIS_PAGE . '">RESET</a></p>'; get_footer(); #defaults to footer_inc.php } ?> Edited by Chezshire, 25 May 2014 - 08:10 AM. Hello All,
I have designed a small php module Which has more than 80 .php files. I want to give the access level for all those files through a global access.php file. But i am not getting how it can be developed. I made a table in database which has all the scripts name. When those are checked value 1 it has to be visible for those users who come under a perticular position like MD, CEO, Sales Manager etc. Here is my table structure
script.JPG 20.61KB
0 downloads
and i tried doing like this
if($_SESSION['pos']=='admin') { echo "<h1> SORRY YOU DONT HAVE ACCESS </h1>"; } else { // file contents... } functions.php source -> http://smileybb.com/paste/99 <- [Password: freak] Error: Fatal error: Cannot redeclare log() in /home/smileybb/public_html/style/inc/functions.php on line 62 functions.php is only called one time to check for errors since I tend to write the backend before the frontend. Any chance you guys could give me some help? Here's my second go at this since the pros in here seem to have given up on the standard methods. On a WordPress site running PHP 5.0.3 (or something like that) I have multiple checkboxes that return an array of values depending on which ones are checked. In the source code the checkboxes load up this way--- I will include the OUTPUT source code seen in the browser for two different multiple checkboxes -- one named "cp_checkbox_help" and the next named "cp_checkbox_charley" <div id="checkboxes"><table width="100%" border="0" cellspacing="0" cellpadding="5"> <tr> <th colspan="2" scope="col">help checkbox</th> </tr> <tr> <td width="4%"><input style="display:inline-block; float:left;" type="checkbox" name="cp_checkbox_help[]" class="checkbox" id="" value="Sunday" checked="yes"/></td> <td width="96%"style="vertical-align:top; text-indent: 7px; text-align: left;" >Sunday</td> </tr> <tr> <td width="4%"><input style="display:inline-block; float:left;" type="checkbox" name="cp_checkbox_help[]" class="checkbox" id="" value=" Monday" checked="yes"/></td> <td width="96%"style="vertical-align:top; text-indent: 7px; text-align: left;" > Monday</td> </tr> <tr> <td width="4%"><input style="display:inline-block; float:left;" type="checkbox" name="cp_checkbox_help[]" class="checkbox" id="" value=" Tuesday" checked="yes"/></td> <td width="96%"style="vertical-align:top; text-indent: 7px; text-align: left;" > Tuesday</td> </tr> <tr> <td width="4%"><input style="display:inline-block; float:left;" type="checkbox" name="cp_checkbox_help[]" class="checkbox" id="" value=" Wednesday" /></td> <td width="96%"style="vertical-align:top; text-indent: 7px; text-align: left;" > Wednesday</td> </tr> <tr> <td width="4%"><input style="display:inline-block; float:left;" type="checkbox" name="cp_checkbox_help[]" class="checkbox" id="" value=" Thursday" /></td> <td width="96%"style="vertical-align:top; text-indent: 7px; text-align: left;" > Thursday</td> </tr> <tr> <td width="4%"><input style="display:inline-block; float:left;" type="checkbox" name="cp_checkbox_help[]" class="checkbox" id="" value=" Friday" /></td> <td width="96%"style="vertical-align:top; text-indent: 7px; text-align: left;" > Friday</td> </tr> <tr> <td width="4%"><input style="display:inline-block; float:left;" type="checkbox" name="cp_checkbox_help[]" class="checkbox" id="" value=" Saturday" /></td> <td width="96%"style="vertical-align:top; text-indent: 7px; text-align: left;" > Saturday</td> </tr> </tr> </table></div><div class="clr"></div> <div id="checkboxes"><table width="100%" border="0" cellspacing="0" cellpadding="5"> <tr> <th colspan="2" scope="col">Staff Provided</th> </tr> <tr> <td width="4%"><input style="display:inline-block; float:left;" type="checkbox" name="cp_checkbox_charley[]" class="checkbox" id="" value="Cook" checked="yes"/></td> <td width="96%"style="vertical-align:top; text-indent: 7px; text-align: left;" >Cook</td> </tr> <tr> <td width="4%"><input style="display:inline-block; float:left;" type="checkbox" name="cp_checkbox_charley[]" class="checkbox" id="" value=" Housekeeper / Maid" checked="yes"/></td> <td width="96%"style="vertical-align:top; text-indent: 7px; text-align: left;" > Housekeeper / Maid</td> </tr> <tr> <td width="4%"><input style="display:inline-block; float:left;" type="checkbox" name="cp_checkbox_charley[]" class="checkbox" id="" value=" Gardener" checked="yes"/></td> <td width="96%"style="vertical-align:top; text-indent: 7px; text-align: left;" > Gardener</td> </tr> <tr> <td width="4%"><input style="display:inline-block; float:left;" type="checkbox" name="cp_checkbox_charley[]" class="checkbox" id="" value=" Watchman" checked="yes"/></td> <td width="96%"style="vertical-align:top; text-indent: 7px; text-align: left;" > Watchman</td> </tr> </tr> </table></div><div class="clr"></div> This code is on an EDIT page that allows a user identified by their post_id to just edit the Classified Ad they "own" and created. They are not given access to the WordPress Dashboard--just to this Edit function page. Here they can click on a list of their own ads and change things. As long as they select or unselect individual checkboxes within "cp_checkbox_help" or "cp_checkbox_charley" or "cp_checkbox_hello" and Submit the form the page returns with the new checked values showing correctly. HOWEVER, if they UNSELECT ALL associated checkboxes in one or both or all three of these multiple checkboxes when the ad is updated the former values return for checkboxes. The previous saved array does not get overwritten. I need help in modifying this code so that it detects the change if all checkboxes within a specific name are UNSELECTED and THEN overwrites that darned array! As my code shows-- JUST for the multiple checkbox arrays I IMPLODE and put a comma between each value and it is saved that way. Each array will have a different number of values inside and so I cannot just stick an UNSET in front of it. Finally, I need to confine the overwriting of the $meta_value array to JUST the $meta_key identified as 'cp_checkbox_charley'...otherwise in some tests of different way to write this I get the $meta_value wiped out for everything. And I must find a way to EXCLUDE these checkbox arrays so that the OTHER custom fields that start with "cp_" have their $meta_value's retained and updated either before or after running through the checkboxes. // update the ad and return the ad id $post_id = wp_update_post($update_ad); if($post_id) { // now update all the custom fields foreach($_POST as $meta_key => $meta_value) { if (cp_str_starts_with($meta_key, 'cp_')) if (cp_str_starts_with($meta_key, 'cp_checkbox_charley') && is_array($_POST['cp_checkbox_help'])) $meta_value= implode(',', $_POST['cp_checkbox_charley']); else if (cp_str_starts_with($meta_key, 'cp_checkbox_charley') && is_null($_POST['cp_checkbox_help']))$meta_value= NULL ; if (cp_str_starts_with($meta_key, 'cp_checkbox_help')) $meta_value = implode(',', $_POST['cp_checkbox_help']); if (cp_str_starts_with($meta_key, 'cp_checkbox_hello')) $meta_value= implode(',', $_POST['cp_checkbox_hello']); //echo $meta_key . ' <--metakey <br/>' . $meta_value . ' <--metavalue<br/><br/>'; // for debugging update_post_meta($post_id, $meta_key, $meta_value); } $errmsg = '<div class="box-yellow"><b>' . __('Your ad has been successfully updated.','cp') . '</b> <a href="' . CP_DASHBOARD_URL . '">' . __('Return to my dashboard','cp') . '</a></div>'; } else { // the ad wasn't updated so throw an error $errmsg = '<div class="box-red"><b>' . __('There was an error trying to update your ad.','cp') . '</b></div>'; } return $errmsg; } I know SOME PHP GENIUS has got a great solution! I had a problem with my code, the result shows 'Fatal error: Cannot redeclare create_form_input() (previously declared in ....\form_functions.inc.php:9) in ....\includes\form_functions.inc.php on line 32 I need to make registration forms and I already defined a function for creating this inputs.. here's the code Code: [Select] <?php function create_form_input($name, $type, $errors) { $value = false; if (isset($_POST[$name])) $value = $_POST[$name]; if ($value && get_magic_quotes_gpc( )) $value = stripslashes($value); if ( ($type == 'text') || ($type == 'password') ) { echo '<input type="' . $type . '" name="' . $name . '" id="' . $name . '"'; if ($value) echo ' value="' . htmlspecialchars($value) . '"'; if (array_key_exists($name, $errors)) { echo 'class="error" /> <span class="error">' . $errors[$name] .'</span>'; } else { echo ' />'; } } elseif ($type == 'textarea') { if (array_key_exists($name, $errors)) echo ' <span class="error">' .$errors[$name] . '</span>'; echo '<textarea name="' . $name . '" id="' . $name . '" rows="5" cols="75"'; if (array_key_exists($name, $errors)) { echo ' class="error">'; } else { echo '>'; } if ($value) echo $value; echo '</textarea>'; } // End of primary IF-ELSE. } // End of function And here is the form registration. Code: [Select] <?php require ('./includes/form_functions.inc.php'); ?> <form action="register.php" method="post" accept-charset="utf-8" style="padding-left:100px"> <p><label for="first_name"><strong>First Name</strong></label> <br /><?php create_form_input('first_name', 'text', $reg_errors); ?></p> <p><label for="last_name"><strong>Last Name</strong></label><br /><?php create_form_input('last_name', 'text', $reg_errors); ?></p> <p><label for="username"><strong>Desired Username</strong></label><br /> <?php create_form_input('username', 'text', $reg_errors); ?> <small>Only letters and numbers are allowed.</small></p> <p><label for="email"><strong>Email Address</strong></label> <br /><?php create_form_input('email', 'text', $reg_errors); ?></p> <p><label for="pass1"><strong>Password</strong></label><br /> <?php create_form_input('pass1', 'password', $reg_errors); ?> <small>Must be between 6 and 20 characters long, with at least one lowercase letter, one uppercase letter, and one number.</small></p> <p><label for="pass2"><strong>Confirm Password</strong> </label><br /><?php create_form_input('pass2', 'password', $reg_errors); ?></p> <input type="submit" name="submit_button" value="Next →" id="submit_button" class="formbutton" /> </form> Thanks before I'm not seeing what is causing this: (Fatal error: Cannot redeclare shopdisplay() (previously declared in /home/katarra/public_html/shops.php:11)in /home/katarra/public_html/shops.php on line 21) error... Any help would be appreciated! (This probably isn't the only error, but it's the one that's stopping me from finding the others) Thanks! <?php error_reporting(E_ALL); ini_set('display_errors', TRUE); ini_set('display_startup_errors', TRUE); require_once('dk_lib.php'); require_once('scripts/dbfunc.s'); include ("debug.php"); include("lib.php"); $player = check_user($secret_key, $db); function shopdisplay($content, $title) { // Finalize page and output to browser. $template = gettemplate("shops"); $finalarray = array( "title"=>$title, "content"=>$content); $page = parsetemplate($template, $finalarray); echo $page; die(); } if (isset($_GET["do"])) { $do = explode(":",$_GET["do"]); if ($do[0] == "buy") { include('shops.php'); buy(); } elseif ($do[0] == "buy2") { include('shops.php'); buy2($do[1]); } elseif ($do[0] == "buy3") { include('shops.php'); buy3($do[1]); } elseif ($do[0] == "sell") { include('shops.php'); sell(); } } else { donothing(); } function donothing() { $page = "Welcome to my shop. What do you want?"; shopdisplay($page, "Shop Home"); } function buy() { // Displays a list of available items for purchase. global $numqueries; $query1 = doquery("SELECT * FROM levels", "levels") or trigger_error("Query failed: ". mysql_error()); $location = mysql_fetch_array($query1); $townquery = doquery("SELECT name,itemslist FROM shop WHERE location=$location", "shop") or trigger_error("Query failed: ". mysql_error()); if (mysql_num_rows($townquery) != 1) { shopdisplay("Cheat attempt detected.<br /><br />Get a life, loser.", "Error"); } $townrow = mysql_fetch_array($townquery); $itemslist = explode(",",$townrow["itemslist"]); $querystring = ""; foreach($itemslist as $a=>$b) { $querystring .= "id='$b' OR "; } $querystring = rtrim($querystring, " OR "); $itemsquery = doquery("SELECT * FROM items WHERE $querystring ORDER BY id", "items"); $page = "Buying weapons will increase your Attack Power. Buying armor and shields will increase your Defense Power.<br /><br />Click an item name to purchase it.<br /><br />The following items are available at this shop:<br /><br />\n"; $page .= "<table width=\"80%\">\n"; while ($itemsrow = mysql_fetch_array($itemsquery)) { if ($itemsrow["type"] == 'weapon') { $attr = "Attack Power:"; } else { $attr = "Defense Power:"; } $page .= "<tr><td width=\"4%\">"; /* if ($userrow["weaponid"] == $itemsrow["id"] || $userrow["armorid"] == $itemsrow["id"] || $userrow["shieldid"] == $itemsrow["id"]) { $page .= "<td width=\"32%\"><span class=\"light\">".$itemsrow["name"]."</span></td><td width=\"32%\"><span class=\"light\">$attrib ".$itemsrow["attribute"]."</span></td><td width=\"32%\"><span class=\"light\">Already purchased</span></td></tr>\n"; } else } */ $page .= "<td width=\"32%\"><b><a href=\"shops.php?do=buy2:".$itemsrow["id"]."\">".$itemsrow["name"]."</a>$</b></td><td width=\"32%\">$attr <b>".$itemsrow["attr"]."</b></td><td width=\"32%\">Price: <b>".$itemsrow["price"]." gold</b></td></tr>\n"; } $page .= "</table><br />\n"; $title = "Buy Items"; shopdisplay($page, $title); } function buy2($id) { // Confirm user's intent to purchase item. global $userrow, $numqueries; $query1 = doquery("SELECT * FROM levels", "levels"); $location = mysql_fetch_array($query1); $townquery = doquery("SELECT name,itemslist FROM shop WHERE location=$location", "shop") or trigger_error("Query failed: ". mysql_error()); if (mysql_num_rows($townquery) != 1) { shopdisplay("Cheat attempt detected.<br /><br />Get a life, loser.", "Error"); } $townrow = mysql_fetch_array($townquery); $townitems = explode(",",$townrow["itemslist"]); if (! in_array($id, $townitems)) { shopdisplay("Cheat attempt detected.<br /><br />Get a life, loser.", "Error"); } $itemsquery = doquery("SELECT * FROM items WHERE id='$id'", "items") or trigger_error("Query failed: ". mysql_error()); $itemsrow = mysql_fetch_array($itemsquery); if ($player["gold"] < $itemsrow["price"]) { shopdisplay("You do not have enough gold to buy this item!", "Buy Items"); die(); } if ($itemsrow["type"] == 'weapon') { $page = "You are buying the ".$itemsrow["name"].", is that ok?<br /><br /><form action=\"shops.php?do=buy3:$id\" method=\"post\"><input type=\"submit\" name=\"submit\" value=\"Yes\" /> <input type=\"submit\" name=\"cancel\" value=\"No\" /></form>"; } elseif ($itemsrow["type"] == 'armor') { $page = "You are buying the ".$itemsrow["name"].", is that ok?<br /><br /><form action=\"shops.php?do=buy3:$id\" method=\"post\"><input type=\"submit\" name=\"submit\" value=\"Yes\" /> <input type=\"submit\" name=\"cancel\" value=\"No\" /></form>"; } elseif ($itemsrow["type"] == 'item') { $page = "You are buying the ".$itemsrow["name"].", is that ok?<br /><br /><form action=\"shops.php?do=buy3:$id\" method=\"post\"><input type=\"submit\" name=\"submit\" value=\"Yes\" /> <input type=\"submit\" name=\"cancel\" value=\"No\" /></form>"; } elseif ($itemsrow["type"] == 'pet') { $page = "You are buying the ".$itemsrow["name"].", is that ok?<br /><br /><form action=\"shops.php?do=buy3:$id\" method=\"post\"><input type=\"submit\" name=\"submit\" value=\"Yes\" /> <input type=\"submit\" name=\"cancel\" value=\"No\" /></form>"; } $title = "Buy Items"; shopdisplay($page, $title); } function buy3($id) { // Update user profile with new item & stats. if (isset($_POST["cancel"])) { header("Location: shops.php"); die(); } global $userrow; $query1 = doquery("SELECT * FROM levels", "levels"); $location = mysql_fetch_array($query1); $townquery = doquery("SELECT name,itemslist FROM shop WHERE location=$location", "shop") or trigger_error("Query failed: ". mysql_error()); if (mysql_num_rows($townquery) != 1) { shopdisplay("Cheat attempt detected.<br /><br />Get a life, loser.", "Error"); } $townrow = mysql_fetch_array($townquery); $townitems = explode(",",$townrow["itemslist"]); if (! in_array($id, $townitems)) { shopdisplay("Cheat attempt detected.<br /><br />Get a life, loser.", "Error"); } $itemsquery = doquery("SELECT * FROM items WHERE id='$id'", "items") or trigger_error("Query failed: ". mysql_error()); $itemsrow = mysql_fetch_array($itemsquery); if ($player["gold"] < $itemsrow["price"]) { shopdisplay("You do not have enough gold to buy this item!", "Buy Items"); die(); } $query = mysql_select("select `id`, `name`, `price`, `type`, `slot` from `items` where `id`=?", array($_GET['id'])) or trigger_error("Query failed: ". mysql_error()); $item = $query->fetchrow(); $q1 = mysql_select("select * from `inventory` where `player`=? and item_id=?", array($player->id,$item['id'])) or trigger_error("Query failed: ". mysql_error()); if($q1->recordcount() == 0) { $insert['player'] = $player->id; $insert['quantity'] = '0'; $insert['status'] = 'unequipped'; $insert['item_id'] = $item['id']; $insert['type'] = $item['type']; $insert['slot'] = $item['slot']; $query2 = $db->autoexecute('inventory', $insert, 'INSERT') or trigger_error("Query failed: ". mysql_error()); } $query1 = mysql_select("update `users` set `gold`=? where `id`=?", array($player->gold - $item['price'], $player->id)) or trigger_error("Query failed: ". mysql_error()); $insert['player'] = $player->id; $insert['item_id'] = $item['id']; $q = mysql_select("select * from `inventory` where `player`='".$insert['player']."' and `item_id`='".$item['id']."'") or trigger_error("Query failed: ". mysql_error()); $row = $q->fetchrow(); $query = mysql_select("update `inventory` set `quantity`=? where `item_id`='".$item['id']."' and `player`='".$insert['player']."'", array($row['quantity'] + 1)) or trigger_error("Query failed: ". mysql_error()); if ($query && $query1) //If successful { $player = check_user($secret_key, $db); //Get new user stats echo "<b>Blacksmith:</b><br />\n"; if ($query2){echo "<strong>You purchased a " . ucwords($item['name']) . "!</strong><br />";} echo "<i>Thank you, enjoy your new <b>" . ucwords($item['name']) . "</b>!</i><br /><br />\n"; $q1 = mysql_select("select * from `inventory` where `item_id`='".$_GET['id']."' and `player`='".$insert['player']."'"); $row1 = $q1->fetchrow(); echo "<i>You now have " . $row1['quantity'] . " <b>" . $item['name'] . "(s)</b>!</i><br /><br />\n"; echo "<a href=\"main.php?username=$x&password=$y&doit=inventory\">Return to inventory</a>"; break; } else { //Error logging here } } function sell($id) { if (!$_GET['id']) //No item ID { echo "That item does not exist in your inventory!"; break; } //Select the item from the database $inventitemid = $_GET['id']; $query = mysql_select("select * from `inventory` where inventory.item_id='".$inventitemid."' and inventory.player=?", array($player->id)); //Either item doesn't exist, or item doesn't belong to user if($query->recordcount() == 0){ echo "Sorry, that item does not exist!"; break;} $query = mysql_select("select * from `items` where items.id=?", array($_GET['id'])); $query12 = $db->execute("SELECT `status`, `quantity` FROM `inventory` where inventory.item_id='".$inventitemid."' and inventory.player=?", array($player->id)); $row = $query12->fetchrow(); if($row['status'] == 'equipped') { echo "Unequip this item before trying to sell it!<br>"; echo "<a href=\"main.php?username=$x&password=$y&doit=inventory\">Return to inventory</a><br>"; exit;} //Either item doesn't exist, or item doesn't belong to user if ($query->recordcount() == 0) { echo "Sorry, that item does not exist!"; break; } $sell = $query->fetchrow(); //Get item info //Check to make sure clicking Sell wasn't an accident if (!$_POST['sure']) { echo "Are you sure you want to sell your <b>" . $sell['name'] . "</b> for <b>" . floor($sell['price']/2) . "</b> gold?<br /><br />\n"; echo "<form method=\"post\" action=\"shops.php?act=sell&id=" . $inventitemid . "\">\n"; echo "<input type=\"submit\" name=\"sure\" value=\"Yes, I am sure!\" />\n"; echo "</form>\n"; break; } if ($row['quantity']== 1) { $query = mysql_select("delete from `inventory` where `item_id`=? and `player`=?", array($inventitemid, $player->id)); } elseif($row['quantity'] > 1) { $query = mysql_select("UPDATE `inventory` SET `quantity`=? WHERE `item_id`=? and `player`=?",array($row['quantity'] - 1, $inventitemid, $player->id)); } $query = mysql_select("update `users` set `gold`=? where `id`=?", array($player->gold + floor($sell['price']/2), $player->id)); $player = check_user($secret_key, $db); //Get updated user info echo "You have sold your <b>" . $sell['name'] . "</b> for <b>" . floor($sell['price']/2) . "</b> gold.<br /><br />\n"; echo "<a href=\"main.php?username=$x&password=$y&doit=inventory\">Return to inventory</a>"; break; } ?> Hi guys, i have a little problem was wondering if anybody can help me out,.. i cant seem to understand why this keeps popping up Fatal error: Cannot redeclare CSQLAdmin::$functions in /home/chekweb1/public_html/propretymanagement/lib/sqladmin.php on line 31 Code: [Select] <?php class CSQLAdmin extends CLibrary { /** * description * * @var type * * @access type */ var $form; /** * description * * @var type * * @access type */ var $functions; /** * description functions list which will be executed in variouse points of sqladmin * * @var type * * @access type */ var $functions; function CSQLAdmin($section , $templates , $db , $tables , $extra = "") { global $_CONF; if (!$_GET["page"]) $_GET["page"] = 1; parent::CLibrary("SQLAdmin"); //checking if the templates are orblects or path to a template file if (!is_array($templates)) //if path the load the tempmate form that file $this->templates = array("generic_form" => new CTemplate($templates)); else $this->templates = $templates; $this->db = $db; $this->tables = $tables; //extra variables to be passed to cform $this->extra = $extra; //loading the forms , changed the varialbes locations, but still keeping the compatibility $path = ($_CONF["forms"]["adminpath"] ? $_CONF["forms"]["adminpath"] : $_CONF["formspath"] ); if (dirname($section)) { $path .= dirname($section) . "/" ; $section = basename($section); } //debuging part if (defined("PB_DEBUG") && (PB_DEBUG == "1")) echo "<br>FILE:SQLADMIN:MAIN:{$path}{$section}.xml"; $conf = new CConfig( $path . $section . ".xml"); $this->forms = $conf->vars["form"]; //loading the edit/add forms if (is_array($this->forms["forms"])) { foreach ($this->forms["forms"] as $key => $val) { unset($conf); //debuging part // if (defined("PB_DEBUG") && PB_DEBUG == "1") // echo "<br>FILE:SQLADMIN:SECTION:{$path}{$section}.xml"; $conf = new CConfig($path . $val ); $this->forms["forms"][$key] = $conf->vars["form"]; //adding the tables $this->forms["forms"][$key]["table"] = $this->forms["table"]; $this->forms["forms"][$key]["table_uid"] = $this->forms["table_uid"]; $this->forms["forms"][$key]["xmlfile"] = $path . $val ; } } $this->form = new CForm($this->templates["generic_form"], &$db , &$tables); } /** * description * * @param * * @return * * @access */ function FormList($items = "") { global $base; //checking if hte values weren't inputed ion the main object if (is_array($this->items)) { $items = $this->items; } //crap, preexecute a function, which is suposed in some times to preload the items too if (is_array($this->functions["list"]["pre"])) call_user_func($this->functions["list"]["pre"], &$items , &$items_count); //if i got no elements from preloader functions, then i load it manualy if (!is_array($items)) { //cheking if is a normal browse or a search method if (isset($this->forms["uridata"]["search"]) && ($_GET[$this->forms["uridata"]["action"]] == $this->forms["uridata"]["search"])) { $items = $this->db->QuerySelectLimit($this->tables[$this->forms["forms"]["list"]["table"]],"*", "`" . $_GET["what"] . "` " . ( $_GET["type"] == "int" ? "='" . $_GET["search"] . "'" : "LIKE '%" . $_GET["search"] . "%'"),(int) $_GET["page"],$this->forms["forms"]["list"]["items"]); $count = $this->db->RowCount($this->tables[$this->forms["forms"]["list"]["table"]] , " WHERE `" . $_GET["what"] . "` " . ( $_GET["type"] == "int" ? "='" . $_GET["search"] . "'" : "LIKE '%" . $_GET["search"] . "%'")); } else { $items = $this->db->QuerySelectLimit($this->tables[$this->forms["forms"]["list"]["table"]],"*","",(int) $_GET["page"],$this->forms["forms"]["list"]["items"]); $count = $this->db->RowCount($this->tables[$this->forms["forms"]["list"]["table"]]); } } $_GET["page"] = $_GET["page"] ? $_GET["page"] : 1; //auto index the element $start = $this->forms["forms"]["list"]["items"] * ($_GET["page"] - 1 ); if (is_array($items)) { foreach ($items as $key => $val) { $items[$key]["_count"] = ++$start; } } //$data = new CForm($this->templates["generic_form"], &$this->db , &$this->tables); return $this->form->SimpleList($this->forms["forms"]["list"] , $items , $count , $this->extra["list"]); } /** * description * * @param * * @return * * @access */ function SetFunction( $form , $event , $function) { $this->functions[$form][$event] = $function; } /** * description * * @param * * @return * * @access */ function ListProcess($pre = "" , $after = "" ) { $this->functions["list"]["pre"] = $pre; $this->functions["list"]["after"] = $after; } /** * description * * @param * * @return * * @access */ function StoreRecord($redirect = true) { global $base, $_CONF; //validating the input data if ($_SERVER["REQUEST_METHOD"] == "POST") { //doing a autodetect for storing type , edit or add //if $_GET["type"] is set is simple, else detecting after the id form if (!isset($_GET["type"])) { if ($_POST[$this->forms["table_uid"]]) $_GET["type"] = "edit"; else $_GET["type"] = "add"; } //if validation succeeds then i move the files from /tmp to their directory, else i will proceed to add //precheck for uploaded files, like temporary images, etc. $form = $this->forms["forms"][$_GET["type"]]; if (is_array($form["fields"])) { foreach ($form["fields"] as $key => $val) { switch ($val["type"]) { case "date": $_POST[$key] = mktime ( $_POST[$key . "_hour"] , $_POST[$key . "_minute"] , $_POST[$key . "_second"] , $_POST[$key. "_month"] , $_POST[$key. "_day"] , $_POST[$key. "_year"]); break; case "droplist": if ($val["subtype"] == "multiple") { //detect the fields which should be available for this field if (is_array($_POST)) { foreach ($_POST as $k => $v) { if (strstr($k , $key . "_option_")) { $option[] = $v; } } //ok, now build the result if (is_array($option)) { $_POST[$key] = implode($val["tree"]["db_separator"],$option); } else { $_POST[$key] = ""; } } else { } } break; case "upload": $file = true; case "image": unset($_POST[$key]); //checking how choosed the client to set the image switch ($_POST[$key . "_radio_type"]) { case 0: //checking if the client specified any image type if (is_array($_FILES[$key . "_upload_client"]) && is_uploaded_file($_FILES[$key . "_upload_client"]["tmp_name"])) { $img = &$_FILES[$key . "_upload_client"]; //temporary upload the file in images/upload/tmp/ $name = $_POST[$key . "_temp"] != "" ? $_POST[$key . "_temp"] : $val["file"]["default"] . time() . $val["file"]["ext"]; @move_uploaded_file($img["tmp_name"] , $_CONF["path"] . $_CONF["upload"] . "tmp/" . $name ); // generate the tn image if ($val["tn"]["generate"] == "true") { $base->image->Resize( $_CONF["path"] . $_CONF["upload"] . "tmp/" . $name , $_CONF["path"] . $_CONF["upload"] . "tmp/" . $val["tn"]["preffix"] . $name , $val["tn"]["width"] ); $_POST["tn_" . $key] = "1"; } //setting read/delete/save permission for all users, usefull if the httpd is working as normal user ( most cases ) chmod ($_CONF["path"] . $_CONF["upload"] . "tmp/" . $name , 0777); // die; //setting the temp variable $_fields["values"][$key . "_temp"] = $name; $_POST[$key . "_temp"] = $name; $_POST[$key . "_file"] = $_FILES[$key . "_upload_client"]["name"]; $_POST[$key] = "1"; } break; case "1": //, the guy wants to download a ing image if ($_POST[$key . "_upload_web"] != "http://") { //i have to be very carefully here, if the image is not a valid link, then //everithing get messed. $image = @GetFileContents($_POST[$key . "_upload_web"]); $name = $_POST[$key . "_temp"] != "" ? $_POST[$key . "_temp"] : $val["file"]["default"] . time() . $val["file"]["ext"]; SaveFileContents( $_CONF["path"] . $_CONF["upload"] . "tmp/" . $name , $image); chmod ($_CONF["path"] . $_CONF["upload"] . "tmp/" . $name , 0777); // generate the tn image if ($val["tn"]["generate"] == "true") { @$base->image->Resize( $_CONF["path"] . $_CONF["upload"] . "tmp/" . $name , $_CONF["path"] . $_CONF["upload"] . "tmp/" . $val["tn"]["preffix"] . $name , $val["tn"]["width"] ); $_POST["tn_" . $key] = "1"; } //setting the temp variable $_fields["values"][$key . "_temp"] = $name; $_POST[$key . "_temp"] = $name; $_POST[$key . "_file"] = basename($_POST[$key . "_upload_web"]); $_POST[$key] = "1"; } break; case "-1": // echo "<pre style=\"background-color:white\">"; // print_r($_POST); // die; //trying to remove the tmp image is exists if (file_exists($_CONF["path"] . $_CONF["upload"] . "tmp/" . $_POST[$key . "_temp"]) && is_file($_CONF["path"] . $_CONF["upload"] . "tmp/" . $_POST[$key . "_temp"])) @unlink($_CONF["path"] . $_CONF["upload"] . "tmp/" . $_POST[$key . "_temp"]); //removing the original image too if exists else @unlink($_CONF["path"] . $_CONF["upload"] . $val["path"] . $val["file"]["default"] . $_POST[$val["file"]["field"]] . $val["file"]["ext"]); $_fields["values"][$key . "_radio_type"] = 0; $_POST[$key] = 0; $_fields["values"][$key . "_temp"] = ""; $_POST[$key . "_temp"] = ""; $_POST[$key . "_file"] = ""; break; } //hm ... checking if that IS A REAL IMAGE if ($_POST[$key . "_temp"] && !$file) { $img = @GetImageSize($_CONF["path"] . $_CONF["upload"] . "tmp/" . $_POST[$key . "_temp"]); if (!is_array($img)) { //removing the image, maybe in future return the er a proper answer //echo "MOHHHHH"; @unlink($_CONF["path"] . $_CONF["upload"] . "tmp/" . $_POST[$key . "_temp"]); $_POST[$key . "_temp"] = ""; $_POST[$key] = 0; } } break; } } } //force for no validation sometimes if ($_GET["FORMvalidate"] == "false") $fields = ""; else $fields = $this->form->Validate($this->forms["forms"][$_GET["type"]] , $_POST); if (!is_array($fields)) { //adding to database if (!$_POST[$this->forms["forms"]["add"]["table_uid"]]) { $id = $this->db->QueryInsert($this->tables[$this->forms["forms"]["add"]["table"]] , $_POST); $_POST[$this->forms["forms"]["add"]["table_uid"]] = $id; } else { $this->db->QueryUpdate($this->tables[$this->forms["forms"]["edit"]["table"]] , $_POST , "`" . $this->forms["forms"]["edit"]["table_uid"] . "`='" . $_POST[$this->forms["forms"]["edit"]["table_uid"]] . "'" ); $id = $_POST[$this->forms["forms"]["edit"]["table_uid"]]; } //data stored, taking care of uploade files/images, etc if (is_array($form["fields"])) { foreach ($form["fields"] as $key => $val) { switch ($val["type"]) { case "upload": case "image": //checking if is really e file, else if no tmp is set then it can be the folder where are stored the values if (is_file($_CONF["path"] . $_CONF["upload"] . "tmp/" . $_POST[$key . "_temp"])) { //moving the image stored in temp variable //check if the file already exists if (is_file($_CONF["path"] . $_CONF["upload"] . $val["path"] . $val["file"]["default"] . $_POST[$val["file"]["field"]] . $val["file"]["ext"])) { @unlink($_CONF["path"] . $_CONF["upload"] . $val["path"] . $val["file"]["default"] . $_POST[$val["file"]["field"]] . $val["file"]["ext"]); } @rename( $_CONF["path"] . $_CONF["upload"] . "tmp/" . $_POST[$key . "_temp"] , $_CONF["path"] . $_CONF["upload"] . $val["path"] . $val["file"]["default"] . $_POST[$val["file"]["field"]] . $val["file"]["ext"] ); // generate the tn image if ($val["tn"]["generate"] == "true") { @rename( $_CONF["path"] . $_CONF["upload"] . "tmp/" . $val["tn"]["preffix"] . $_POST[$key . "_temp"] , $_CONF["path"] . $_CONF["upload"] . $val["path"] . $val["tn"]["preffix"] . $val["file"]["default"] . $_POST[$val["file"]["field"]] . $val["file"]["ext"] ); } //setting the image as true $_POST[$key] = 1; //updateing the database $this->db->QueryUpdate($this->tables[$this->forms["forms"]["edit"]["table"]] , $_POST , "`" . $this->forms["forms"]["edit"]["table_uid"] . "`='" . $_POST[$this->forms["forms"]["edit"]["table_uid"]] . "'" ); } break; default: if (is_array($val["file"])) SaveFileContents($_CONF["path"] . $_CONF["upload"] . $val["file"]["path"] . $val["file"]["default"] . $_POST[$val["file"]["field"]] . $val["file"]["ext"] , $_POST[$key] ); break; } } } if (!$_GET["type"]) { $_GET["type"] = $_POST[$this->forms["forms"]["table_uid"]] ? "edit" : "add"; } $this->templates["generic_form"]->blocks["Temp"]->input = $this->forms["forms"][$_GET["type"]]["redirect"]; //replacing the values //die($this->templates["generic_form"]->blocks["Temp"]->Replace($_POST)); if ($_GET["returnURL"]) { header("Location:" . urldecode($_GET["returnURL"])); exit; } if ($redirect == true) { header("Location: " . CryptLink($this->templates["generic_form"]->blocks["Temp"]->Replace(array_merge($_GET,$_POST)))); exit; } else { return true; } } } else { die("ARGH!!!"); //redirecting to list page header("Location:" . str_replace("&action=store" , "" , $_SERVER["REQUEST_URI"])); exit; } if (is_array($_fields["values"])) $fields["values"] = array_merge($fields["values"], $_fields["values"]); return $this->form->Show($this->forms["forms"][$_GET["type"]] , $fields); } /** * description * * @param * * @return * * @access */ function RestoreURI($section) { if (is_array($_GET)) { foreach ($_GET as $key => $val) { $out[$key] = $key . "=" . $val; } $out[$this->forms["uridata"]["action"]] = $this->forms["uridata"]["action"] . "=" . $this->forms["uridata"][$section]; unset($out[$this->forms["table_uid"]]); return CryptLink($_SERVER["SCRIPT_NAME"] . "?" . implode("&" , $out)); //return $_ } } /** * description * * @param * * @return * * @access */ function DoEvents($section = "" , $extra = "" , $values = "") { global $base , $_CONF; if (is_array($extra)) { $this->extra = array_merge($this->extra , $extra); } switch ($_GET[$this->forms["uridata"]["action"]]) { case $this->forms["uridata"]["delete"]: if (($_GET["rconfirm"] == "true")&&($_GET["confirmed"] != "true")) { return $this->templates["generic_form"]->blocks["DeleteItem"]->Replace(array( "title" => $_GET["title"] ? urldecode($_GET["title"]) : "Delete Item", "description" => $_GET["description"] ? urldecode($_GET["description"]) : "Are you sure you want to delete this record?", "return" => urldecode($_GET["returnURL"]), "cancel_location" => urldecode($_GET["returnURL"]), "delete_location" => $_SERVER["REQUEST_URI"] . "&confirmed=true" )); } //searching for element $data = $this->db->QFetchArray("SELECT * FROM `" . $this->tables[$this->forms["forms"]["edit"]["table"]] . "` WHERE `" . $this->forms["forms"]["edit"]["table_uid"] . "`='" . $_GET[$this->forms["forms"]["edit"]["table_uid"]] . "'" ); //checking if this is a valid data if (is_array($data)) { $this->db->Query("DELETE FROM `" . $this->tables[$this->forms["forms"]["edit"]["table"]] . "` WHERE `" . $this->forms["forms"]["edit"]["table_uid"] . "`='" . $_GET[$this->forms["forms"]["edit"]["table_uid"]] . "'" ); } if ($_GET["returnURL"]) { header("Location: " . CryptLink(urldecode($_GET["returnURL"]))); exit; } else { header("Location:" . $_SERVER["HTTP_REFERER"]/*$this->RestoreURI("list")*/); exit; } break; case $this->forms["uridata"]["store"]: return $this->StoreRecord(); break; case $this->forms["uridata"]["add"]: $fields["values"] = $values; return $this->form->Show($this->forms["forms"]["add"] , $fields , $this->extra["add"]); break; case $this->forms["uridata"]["edit"]: //searching for element $data = $values["edit"] ? $values["edit"] : $this->db->QFetchArray("SELECT * FROM `" . $this->tables[$this->forms["forms"]["edit"]["table"]] . "` WHERE `" . $this->forms["forms"]["edit"]["table_uid"] . "`='" . $_GET[$this->forms["forms"]["edit"]["table_uid"]] . "'" ); //checking if this is a valid data if (is_array($data)) { $fields["values"] = $data; return $this->form->Show($this->forms["forms"]["edit"] , $fields , $this->extra["edit"]); } header("Location:" . $this->RestoreURI("list")); exit; break; case $this->forms["uridata"]["details"]: //searching for element $data = $this->db->QFetchArray("SELECT * FROM `" . $this->tables[$this->forms["forms"]["edit"]["table"]] . "` WHERE `" . $this->forms["forms"]["edit"]["table_uid"] . "`='" . $_GET[$this->forms["forms"]["edit"]["table_uid"]] . "'" ); //checking if this is a valid data if (is_array($data)) { $fields["values"] = $data; return $this->form->Show($this->forms["forms"]["details"] , $fields, $this->extra["details"]); } header("Location:" . $this->RestoreURI("list")); exit; break; case $this->forms["uridata"]["search"]: case $this->forms["uridata"]["list"]: default: return $this->FormList($values["list"]); break; } } } ?> My website uses the Zend Framework. It also use openx to serve ads. Openx uses parts of the Zend Framework. I am getting this error. Cannot redeclare class Zend_Registry. require_once is used so I am wondering why this is happening at all. Any ideas on what I can try? I am moving servers and have a similar working set up on a existing server so I was surprised to see this breaking. Thanks, Brian I have 4 php files. 1. dbuser.php, declares class dbuser.php, no includes 2. dbobject.php, declares class dbobject.php, includes file 1. 3. casedetails.php, includes files 1 and 2 4. viewcase.php, includes files 1 and 3. When I try to run file 4, i get cannot redeclare class dbuser.php - error Even every require is followed by _once, but I still get "Cannot redeclare class dbuser"-error when running file 4. Full PHP-code below. I tried also putting "if(!class_exists('dbuser')) { ... " around class dbuser declaration but I still got the same error.. Is this a bug in PHP? I'm running version 5.x on apache 2 Thanks! 1. dbuser.php Code: [Select] <?PHP //$time = round(microtime(), 3); session_start(); require_once("settings.php"); //this is just simple array class dbuser { //Constructor function __construct($username=NULL, $password=NULL, $cookies=FALSE) { //Yhdistet��n tietokantaan ja k�ynnistet��n sessio require_once("dbconnect.php"); //Jos ei annettu parametrein� kayttajanimea ja salasanaa if (!isset($username) | !isset($password)) { //Jos salasana ja kayttaja tallennettu SESSION variableen if (isset($_SESSION['user']['email']) && $this->checkFingerprint($_SESSION['user']['fingerprint'])) { $this->logged = TRUE; foreach($_SESSION['user'] as $key => $value) { $this->$key=$value; } //Jos salasana ja kayttaja tallennettu kekseihin } elseif ( isset($_COOKIE['email']) && isset($_COOKIE['password']) ) { $this->logged = ($this->login($_COOKIE['email'], $_COOKIE['password'], FALSE, TRUE)); } //Jos annettu parametrein� knimi ja pwd } else { $this->logged = ($this->login($username, $password, $cookies, FALSE)); } //Costructor loppuu } //Kirjautuu sisaan, ottaa parametreina knimen ja pwd:n sek� tallennetaanko kekseihin, sa sen onko pwd kryptattu valmiiksi public function login($username, $password, $cookies=FALSE, $precrypted=FALSE) { global $settings; if ($precrypted) { $password = mysql_real_escape_string($password); } else { $password = sha1($password); } $username = mysql_real_escape_string($username); //MySQL query $time = time(); $loginQuery = "SELECT * FROM users WHERE email='$username' AND salasana='$password' AND aktiivinen='1' AND (vanhenee>'$time' OR vanhenee='')"; $fprint = $this->createFingerprint(); if($precrypted) { $loginQuery .= " AND fingerprint='$fprint'"; } $result = mysql_query($loginQuery) or trigger_error(mysql_error); $login = mysql_num_rows($result) or trigger_error(mysql_error()); if ($login != 1) { setcookie("email",'',-100000, "/"); setcookie("password",'',-100000, "/"); mysql_close(); session_destroy(); return FALSE; } else { $result = mysql_fetch_assoc($result); foreach ($result as $field => $value) { $this->$field=$value; $_SESSION['user'][$field] = $value; } $update = "UPDATE users SET kirjautunut='" . time() . "' WHERE id='" . $this->id . "'"; mysql_query($update) or trigger_error(mysql_error()); $update = "UPDATE users SET fingerprint='" . $fprint . "' WHERE id='" . $this->id . "'"; mysql_query($update) or trigger_error(mysql_error()); $this->kirjautunut=time(); $_SESSION['user']['kirjautunut'] = time(); if ($cookies) { setcookie("email",$username,($settings['REMEMBER_LOGIN_DURATION'] + time()), "/"); setcookie("password",$password,($settings['REMEMBER_LOGIN_DURATION'] + time()), "/"); } return TRUE; } } public function adduser($values) { if ($this->logged) { $insert = "INSERT INTO users ("; $vals = " VALUES("; $values['salasana'] = sha1($values['salasana']); foreach($values as $key => $value) { $insert .= mysql_real_escape_string($key) . ', '; $vals .= "'" . mysql_real_escape_string($value) . "', "; } $insert = substr($insert, 0, -2); $vals = substr($vals , 0, -2); $insert .= ')'; $vals .= ')'; $insert .= $vals; mysql_query($insert) or trigger_error(mysql_error()); return TRUE; } else { return FALSE; } } public function getusers($where=NULL, $order=NULL, $desc=NULL) { $query = "SELECT * FROM users"; if (isset($where)) { $query .= " WHERE "; foreach($where as $column => $value) { $query .= $column . " = '" . $value . "' AND "; } $query = substr($query, 0 ,-4); } if (isset($order)) { $query .= " ORDER BY " . $order . " "; } if (isset($desc)) { $query .= 'DESC'; } $values = mysql_query($query) or trigger_error(mysql_error()); $counter = 0; while ($row = mysql_fetch_assoc($values)) { foreach ($row as $key => $value) { $return[$counter][$key] = $value; } $counter++; } return $return; } public function update($id, $data) { $insert = "UPDATE users SET "; foreach($data as $key => $value) { $insert .= $key . '='; $insert .= "'" .$value . "', "; } $insert = substr($insert, 0, -2); $insert .= " WHERE id = '" . $id . "'" ; unset($data['id']); mysql_query($insert) or trigger_error(mysql_error()); } public function remove($id) { $rem = "DELETE FROM users WHERE id=$id LIMIT 1"; mysql_query($rem) or trigger_error(mysql_error()); } private function createFingerprint() { $print = "NJIARDL"; $print .= $_SERVER['HTTP_USER_AGENT']; $print .= $_SERVER['REMOTE_ADDR']; return md5($print); } private function checkFingerprint($real) { $print = $this->createFingerprint(); if ($real == $print) { return TRUE; } else { return FALSE; } } // Class dbuser loppuu } 2. dbobject.php Code: [Select] <?PHP //$time = round(microtime(), 3); require_once("dbuser.php"); .... lots of irrelevant code... class dbobject { .... ?> 3. Code: [Select] <?PHP require_once('../PHPcore/dbuser.php'); // this causes the error somehow... $user = new dbuser(); if(!$user->logged) { Header("Location:index.php"); } ... Lots of irrelevant code.. 4. I tried running this file when got the error... Code: [Select] <?PHP session_start(); require_once("PHPcore/dbuser.php"); $user = new dbuser(); if(!$user->logged) { Header("Location:index.php"); } require_once("views/casedetails.php"); Hi, I am working on a registration login system and after a person registers and logs in, they will get the option to upload a profile picture. The picture and registration info will need to be in two different tables. I want to know the best way to associate the two (registration info and photo) so that I know who's picture goes with what registration info? I thought about IP address, but a user might register on one computer and login and upload a photo on another computer. |