PHP - Recursive Function Not Working Correctly
Hey all!
I'm writing a simple script to scan a local directory named 'files' and all sub directories of 'files', adding each file to a database in the same table. To do this, I'm using scandir on the current working directory/files to start, and iterating over each file in a loop, but if the file is a directory, I append the directory name to the cwd/files and call scandir on that, creating a list of files in the subfolder, and then I call my addFiles() function recursively, with this as the argument. As of now, it just stops at the second call to addFiles. It adds all the top level files fine, stops there. That's where all my print_r() lines have gotten me. Here's my code... <!-- To change this template, choose Tools | Templates and open the template in the editor. --> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title></title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> </head> <body> <?php include 'DBConnect.php'; $db = new DBConnect() or die("Can't connect to DB"); $conn = $db->getConn(); mysql_select_db('download', $conn) or die("Can't select DB"); $dir = getcwd(); $dir = $dir . '\files' . "\\"; $fid = 1; $dir = addslashes($dir); $files = scandir($dir); echo $fid . " "; echo $dir; function addFiles($files) { global $dir; global $conn; global $fid; unset($files[0]); unset($files[1]); print_r($files); foreach ($files as $aFile) { if (is_file($dir.$aFile)) { echo "<li> $aFile </li>"; $query = "INSERT INTO files (file_id, file_path, file_name) values ($fid, '$dir', '$aFile')"; mysql_query($query, $conn) or die("Something wrong with query"); $fid = $fid + 1; } else if (is_dir($dir.$aFile)) { $fid = $fid + 1; $aDir = $dir . $aFile . "\\"; echo $dir; addFiles(scandir($dir.$aFile)); } } } addFiles($files); ?> </body> </html> Thanks in advance for any ideas. Also, if I'm approaching this problem completely wrong, let me know! I just came up with this and I feel like it should work... Similar TutorialsI'm trying to return to array of letters that bruteForce finally decides upon. However, I can't seem to pass the array to librarySolve. I'm feeling dumb, any help? Code: [Select] function librarySolve($string){ $temp = $this->bruteForce($string, FALSE, 0); return $temp; } function bruteForce($string, $state, $trys){ $base = $string; $state = $state; $new_letters = array(); if($trys <= 6000){ $this->new_letters = $this->generateRandomCipher(); $string = preg_replace('/[^a-zA-Z0-9-\s]/', '', $string); for($a=0;$a<=strlen($string);$a++){ $letter = substr($string, $a, 1); $pattern = "/[A-Z]/"; if(preg_match($pattern, $letter)!=0){ $new_letter = $this->new_letters[$letter]; } else if(preg_match($pattern, $letter)==0) { $new_letter = $letter; } $decipher .= $new_letter; } $word_array = explode(" ", $decipher); $count = 0; for($a=0;$a<count($word_array);$a++){ $do = $this->checkWord($word_array[$a]); if(!empty($do)){ $count++; } } if($count>=2){ $state = TRUE; } else { $state = FALSE; } if($state==TRUE){ return $this->new_letters; } else { $trys++; $this->bruteForce($base, $state, $trys); } } } Hello! Maybe I'm a bit ashamed to question some little kind of thing, but I tested 3 hours and couldn't let this function. It's like the most easiest possible recursiv function...: Code: [Select] function recursiv($s){ $s.="b"; if(strlen($s)>30){return $s;} //else return 0; else recursiv($s); } echo recursiv("h"); The result is a blank page... Thanks a lot for your help !! I have a function that searches first for a line in a file and then for a string in that line. If the string is not found, it concatenates the line with the next line and so on until it finds the string. The following script works but it is time consuming. I want to put a "break" somewhere so that if the line is found, the foreach will break. Can someone please help and tell me how to do this? If I put the break before the recursive call, it wont do the call. If I put it after, it wont get to the break. Thanks! function findEndTag($file, $line, $consolidatedLine) { $endTagFound = strstr($consolidatedLine,"/>"); if (!$endTagFound) { $fileContent = file($file); foreach ($fileContent as $i => $lineArray) { if ($lineArray == $line) { $consolidatedLine = $consolidatedLine." ".$fileContent[$i+1]; return (findEndTag($file, $fileContent[$i+1], $consolidatedLine)); } } } else { return $consolidatedLine; } } Hi there, I have written a recursive function that basically generates a tree structure for my site pages (kind of like a sitemap). It all worked fine until yesterday, I started getting error messages telling me that I have exhausted the amount of memory available. There are only about 30 pages in the site (parent, child, sub-child etc), so I dont think that I should be using up that much memory. This was my first attempt at a recursive function so I am pretty sure that it may not have been optimised properly. If anyone could take a look and offer any feed back that would be great. (written in codeigniter framework) function getAllPages() { $this->tmp_arr = array(); $this->buildPageStructure(0, 0); return $this->tmp_arr; } function buildPageStructure($parent_id, $counter) { $CI = & get_instance(); $query = $CI->db->query("SELECT page_id, title, page_url, status FROM pages WHERE parent_page='$parent_id' ORDER BY sort_order ASC"); $counter++; if($query->num_rows() > 0) { foreach($query->result() as $row) { $new_arr = new Page(); $new_arr->page_id = $row->page_id; $new_arr->title = $row->title; $new_arr->level = $counter; $new_arr->page_url = $row->page_url; $new_arr->status = $row->status; $this->tmp_arr[] = $new_arr; $this->buildPageStructure($row->page_id, $counter); } } } Cheers Jon Hey guys, I've got a problem. I need a function, that gives me a menue like that: parent_page1 page1 page2 page3 parent_page2 page1 page2 page3 So.. here is my database structu All what I need, is a function, that gives me a menu like that on top. Do you need some more information? Let me know.. Hi, I am using a separate class for all the functions. And using using the following function "objectToArray" to convert the JSON decoded object to Array. Class file: class xyz { . . . . . function objectToArray($d) { if (is_object($d)) { $d = get_object_vars($d); } if (is_array($d)) { return array_map(__FUNCTION__, $d); } else { return $d; } } . . . } Main page: $obj = new xyz(); $arr = $obj->objectToArray($json_obj); Because the function "objectToArray" is recursive, array_map(__FUNCTION__, $d) is not able to applies the callback. And throws the warning "array_map() expects parameter 1 to be a valid callback". Need help! Girish i have the below script but it doesn't work it just refreshes the page anyone know what is wrong Code: [Select] <?php $path = "../../gallery/gallery_files/gallery/"; if(isset($_POST['file']) && is_array($_POST['file'])) { foreach($_POST['file'] as $file) { $dirname = $path; //Recursive Delete Function function DELETE_RECURSIVE_DIRS($dirname) { // recursive function to delete // all subdirectories and contents: if(is_dir($dirname))$dir_handle=opendir($dirname); while($file=readdir($dir_handle)) { if($file!="." && $file!="..") { if(!is_dir($dirname."/".$file))unlink ($dirname."/".$file); else DELETE_RECURSIVE_DIRS($dirname."/".$file); } } closedir($dir_handle); rmdir($dirname); return true; } } } ?> Hi, I am trying to recursively build another array based on the one I get back from our CRM api. The array I get back looks like this: Code: [Select] [1] => stdClass Object ( [description] => Description Text [label] => Product [name] => Product [sobject] => KnowledgeArticleVersion [topCategories] => stdClass Object ( [childCategories] => Array ( [0] => stdClass Object ( [childCategories] => Array ( [0] => stdClass Object ( [childCategories] => Array ( [0] => stdClass Object ( [label] => Apple [name] => Apple ) [1] => stdClass Object ( [label] => Orange [name] => Orange ) [2] => stdClass Object ( [label] => lemon [name] => lemon ) ) [label] => Templates [name] => Templates ) [1] => stdClass Object ( [label] => Connector [name] => Connector ) [2] => stdClass Object ( [label] => AeroView [name] => AeroView ) ) [label] => AeroWare [name] => AeroWare ) [1] => stdClass Object ( [label] => BackOffice [name] => BackOffice ) [2] => stdClass Object ( [label] => OutWare [name] => OutWare ) [3] => stdClass Object ( [childCategories] => Array ( [0] => stdClass Object ( [label] => ERA [name] => ERA ) [1] => stdClass Object ( [label] => Kairos [name] => Kairos ) ) [label] => InWare [name] => InWare ) ) [label] => All [name] => All ) ) The child categories could be any level deep. I would like put it in an array something like this: Code: [Select] Array ( [label] => Cat 1 [level] => 0 [children] => Array ( [label] => Sub Cat 1 [level] => 1 [children] => Array ( [label] => Sub Sub Cat 1 [level] => 2 ) ) ) I have tried so many things but I just can't get it right. Any assistance would be greatly appreciated. Thanks Peter Hey there I just started out with PHP so it might be a trivial problem. I want to populate an array with values by a recursive function but i don't get it the way i want it to have. Target array (written in python syntax): myArray = { key : [ [a1, a2, a3, a4], [b1, b2, b3 ,b4] ], key2 : [ [c1, c2, c3, c4], [d1, d2, d3, d4] ] } So far i created a recursive function to collect all data i need for the array but i don't get the right syntax to achieve my target array. What i have so far is following code (snippet): function get_data($main_dir, $items=[], $myArray=[], $depth=0) { global $items; if ($myArray == NULL && depth == 0) { $myArray = array(); } $depth++; $dirHandle = opendir($main_dir); while ($file = readdir($dirHandle)){ if(is_dir($main_dir.$file) && $file != "." && $file != "..") { $new_dir = $main_dir.$file."/"; $items = get_data($new_dir, $items, $myArray, $depth); $myArray = $items[1] $items = $items[0] } else { splitted_dir = preg_split("/\//", $main_dir); key = splitted_dir[2]; file_information = read_out_file($main_dir.$file); information_1 = file_information[0]; information_2 = file_information[1]; myArray = array_merge($myArray, array($key, array($key, $information_1, $information_2, $main_dir, $file)) } } } The array contains all informations i need but the structure of it is not useable. Current output: Array ( [0] => key1 [1] => Array ( [0] => key1 [1] => information_1 [2] => information_2 [3] => ./path/ [4] => filename ) [2] => key1 [3] => Array ( [0] => key1 [1] => information_1 [2] => information_2 [3] => ./path/ [4] => filename ) [4] => key1 [5] => Array ( [0] => key1 [1] => information_1 [2] => information_2 [3] => ./path/ [4] => filename ) [6] => key2 [7] => Array ( [0] => key2 [1] => information_1 [2] => information_2 [3] => ./path/ [4] => filename ) [8] => key2 [9] => Array ( [0] => key2 [1] => information_1 [2] => information_2 [3] => ./path/ [4] => filename ) ) 1 ## IDK why this "1" at the end gets printed out... But what i want to get is this: Array ( [key1] => Array ( Array ( [0] => key1 [1] => information_1 [2] => information_2 [3] => ./path/ [4] => filename ) ) Array ( [0] => key1 [1] => information_1 [2] => information_2 [3] => ./path/ [4] => filename ) ) ) [key2] => Array ( Array ( [0] => key2 [1] => information_1 [2] => information_2 [3] => ./path/ [4] => filename ) ) Array ( [0] => key2 [1] => information_1 [2] => information_2 [3] => ./path/ [4] => filename ) ) ) )
At the end i want to sort the output by alphabetic order of the keys which i should achieve with sort() i guess?
Greetings Edited August 10, 2019 by Sandy_85Hi all, Ok, simple question... just imagine a multidimensional array, array(array(1,2,3,array(4,5,6, array(7,8,9)))); how to build a recursive function that will unpack all the arrays into 1 array. Somehow, none of my tries has worked out properly Cheers I need to create a function that lists subfolders of a given folder, that contain at least one .txt file. I found the following function, which displays a list of file that match a pattern in a directory tree: function find($dir, $pattern){ $dir = escapeshellcmd($dir); $files = glob("$dir/$pattern"); foreach (glob("$dir/{.[^.]*,*}", GLOB_BRACE|GLOB_ONLYDIR) as $sub_dir) //look in subdirectories { $arr = find($sub_dir, $pattern); //recursive call $files = array_merge($files, $arr); // merge array with files from subdirectory } return $files; } $txtFiles=find("project/sys","*.txt"); foreach ($txtFiles as $txtFile) { echo '<h2>'.$txtFile.'</h2>'; //display all text files } My question is, how do I change the function to return only folders that contain at least one text file. But, the functions should look inside child folders of "project/sys" and list a child folder only once if that folder or any of its child folders contain at least one text file. I'll give an example of the output I'm looking for: Folder list project/sys/diagram project/sys/bin project/sys/scripts project/sys/styles project/sys/meta The above folders may not contain a text file directly, but their children folders do. However, I'm not interested in their children folder and I want to list the above level folder only once for each folder. Thanks in advance if ($template->load($maintemplatefile,$values)) { //load every php file in the plugin folder //Handle invalid page Requests } else { echo '404 File Not Found'; //exit; } //print page code echo $template->html(); } I call the above code it prints out the template file but it does not recursively replace the <TEMPLATE_LOADTEMPLATE_$1> that is in the file even though it properly parses both the $tag and $value variables going to the $this->replace($tag,$value); line. Any idea why this does not work? <?php class Template { var $code=''; function load($file,$values) { if (file_exists($file)) { //get template directory $dir=substr($file,0,strrpos($file,'/')) . '/'; //get template $this->code=file_get_contents($file); //check if any recurseve templates to add $tags=$this->tags(); //process all internal template tags $newValues=array_slice($values,1); foreach ($tags as $tag) { //handle inserting new template file if (substr($tag,0,13)=='LOADTEMPLATE_') { $file=substr($tag,13); if ($file[0]=='$') { $file=$values[(substr($file,1)-1)]; } $temp=new Template; $filename=$dir . $file . '.xhtml'; if ($temp->load($filename,$newValues)) { $value=$temp->html(); } else { $value='File Not Found'; } $this->replace($tag,$value); } } return true; } else { return false; } } function tags() { preg_match_all('/<TEMPLATE_[^<]+?>/', $this->code, $tags); $tags=$tags[0]; foreach ($tags as $key=>$value) { $tags[$key]=substr($value,10,-1); } return array_unique($tags); } function replace($tag,$value) { $this->code = ereg_replace('<TEMPLATE_' . $tag . '>',$value . '',$this->code); } function replaceSection($tag,$value) { $replace='~<TEMPLATE_' . $tag . '>[\s\S]*?</TEMPLATE_' . $tag . '>~'; $this->code = preg_replace($replace,$value . '',$this->code); } function compress() { $this->code = ereg_replace("\n",'',$this->code); $this->code = ereg_replace(" ",' ',$this->code); $this->code = ereg_replace("\r",'',$this->code); } function html() { //remove <TEMPLATE_*> & </TEMPLATE_*> tags then return html. return preg_replace('/(<\/?)TEMPLATE_[^<]+?>/','',$this->code); } } ?> All code listed is available for use under GNU public license. Hi there, hope one of you can help me with a problem im just having. Ok, lets start with the explanation what i want to to: I'd like to collect headlines from a html site, and get the test results in an array, so that the array structure represents the dom-levels of the site. Small Example: <h1>test1.1<h1/> <h2>test2.1</h2> <h2>test2.2</h2> <h3>test3</h3> <h1>test1.2<h1/> Shoul end in a array structure like: Code: [Select] array('level 1' => array ( 'sibble1' => array ( 'headline' => 'test1.1', 'level2' => array( 'sibble1' => array ( 'headline' => 'test2.1', 'level3' => array(), // empty data, needs to be processed anyway to find gaps, to maybe a h4 headline would be existing ), 'sibble2' => array ( 'headline' => 'test2.2', 'level3' => array ( 'sibble1' => array ( 'headline' => 'test3.1', 'level4' => array(), // empty data, needs to be processed anyway to find gaps, to maybe a h4 headline would be existing ), ), ), ), ), 'sibble2' => array ( 'headline' => 'test1.1', 'level2' => array(), ), ), ); So i hope out of this example you can see what i want to do. level represents the healdine level 1-9, sibblin is as name for the childs on the headline level. Ok, so to extract the herefore needed data out of the html, i build a class with a recursive function, that filters the html by a regex from one headline to the next, first iteratin all childs, if there are no more childs i go tho ne nextsibbling element. as an running example code look he Code: [Select] <?php class Application_Model_DomParser { const PREG_MATCH_ONE_ELEMENT_TO_MUCH_LENGTH = 4; private $slicedFields = array(); public function __construct() { } public function sliceFirstSectionToDataFields($level = 1, $haystack) { preg_match_all("#(.*?)<h$level>(.*?)</h$level>(.*?)(<h$level>|$)#s", $haystack, $data); // prepare the chunkData $pageText = ''; if (isset($data[1][0])) { $pageText = $data[1][0]; } $headline = ''; if (isset($data[2][0])) { $headline = $data[2][0]; } $dataToProcessNextLevel =''; if (isset($data[3][0])) { $dataToProcessNextLevel = $data[3][0]; } // @todo dirty warnings compression, search why warning occures @$posOfNextChild = strlen($data[0][0]) - self::PREG_MATCH_ONE_ELEMENT_TO_MUCH_LENGTH; // from here goes the debug... echo $headline ."::" .strlen($dataToProcessNextLevel). "<br>"; if (strlen($dataToProcessNextLevel) <= self::PREG_MATCH_ONE_ELEMENT_TO_MUCH_LENGTH) { if ($level < 9) { $dataToProcessNextLevel = $haystack; } else { return; } } //recursive check for next level in $dataToProcessNextLevel $nextLevel = $level + 1; $this->sliceFirstSectionToDataFields($nextLevel, $dataToProcessNextLevel); $haystack = substr($haystack, $posOfNextChild); // slized To The End if (self::PREG_MATCH_ONE_ELEMENT_TO_MUCH_LENGTH == strlen($haystack)) { // die("slized To The End"); return; } // recursive check for other childs in actuall level... $this->sliceFirstSectionToDataFields($level, $haystack); } } $htmlString = 'test<h1>headkline1.1</h1> <p>test test</p> <h2>headline 2.1</h2>test test <h2>headline 2.2</h2> <p>tes test test</p> <h3>headline 3.1</h3>test <h3>headline 3.2</h3>test <h2>headline 2.3</h2> <p> </p> <p>test</p> <h1>headline 1.2</h1> <h2>headline 2.4</h2> <p>11111111111112222222222222222222222</p> <p> ewfwrefg upowmdg w3q09umq09wrt n3q089ty 3q0898943ty -98 41</p> <h3>headline 3.3</h3> <p>test</p> <p>test</p> <p>test</p> <h1>1.3 testtest</h1> <p>test</p> <h3>head 3.4</h3> <p>sadfsadfsadf asdfsda f sdaas saf saddas</p> <h3>head 3.4</h3> <h3>test 1.3</h3> <p>test;</p> '; $model = new Application_Model_DomParser(); $result = $model->sliceFirstSectionToDataFields(1, $this->htmlString); So letting this piece of code run, you can se via the debug echo, every headline is found, even in the right order of its occurence. My problem now is dont get it how to return the extracted values, and collect them to get a result as my above shown structure shows. So i spent ours to solve this problem but didnt come to a result. I know its a hard problem, and to help me takes time, cause its a complex situation. Allthough i hope someone knows a anser. I need this problem solved, to get my mind rested! Thanks, and greetings Selma Hello, I am pasting code below that isn't working corrrectly. One problem is the pagination. When I get more than 10 records, it will show the next 10 link but when I click on it, it just takes me back to an empty page with NO results. How do I fix this? Also where do I insert the block of code for a table to structure my results. As of now, the returned results are all over the page! Thanks! This is the code: Code: [Select] <?php // display what the person searched for echo "<p>You searched for: "" . $var . ""</p>"; // begin to show results set echo "Results"; $count = 1 + $s ; // now you can display the results returned while ($row= mysql_fetch_array($result)) { $title = $row["1st_field"]; echo "$count.) $title" ; $count++ ; } $currPage = (($s/$limit) + 1); //break before paging echo "<br />"; // next we need to do the links to other results if ($s>=1) { // bypass PREV link if s is 0 $prevs=($s-$limit); print " <a href=\"$PHP_SELF?s=$prevs&q=$var\"><< Prev 10</a>  "; } // calculate number of pages needing links $pages=intval($numrows/$limit); // $pages now contains int of pages needed unless there is a remainder from division if ($numrows%$limit) { // has remainder so add one page $pages++; } // check to see if last page if (!((($s+$limit)/$limit)==$pages) && $pages!=1) { // not last page so give NEXT link $news=$s+$limit; echo " <a href=\"$PHP_SELF?s=$news&q=$var\">Next 10 >></a>"; } $a = $s + ($limit) ; if ($a > $numrows) { $a = $numrows ; } $b = $s + 1 ; echo "<p>Showing results $b to $a of $numrows</p>"; ?> MOD EDIT: [code] . . . [/code] BBCode tags added. I'm getting the following error with the code below: Parse error: syntax error, unexpected T_CONSTANT_ENCAPSED_STRING, expecting ',' or ';' in C:\wamp\www\flow\fpdf\rev.php on line 47 Can I get another set of eyes to look at it & see what I'm missing? Code: [Select] <html <head> <?php require('connection.php'); if (isset($_GET['op']) && $_GET['op'] == "d") if($_GET['op'] == "d" && !empty($_GET['id']) ) { { $result = mysql_query($query) or die(mysql_error()); } $query="SELECT fid, pacts, fname, lname, employee, dock, due_owner, due_attny, due_suspo, due_clerk, interv_date, due_rev, assgn_date, sent_date FROM psrinfo"; $result = mysql_query($query) or die(mysql_error()); while($row = mysql_fetch_array( $result )) { ?> <?php } require('connection.php'); if (isset($_GET['op']) && $_GET['op'] == "d") if($_GET['op'] == "d" && !empty($_GET['id']) ) { $result = mysql_query($query) or die(mysql_error()); } $query="SELECT fid, pacts, fname, lname, employee, dock, due_owner, due_attny, due_suspo, due_clerk, interv_date, due_rev, assgn_date, sent_date FROM psrinfo WHERE employee = 'employee1' "; $result = mysql_query($query) or die(mysql_error()); echo '<form action="111.php" method="post"> <h2> <center> Paper Review </center></h2> <table width="75%" border="1">'; while($row = mysql_fetch_array( $result )) { echo '<tr> <td><b>PACTS:</b> <br><input type="text" name="pacts" size="25" maxlength="30" value="'. $row['pacts'] .'" /><br> </td> <td><b>Reviewer:</b> <br><input type="text" name="dock" size="25" maxlength="30" value="''" /><br> </td> </tr> <tr> <td><b>First Name:</b> <br><input type="text" name="fname" size="25" maxlength="30" value="'. $row['fname'] .'" /><br> </td> <td><b>Last Name:</b> <br><input type="text" name="lname" size="25" maxlength="30" value="'. $row['lname'] .'" /><br> </td> <td><b>Dock:</b> <br><input type="text" name="dock" size="25" maxlength="30" value="'. $row['dock'] .'" /><br> </td> </tr> <tr> <td><b>Sent Date:</b> <br><input type="text" name="sent_date" size="25" maxlength="30" value="'. $row['sent_date'] .'" /><br> </td> <td><b>Assign Date:</b> <br><input type="text" name="assgn_date" size="25" maxlength="30" value="'. $row['assgn_date'] .'" /><br> </td> <td><b>Interview Date:</b> <br><input type="text" name="interv_date" size="25" maxlength="30" value="'. $row['interv_date'] .'" /><br> </td> </tr> <tr> <td></b><br><input type="text" name="assgn_date" size="30" maxlength="30" value="Given to Reviewer" /> <br><input type="text" name="assgn_date" size="30" maxlength="30" value="Given to SUSPO" /> <br> <input type="text" name="assgn_date" size="30" maxlength="30" value="Given to Clerk" /> <br> <input type="text" name="assgn_date" size="30" maxlength="30" value="PSR Disclosed to Attn" /> <br> <input type="text" name="assgn_date" size="30" maxlength="30" value="PSR Disclosed to owner" /> </td> <td><b>Initials</b> <br><input type="text" name="dock" size="30" maxlength="30" /> <br> <input type="text" name="dock" size="30" maxlength="30" /> <br><input type="text" name="dock" size="30" maxlength="30" /> <br> <input type="text" name="dock" size="30" maxlength="30" /> <br> <input type="text" name="dock" size="30" maxlength="30" /></td> <td><b>Due Date:</b> <br><input type="text" name="due_rev" size="25" maxlength="30" value="'. $row['due_rev'] .'" /> <br> <input type="text" name="due_suspo" size="25" maxlength="30" value="'. $row['due_suspo'] .'" /> <br> <input type="text" name="due_clerk" size="25" maxlength="30" value="'. $row['due_clerk'] .'" /> <br> <input type="text" name="due_attny" size="25" maxlength="30" value="'. $row['due_attny'] .'" /> <br> <input type="text" name="due_" size="25" maxlength="30" value="'. $row['due_owner'] .'" /> </td> <td><br><input type="text" name="assgn_date" size="30" maxlength="30" value="Given to Reviewer" /> <br><input type="text" name="assgn_date" size="30" maxlength="30" value="Given to SUSPO" /> <br> <input type="text" name="assgn_date" size="30" maxlength="30" value="Given to Clerk" /> <br> <input type="text" name="assgn_date" size="30" maxlength="30" value="PSR Disclosed to Attn" /> <br> <input type="text" name="assgn_date" size="30" maxlength="30" value="PSR Disclosed to Owner" /> </td> <td><b>Actual Date:</b><br><input type="text" name="assgn_date" size="30" maxlength="30" value="" /> <br> <input type="text" name="assgn_date" size="30" maxlength="30" value="" /> <br> <input type="text" name="assgn_date" size="30" maxlength="30" value="" /> <br> <input type="text" name="assgn_date" size="30" maxlength="30" value="" /> <br> <input type="text" name="assgn_date" size="30" maxlength="30" value="" /> </td> </tr>; <td> <b>Employee Notes:</b> <br> <textarea name = "notes" rows=9 cols=100></textarea> </td> </tr>'; } echo '</table> </form>'; mysql_close(); // Close the database connection. ?> </tbody> </table> if ($content['size'] == "sizel") {$content['size'] = "Large";} echo "{$content['size']}"; This doesn't work and just echo's "sizel". Why? I want to make it so that whoever is sending the fame (sender) doesn't send it to themselves (receiver). However, I can't get it to block that. Everything else works, so something must be up with that specific requirement. Any help would be appreciated! Thanks! <?php //error_reporting(E_ALL); //ini_set('display_errors', 1); include("fightfunc.php"); include("lib.php"); define("PAGENAME", "GFame"); $player = check_user($secret_key, $db); $x = $player->username; if($_SESSION['234asdfas']){$y = $_SESSION['234asdfas'];}else{echo 'Error: You do not have a session variable set'; exit;} $command = 1; if (isset($_POST["sendfame"])) { $maxgfame = $player->gfame; include("tmpconfig.php"); $checkquery = mysql_query("SELECT * FROM `users` WHERE `username`='".ucwords(strtolower($_POST['receiver']))."'"); extract($_POST); if($sender == "") { echo "You must put a sender's name in the text box.";//The amount would create a negative balance - implement error condition } elseif ($gfamesent == 0) { echo "Enter an amount greater than 0."; } elseif ($gfamesent < 0) { echo "Enter an amount greater than 0."; } elseif (!is_numeric($gfamesent)) { echo "Enter a numerical amount!"; } elseif ($gfamesent == "") { echo "Enter a numerical amount!"; } elseif ($receiver == "") { echo "You must put a name in the Receiver field."; } elseif ($gfamesent > $maxgfame) { echo "You don't have that much gfame to give."; } elseif ($receiver == $sender) { echo "You can't give gfame to yourself."; } elseif (mysql_num_rows($checkquery) == 0) { echo "That player does not exist."; } else { $query = $db->execute("UPDATE `users` SET `gfame`=? WHERE `id`=?", array($player->gfame - 1, $player->id)) or die("querya failed: ". mysql_error()); if($query) $qry = $db->execute("select * from `users` where `username`=?", array(ucwords(strtolower($_POST['reciever'])))) or die("qry failed: ".mysql_error()); $rw = $qry->fetchrow(); if($qry){ $query2 = $db->execute("UPDATE `users` SET `fame`=? WHERE `username`=?", array($rw['fame'] + 1, $rw['username'])) or die("query2 failed: ". mysql_error()); if($query2){ echo("<br><br>You have successfully transfered your gfame over.<br>"); } } }} $player = check_user($secret_key, $db); ?> <br /><br /><blockquote><center>GFame is fame you can award 1 other person for what you feel is "noteworthiness". In otherwords, if you feel someone is doing a superb job of role-playing their character, you can "reward" them for their actions. You may send 1 gfame point per day. And no, you cannot send it to yourself.</center></blockquote><br /><br /> <table width="100%"> <tr> <td colspan="2"><fieldset> <legend>Transfer GFame:</legend> You have <b><?=$player->gfame?></b> GFame to give.<br /> <form method="post" action="gfame.php"> <input name="sender" type="hidden" value="$player->id" id="sender" /> <input type="submit" value="Transfer" name="sendfame"> <input type="text" value="1" name="gfamesent"> to <input name="receiver" type="text" id="receiver"> </form> </fieldset></td> </tr> </table> Hello PHP Wizards, i wonder if anyone can help, Ive got an associative array set up with a bunch of items, the idea is to compare the array items with items from a form using $_POST. So far ive got the items displaying from the form as follows Code: [Select] <?php while ($client_prices = each($_POST)) { /* sets the name of the array to $client_prices for easy identification */ echo $client_prices['key']; /* Displays the keys withing the $client_prices array */ echo ' - '; echo $client_prices['value']; /* Displays the values within the $client_prices array */ echo '<br />'; } ?> and for the sake of it ill display the array ive set up on the server side using similar code : Code: [Select] <?php while ($server_prices = each($coffee_prices)) { /* sets the name of the array to $server_prices for easy identification */ echo $server_prices['key']; /* Displays the keys withing the $server_prices array */ echo ' - '; echo $server_prices['value']; /* Displays the values within the $server_prices array */ echo '<br />'; } ?> now, what i want to do is make sure that the keys (name of items) and the values (cost of items) from the client side are the same as the keys and values ive set on the server. so i created an if statement : Code: [Select] <?php if( $client_prices['key'] === $server_prices['key'] && $client_prices['value'] === $server_prices['value'] ) echo 'Prices Match'; else echo '<h2>Oops! Somthing Has Gone, Please Call Us To Place Your Order</h2>'; ?> so i thought i had it all working when as it came back with 'prices match', i thought all is good. however when i purposely change the value of one of the items in my server side array so it will be different from the incoming client value, it still says 'prices match' when they clearly don;t? Anyone help would be appreciated p.s. im fairly new to php, and this is for my learning, not a real client. Hi, i am trying to add a very simple shopping cart script to my site, and the session is simply used to keep the contents of the shopping cart, yet its not working properly! Ok ignoring the layout issues with the cart here is the issues. Only two links to the same script First one is a link to the shopping cart with an action to add the item ID to it. http://www.heliuk.co.uk/index.php?n=pages/shop-cart-action&id=1&action=add This works, it adds the item to the session "cart", if that's successful it then shows the cart from the session. But if i just go to the shopping cart with no actions (so just to view it) it shows no items http://heliuk.co.uk/index.php?n=pages/shop-cart-action And what this is doing is checking it the cart is empty, if not show the cart, if it is then show nothing, which is what happening. But if you go back to the first link and add the item again, it is adding it on to the cart so the session is there and working? I don't understand what's happening! Here the shopping cart page. Code: [Select] <?php error_reporting(E_ALL ^ E_NOTICE); $product_id = $_GET["id"]; //the product id from the URL $action = $_GET["action"]; //the action from the URL //if there is an product_id and that product_id doesn't exist display an error message if($product_id && !productExists($product_id)) { die("Error. Product Doesn't Exist"); } switch($action) { //decide what to do case "add": $_SESSION['cart'][$product_id]++; //add one to the quantity of the product with id $product_id break; case "remove": $_SESSION['cart'][$product_id]--; //remove one from the quantity of the product with id $product_id if($_SESSION['cart'][$product_id] == 0) unset($_SESSION['cart'][$product_id]); //if the quantity is zero, remove it completely (using the 'unset' function) - otherwise is will show zero, then -1, -2 etc when the user keeps removing items. break; case "empty": unset($_SESSION['cart']); //unset the whole cart, i.e. empty the cart. break; } ?> <table class='main' cellspacing='1' cellpadding='4'> <tr class='head'> <td class='head' colspan='2'>HeliUK Shop - Your Shopping Cart</td> </tr> <tr> <td style='Text-align:left;' class='con1' colspan='2'> <table border="0" cellpadding="0" cellspacing="0" width="100%"> <?php error_reporting(E_ALL ^ E_NOTICE); if($_SESSION['cart']) { //if the cart isn't empty //show the cart echo "<table border=\"1\" padding=\"0\" width=\"100%\">"; //format the cart using a HTML table //iterate through the cart, the $product_id is the key and $quantity is the value foreach($_SESSION['cart'] as $product_id => $quantity) { //get the name, description and price from the database - this will depend on your database implementation. //use sprintf to make sure that $product_id is inserted into the query as a number - to prevent SQL injection $sql = sprintf("SELECT title, description, price FROM items WHERE id = %d;", $product_id); $result = mysql_query($sql); //Only display the row if there is a product (though there should always be as we have already checked) if(mysql_num_rows($result) > 0) { list($name, $description, $price) = mysql_fetch_row($result); $line_cost = $price * $quantity; //work out the line cost $total = $total + $line_cost; //add to the total cost echo "<tr>"; echo "<td style=\"border-left-width: 1px; border-right-style: solid; border-right-width: 1px; border-top-width: 1px; border-bottom-style: solid; border-bottom-width: 1px\" width=\"145\">"; echo "<font face=\"Tahoma\" size=\"2\">$quantity</font></td>" ; echo "<td style=\"border-left-width: 1px; border-right-style: solid; border-right-width: 1px; border-top-width: 1px; border-bottom-style: solid; border-bottom-width: 1px\" width=\"693\">"; echo "<font face=\"Tahoma\" size=\"2\">$name</font></td>" ; echo "<td style=\"border-left-width: 1px; border-right-style: solid; border-right-width: 1px; border-top-width: 1px; border-bottom-style: solid; border-bottom-width: 1px\" width=\"162\">"; echo "<font face=\"Tahoma\" size=\"2\">$line_cost</font></td>" ; echo "<td style=\"border-left-width: 1px; border-right-width: 1px; border-top-width: 1px; border-bottom-style: solid; border-bottom-width: 1px\">"; echo "<p align=\"center\"><a href=\"$_SERVER[PHP_SELF]?action=remove&id=$product_id\">" ; echo "<img border=\"0\" src=\"empty-cart.jpg\" width=\"24\" height=\"24\"></a></td>" ; echo "</tr>"; } } //show the total echo "<tr>"; echo "<td colspan=\"0\" align=\"right\">Total</td>"; echo "<td align=\"right\">$total</td>"; echo "</tr>"; //show the empty cart link - which links to this page, but with an action of empty. A simple bit of javascript in the onlick event of the link asks the user for confirmation echo "<tr>"; echo "<td colspan=\"0\" align=\"right\"><a href=\"$_SERVER[PHP_SELF]?action=empty\" onclick=\"return confirm('Are you sure?');\">Empty Cart</a></td>"; echo "</tr>"; echo "</table>"; }else{ //otherwise tell the user they have no items in their cart echo "You have no items in your shopping cart."; } ?> </table> </td> </tr> </table> <? //function to check if a product exists function productExists($product_id) { //use sprintf to make sure that $product_id is inserted into the query as a number - to prevent SQL injection $sql = sprintf("SELECT * FROM items WHERE id = %d;", $product_id); return mysql_num_rows(mysql_query($sql)) > 0; } ?> Hey guys, I'm using a PHP form for my website & I can't get it to send the email correctly, all it send me is the first and last name, but none of the other boxes, any help? Also how can I secure it?
This is the PHP file:
<!DOCTYPE html> |