PHP - Get_headers() Returns Empty When Called From Another Php File :(
Hi everyone!
I've been working on a php script to replace links that contain a query with direct links to the files they would redirect to. In this case I have to rewrite the xml with this script. Situation is not optimal, I'm running the chunk script because we're stuck with the execution time limit too. Export filter: This loops over a xml file and splits it into chunks <?php //ini_set('max_execution_time', 10); // ---- includes if ( ! defined('ABSPATH') ) { require_once( dirname( __FILE__ ) . '/wp-load.php' ); } // ---- end includes // console function vwaconsole($input) { $disabled = false; if ($disabled === false) { $a = print_r($input.'</br>'); $a = $input; echo "<script>console.log( '--log--: " . $a . "' );</script>"; } } //end console // settings // $chunk_size = 20; // $home = constant( 'ABSPATH' ); $xml_path = $home."/wp-content/uploads/wpallimport/files/Bastiaansen.xml"; if (fopen($xml_path,"r") != true) { vwaconsole("xml file does not exist"); exit(); } $xml = new DOMDocument(); $xml->formatOutput = true; $xml->preserveWhiteSpace = false; $xml->load($xml_path); // Main program // creates another file to be filled by sub scripts if (!empty($xml)) { vwaconsole("Running main program"); // backup xml first $date = "_".date("Y M D h i"); $date = str_replace(' ', '_', $date); $xpath = new DOMXpath($xml); $items = $xpath->query("//aanbiedingen//item"); $loopcount = 0; $processedamount = 0; $islast = 0; vwaconsole('total items: '.$items->length); vwaconsole('chunk size: '.$chunk_size); echo'<br>'; /* chunks processing: */ $chunkxml = new DOMDocument(); $chunkxml->formatOutput = true; $chunkxml->preserveWhiteSpace = false; $counter = 0; $chunkroot = null; foreach($items as $item) { //vwaconsole('processing item'); if ($chunkroot === null) { $chunkroot = $chunkxml->createElement('root'); $chunkxml->appendChild($chunkroot); //vwaconsole('created root'); } if (($processedamount + $chunk_size) > $items->length) { //vwaconsole("last chunk in progress..."); $islast = 1; } $chunkitem = $chunkxml->createElement($item->nodeName); $chunkroot->appendChild($chunkitem); //vwaconsole('appended child item to root'); foreach($item->childNodes as $spec) { //vwaconsole('processing specs in item'); $chunkspec = $chunkxml->createElement($spec->nodeName); $chunkitem->appendChild($chunkspec); $chunkspectext = $chunkxml->createTextNode($spec->nodeValue); $chunkspec->appendChild($chunkspectext); } $counter++; $processedamount++; if ($counter >= $chunk_size) { $chunkxml->save("wp-content/uploads/wpallimport/files/chunks_bast/bast_chunk_".$loopcount.".xml"); vwaconsole("saved array chunk"); $output = `php export_filter_chunk_processor.php $loopcount $islast `; vwaconsole($output); vwaconsole("creating new array chunk"); $chunkxml = new DOMDocument(); $chunkxml->formatOutput = true; $chunkxml->preserveWhiteSpace = false; $loopcount++; $counter = 0; $chunkroot = null; } if ($items->length === $processedamount) { $chunkxml->save("wp-content/uploads/wpallimport/files/chunks_bast/bast_chunk_".$loopcount.".xml"); vwaconsole("finished saving last chunk"); } } // merge documents later.. /* $newxml = new DOMDocument("1.0", "utf-8"); $newxml->formatOutput = true; $newxml->preserveWhiteSpace = false; $itemContainer = $newxml->createElement('aanbiedingen'); $newxml->appendChild($itemContainer); //$newxml->save("wp-content/uploads/wpallimport/files/TEMP_Bastiaansen.xml"); */ vwaconsole("main ending"); exit(); } else { //vwaconsole("xml is empty ?! exiting"); exit(); } ?>
Export chunk processor: The xml was split by the previous script. This one takes one of the chunks and calls get_headers() , sending a link containing a query multiple of this script run at same time. The queries are then picked up by the last php file. <?php //ini_set('max_execution_time', 10); // console function vwaconsole($input) { $disabled = false; if ($disabled === false) { $a = print_r($input.'</br>'); $a = $input; echo "<script>console.log( '--log--: " . $a . "' );</script>"; } } //end console //echo'<br>'; print_r("called chunk processor > Chunk processor started. "); //echo'<br>'; $loopcount=$argv[1]; $islast=$argv[2]; if ($loopcount === null || $islast === null) { print_r("CHUNK PROCESSOR ERROR > loop count is empty"); exit(); } else { print_r("CHUNK PROCESSOR variables set. loop count: ".$loopcount." is last: ".$islast."<br>"); } if ( ! defined('BAST_ROOT_DIR') ) { define('BAST_ROOT_DIR', __DIR__); } $home = constant( 'BAST_ROOT_DIR' ); $xml_path = $home."/wp-content/uploads/wpallimport/files/chunks_bast/bast_chunk_".$loopcount.".xml"; if (fopen($xml_path,"r") != true) { print_r("chunk file was not found at path: ".$xml_path); exit(); } $xmlChunk = new DOMDocument(); //$xmlChunk = new DOMDocument(); $xmlChunk->formatOutput = true; $xmlChunk->preserveWhiteSpace = false; $xmlChunk->load($xml_path); if (empty($xmlChunk)) { print_r("chunk data is empty, exiting"); exit(); } else { print_r("got chunk data <br>"); } $xpath = new DOMXpath($xmlChunk); $item = $xpath->query("//root//item"); //$items = $xmlChunk->getElementsByTagName('//root//item'); foreach ($item as $node) { echo'new item: <br>'; foreach ($node->childNodes as $spec) { //vwaconsole("processing spec: ".$spec->nodeName); if (($spec->nodeName == 'itemlink')) { $memValue = $spec->nodeValue; //setting new url spec node $spec->nodeValue = processItemLink($memValue); // add new itemfoto nodes to xml } elseif(($spec->nodeName == 'itemfoto1')) { $memValue = $spec->nodeValue; $imgurls = array(); $first = true; for ($i = 1; $i < 50; $i++) { if ($first === false) { $memValue = str_replace('bast_get_itemfoto_id='.strval($i-1), 'bast_get_itemfoto_id='.strval($i), $memValue); } vwaconsole("trying to get a itemfoto with id: ".strval($i)." link: " .$memValue); $triedFotoUrl = processItemLink($memValue); vwaconsole("tried url: ".$triedFotoUrl); if($triedFotoUrl !== $memValue) { $imgurls[] = $triedFotoUrl; } else { vwaconsole("tried url and processed url are equal. end of loop. No new images left or error happened."); break; } $first = false; } //remove the old single itemfoto from xml $spec->parentNode->removeChild($spec); // add sorted nodes from image array if (!empty($imgurls)) { sort($imgurls, SORT_NATURAL); print_r('<br> after sort;'); print_r($imgurls); print_r('<br>'); $arlength = count($imgurls); for($x = 0; $x < $arlength; $x++) { $newItemFoto = $xml->createElement('itemfoto'.strval($x+1)); $newItemFotoText = $xml->createTextNode($imgurls[$x]); $newItemFoto->appendChild($newItemFotoText); $node->appendChild($newItemFoto); } unset($imgurls); } } } echo'<br>'; } //returns string url //follow the query url from xml, return a direct link or returns input on failure. query is processed in Bastiaansen.php. function processItemLink($url) { if (!empty($url)) { $headers = get_headers($url, 1); if(!empty($headers['Location'])) { vwaconsole('test returning header location: '.$headers['Location']); return $headers['Location']; } else { vwaconsole("header empty ?!?! can't convert query"); } } return $url; } $xmlChunk->save("wp-content/uploads/wpallimport/files/chunks_bast/bast_chunk_test_".$loopcount.".xml"); ?>
When the chunk processor calls a query link with get_headers(), the query will be noticed by the next script, the query converter: <?php if ( ! defined('ABSPATH') ) { require_once( dirname( __FILE__ ) . '/wp-load.php' ); } // ---- vars $machineID = $_GET['bast_get_machine_id']; $itemlink = $_GET['bast_get_itemlink']; $itemfoto_id = $_GET['bast_get_itemfoto_id']; if (!empty($itemlink)) { $request = 'bast_get_itemlink'; $value = $itemlink; } elseif (!empty($itemfoto_id)) { $request = 'bast_get_itemfoto_id'; $value = $itemfoto_id; } // ---- end vars if (empty($machineID)) { echo 'please enter query ?bast_get_machine_id=(number) first'; exit(); } if (empty($request) || empty($value)) { echo 'Valid query request would be: bast_get_itemlink <br>'; echo 'Valid query request would be: bast_get_itemfoto_id <br>'; exit(); } // register custom query options function sm_register_query_vars( $vars ) { // get the right custom field names $vars[] = $request; $vars[] = 'pa_'.$request; return $vars; } add_filter( 'query_vars', 'sm_register_query_vars' ); //returns null or string url function fetch($machineID,$request,$value) { $return = null; $args = array( 'orderby' => 'meta_value_num', 'meta_key' => 'bast_get_machine_id', 'meta_type' => 'NUMERIC', 'post_type' => 'product', 'posts_per_page' => -1, 'order' => 'ASC', 'meta_query' => array( array( 'key' => 'bast_get_machine_id', 'type' => 'NUMERIC', 'value' => $machineID, 'compare' => 'EXISTS', ) ) ); $wp_query = new WP_Query($args); if ( $wp_query->have_posts() ) { while ( $wp_query->have_posts() ) { $wp_query->the_post(); apply_filters( 'the_content', 'filter_post_content' ); echo 'found product " '.get_the_title().' " on machine ID '.$machineID.'<br>'; echo 'requested: '.$request.'<br>'; if ($request === 'bast_get_itemlink') { // product url $return = get_permalink(get_the_ID()); break; } elseif ($request === 'bast_get_itemfoto_id') { // image attachment $attachments = get_posts(array( 'post_type' => 'attachment', //'post_mime_type' => 'image', 'posts_per_page' => -1, 'post_parent' => get_the_ID() //'exclude' => get_post_thumbnail_id() )); // as the requested value should be 1, but the array starts at 0.. remove 1 from value if (!empty($attachments) && ($attachments != false) && !empty($attachments[$value-1]) && ($attachments[$value-1] != false) ) { $return = wp_get_attachment_image_src( $attachments[$value-1]->ID, 'full')[0]; echo 'attachment found'; } else { echo 'attachment empty...'; } echo 'total amount of images found on this machine: '.count($attachments); break; } break; } /* Reset Post Data after loop */ wp_reset_postdata(); } else { echo 'query on machine ID '.$machineID.' found no product. Exit.'; } return $return; } function filter_post_content( $content ) { // Check if we're inside the main loop in a single post page. if ( is_single() && in_the_loop() && is_main_query() ) { return $content; } return $content; } $finaldestination = fetch($machineID,$request,$value); if (empty($finaldestination)) { exit(); } //echo 'destination set: '.$finaldestination.'<br>'; header("Location: ".$finaldestination, true, 302); ?>
Similar TutorialsHi everyone! I've been working on a php script to replace links that contain a query with direct links to the files they would redirect to. Hi All, I am pretty new to PHP ( I am a C Programmer). I am trying a simple shopping cart website for my friend. IN one of the pages, I am submitting some info, which is actually not showing up in my server side php. Below is the HTML code to submit. <a href="cart.php?action=add&p=5&size=small"> <img src="images/add_to_cart.gif"/> </a> I tried to check the values of the parameters using $action = $_GET['action'] ; Action stored empty. Then I checked the whole array print_r($_GET) which returned Array( ) So, for some reason the value is always empty. I tried the declaration GLOBAL $_GET, but no use. Any help/directions - much appreciated! Hello i have a system where leaders add members, i want to display a table of members WHERE the 'leader' field equals 'myusername' so that leaders only see members they added. when using the WHERE function i get a database empty as the result but when i remove the WHERE function i get all the data returned Code: [Select] include("system/include/session.php"); $myUname = $session->username; echo "$myUname"; function displayMembers(){ global $database; $q = "SELECT * " ."FROM ".TBL_MEMBERS." WHERE leader = '$myUname'"; $result = $database->query($q); $num_rows = mysql_numrows($result); if(!$result || ($num_rows < 0)){ echo "Error displaying info"; return; } if($num_rows == 0){ echo "Database table empty"; return; } echo "<table>\n"; echo "<thead> <tr> <th>Full Name</th> <th>Gender</th> <th>DOB</th> <th>Post Code</th> <th>Email Address</th> <th>Edit User</th> </tr> </thead>\n"; for($i=0; $i<$num_rows; $i++){ $Mprefix = mysql_result($result,$i,"prefix"); $Mfname = mysql_result($result,$i,"firstname"); $Mlname = mysql_result($result,$i,"lastname"); $Mgender = mysql_result($result,$i,"gender"); $Mdob = mysql_result($result,$i,"dob"); $Mpostcode = mysql_result($result,$i,"postcode"); $Memail = mysql_result($result,$i,"email"); echo " <tbody> <tr> <td>$Mprefix $Mfname $Mlname</td> <td>$Mgender</td> <td>$Mdob</td> <td>$Mpostcode</td> <td>$Memail</td> <td> <center> <form action=\"system/admin/adminprocess.php\" method=\"POST\"> <input type=\"hidden\" name=\"deluser\" value=\"$uname\"> <input type=\"hidden\" name=\"subdeluser\" value=\"1\"> <input type=\"submit\" class=\"button plain\" value=\"Edit Member\"> </form> </center> </td> </tr> </tbody>\n"; } echo "</table><br>\n"; } all help i am thankful for I noticed that strtolower() wasn't working. My script was adding blank rows to a text file that was supposed to be lowercase emails, so I wrote the following script to confirm it's not working: <?php $var = "Foo"; echo "$var<br />"; echo srttolower($var)."<br />"; $var = strtolower($var); echo "$var<br />"; ?> This page just prints "Foo" once on the screen where I should see Foo foo foo I then checked my error log, and I'm getting Call to undefined function messages for strtolower(). Any ideas? In my code I call PEAR::isError to see if there was an error in the SQL Query so I can log it but its always returning this error. Does anyone know a fix? I have tried to search google it and found http://pear.php.net/bugs/bug.php?id=9950 but it does not say how to fix it. Does anyone have any ideas? Error Non-static method PEAR::isError() should not be called statically $query = "SELECT Column FROM TableName"; $res = $db['database']->query($query); if (PEAR::isError($res)) { $logger->err("Error pulling results from DB. Query:" . $query); } Hi All, I am using the uploadify script available at http://uploadify.com/ Now I can get the file uploads working fine with the script below: Code: [Select] <?php session_start(); ?> <link href="/uploadify/uploadify.css" rel="stylesheet" type="text/css" /> <script type="text/javascript" src="/uploadify/jquery-1.3.2.min.js"></script> <script type="text/javascript" src="/uploadify/swfobject.js"></script> <script type="text/javascript" src="/uploadify/jquery.uploadify.v2.1.0.min.js"></script> <input id="fileInput" name="fileInput" type="file" /> <script type="text/javascript">// <![CDATA[ $(document).ready(function() { $('#fileInput').uploadify({ 'uploader' : '/uploadify/uploadify.swf', 'script' : '/uploadify/uploadify.php', 'cancelImg' : '/uploadify/cancel.png', 'auto' : true, 'folder' : '<?php echo $_SESSION['filepath']."/downloads/"; ?>', 'multi' : true }); }); // ]]></script> The problem that I am having is that I also store the mysql connection details in session vars (they change depending on who logs in). I have tried a number of ways of "passing" these session vars to the uploadify.php file which does the grunt work of the uploading, but I can never seem to access them. I obviously dont want to pass them to the uploadify.php script through the js because that will show my credentials in the source code. So, the question is, how can I access these session vars in the called file. I assume its a combination of session_write_end() and session_start() but I havent got the right combination yet. Hello All, I am in desperate help here since my site was DDoS attacked by some one in turkey (Ips originate mostly from turkey, Germany, and some other Europe countries). I have installed the ddos deflation and most of the IPs are now blocked. I have a php file in my server that I use to input data into my database and my streaming servers. This file is called connect.php and the hacker is basically created an automated script that repeatedly call the connect.php file from a botnet resulting in both apache and mysql dead. I use connect.php in the following way http.open('get', "ajax/createchannel_1.php?channel=" + channelname + "&sitename=" + sitename + "&privateurl=" + privateurl + "&privateurlcheck=" + privateurlcheck); How can i change the connect.php so that it only accept execution from my server/ Please your help is greatly appreciated. I use jQuery when adding messages. However, the file can be called directly. For example: includes/add_comment.php?id=2 So, I can make a form and call this file directly to add a message. ID is user id and form can be submited with HTML form wherever are located. How to prevent direct access to the file when called through a Ajax? Need Suggestion for my codes, I want msg1.php to be open in the frame bottomframe. if($username=="" || $password=="") { echo "<form method=\"post\" action=\"msg1.php\" target=\"bottomframe\" >"; } I'm working on a WordPress theme and I'm trying to build in a simple if statement which will check if the user has add his own logo into the images folder if he doesn't then the name of the blog will appear as normal text in place of the graphic logo. This is how it looks like: <?php $logo_dir = get_template_directory_uri() . "/images/logo.png"; if (file_exists($logo_dir)) { ?> <li><img src="<?php bloginfo ('template_directory'); ?>/images/logo.png" alt="<?php bloginfo('description'); ?>" /></li> <?php } else { ?> <li id='blog_name'><a href="<?php bloginfo('url'); ?>"><?php bloginfo('name'); ?><font>*</font></a></li> <?php } ?> I've echo'd out $logo_dir, the URL is correct, but still for some reason it's seeing it as if there would no file exist. If I turn it around into !file_exists then the graphic logo WILL show up. So it's always seeing it as non-existent. Any ideas why this could be or am I using this function in a wrong fashion? As far as I've understood the PHP manual, this is the correct way of using it. So in my last thread I was working on checking if a file was there...I resorted to something not in the library and used $pic_exists_jpg = fopen($jpg_path,'r'); $pic_exists_jpeg = fopen($jpeg_path,'r'); $pic_exists_gif = fopen($gif_path,'r'); $pic_exists_png = fopen($png_path,'r'); if ($pic_exists_jpg != '0') { $jpg_test = '1'; } elseif ($pic_exists_jpg == '1') { $jpg_test = '2'; } elseif ($pic_exists_jpg == '0') { $jpg_test = '2'; } elseif ($pic_exists_jpeg != '0') { $jpeg_test = '1'; } elseif ($pic_exists_gif != '0') { $gif_test = '1'; } elseif ($pic_exists_png != '0') { $png_test = '1'; } now for some reason php is being a poo and no matter what returning that there is a file there. no matter what method i use be it fopen or file_exists or anything else, it saying I have a file in that directory BUT I DO NOT! THERE IS NOT ONE OF THOSE FILES. I know I have my paths right because If I echo them directly I get the picture...what the heck?! I wish to find a way to test if multiple sites are up or not. I have been using get_headers but it seems that this does not do what I thought I would. I wish to know if the sites are down or not. Is there another function that can test what state the site is in. i.e. server not found, server issues prevented the page from showing... Using get_headers will still show the site is live even if the server is not found, due to server problems, if any. I want to remove empty paragraphs from an HTML document using simple_html_dom.php. I know how to do it using the DOMDocument class, but, because the HTML files I work with are prepared in MS Word, the DOMDocument's loadHTMLFile() function gives this exception "Namespaces are not defined". This is the code I use with the DOMDocument object for HTML files not prepared in MS Word: <?php /* Using the DOMDocument class */ /* Create a new DOMDocument object. */ $html = new DOMDocument("1.0", "UTF-8"); /* Load HTML code from an HTML file into the DOMDocument. */ $html->loadHTMLFile("HTML File With Empty Paragraphs.html"); /* Assign all the <p> elements into the $pars DOMNodeList object. */ $pars = $html->getElementsByTagName("p"); echo "The initial number of paragraphs is " . $pars->length . ".<br />"; /* The trim() function is used to remove leading and trailing spaces as well as * newline characters. */ for ($i = 0; $i < $pars->length; $i++){ if (trim($pars->item($i)->textContent) == ""){ $pars->item($i)->parentNode->removeChild($pars->item($i)); $i--; } } echo "The final number of paragraphs is " . $pars->length . ".<br />"; // Write the HTML code back into an HTML file. $html->saveHTMLFile("HTML File WithOut Empty Paragraphs.html"); ?> This is the code I use with the simple_html_dom.php module for HTML files prepared in MS Word: <?php /* Using simple_html_dom.php */ include("simple_html_dom.php"); $html = file_get_html("HTML File With Empty Paragraphs.html"); $pars = $html->find("p"); for ($i = 0; $i < count($pars); $i++) { if (trim($pars[$i]->plaintext) == "") { unset($pars[$i]); $i--; } } $html->save("HTML File without Empty Paragraphs.html"); ?> It is almost the same, except that that the $pars variable is a DOMNodeList when using DOMDocument and an array when using simple_html_dom.php. But this code does not work. First it runs for two minutes and then reports these errors: "Undefined offset: 1" and "Trying to get property of nonobject" for this line: "if (trim($pars[$i]->plaintext == "")) {". Does anyone know how I can fix this? Thank you. I also asked on stackoverflow. Man, I'm having a rough week with questions--if you're following at home. Basically matching a Coach's first and last name to another table, which if matched will yield information about that coach's team. Code: [Select] // or get user by username $current_user = wp_get_current_user(); $current_first = $current_user->user_firstname; $current_last = $current_user->user_lastname; $current_id = $current_user->ID; echo '<div class="contact_form">'; echo $current_first . ' ' . $current_last .' :: '; $query = "SELECT * FROM schools WHERE coachFirst='".$current_first."' AND coachLast='".$current_last."'"; $result = mysql_query ($query); if(!$result) { echo 'There is not a match for your name.'; } else { while($school= mysql_fetch_array($result)) { echo $school['school'] . ' ' . $school['id']; include(ABSPATH ."wp-content/plugins/my-team/form.php"); } echo '</div>'; echo '<div class="roster">'; include(ABSPATH ."wp-content/plugins/my-team/roster.php"); echo '</div>'; } What I am looking for is that if any field in a database is empty, the form comes back and puts in the word "empty" into the web page, but not the database. I got this right now, it shows the first part fine, but the second part it doesn't show the "Empty" comment... I don't understand why... as far as I can tell the code is fine... Code: [Select] <?php //Nonconformity, Disposition, Comments and Comments & Additional Details echo '<div id="box3">'; if (!empty($row['Nonconformity']) || !empty($row['Disposition']) || !empty($row['Comments']) || !empty($row['CommentsAdditional_Details'])) { echo '<div id="non"><span class="b">Nonconformity: </span><br />' . $row['Nonconformity'] . '</div>'; echo '<div id="dis"><span class="b">Disposition: </span><br />' . $row['Disposition'] . '</div>'; echo '<div id="comm"><span class="b">Comments: </span><br />' . $row['Comments'] . '</div>'; echo '<div id="comma"><span class="b">Comments and/or Additional Details: </span><br />' . $row['CommentsAdditional_Details'] . '</div>';} else if (empty($row['Nonconformity']) || empty($row['Disposition']) || empty($row['Comments']) || empty($row['CommentsAdditional_Details'])) { echo '<div id="non"><span class="b">Nonconformity: </span><br />Empty</div>'; echo '<div id="dis"><span class="b">Disposition: <br /></span>Empty</div>'; echo '<div id="comm"><span class="b">Comments: <br /></span>Empty</div>'; echo '<div id="comma"><span class="b">Comments and/or Additional Details: </span><br />Empty</div>';} echo '</div>'; ?> I've been trying to find tutorials/coding today related to controlling the ability to download files. The problem I think I'm having because I know it exists is I don't actually know what it's called. Below is kind of a basis for a tutorial or describing what I'm trying to do. I'm trying to find a tutorial or a how to on storing downloadable files either in a Mysql Database &/or on the file server system. I want to make it so that only users that are stored within the user database who have certain rights or a field can be able to download a file. Those users who don't have the proper permissions in the user table will not be able to and those who do when they go to download a file, will be able to. I know these scripts use PHP but am not really sure where to begin on my search because I don't even know what file permissions coding they are using. It's a little difficult for me to explain but, when a website loads another site (For example with Curl or something) How is the site able to keep a header or some part of original site 'attached' to the site they loaded..for example, say you're redirected, the site you redirected to loads, but you still see the site you redirected from header on at the top of the page. How is this done? What is it called? Do you need me to clear it up a bit better? I can try to find an example. hi, i just wanted to know... $arr[0] $arr[1] $arr[2] also this $arr[1] would be called a value, but how are the numbers 0,1 and 2 called? are that keys? didn't know where else to post this question. Hey guys, I am still kinda new to php and I can't seem to get this to work. Basically I am calling a script and first I need it retrieve certain values which is working fine, but then after that is called I need it to clear those values it just displayed. To do that I am using UPDATE but it doesn't seem to be calling the UPDATE part. Any ideas? Here is the code: Code: [Select] @mysql_select_db("$db_name") or die ("No DataBase Found"); $result = mysql_query("SELECT * FROM members WHERE id='$_POST[id]'"); while ($row = mysql_fetch_array($result)) { $message = $row['message']; $sender = $row['sender']; echo $message . "\n" . $sender; } mysql_query("UPDATE memebers SET message='' WHERE id='$_POST[id]'"); //These never get mysql_query("UPDATE memebers SET sender='' WHERE id='$_POST[id]'");//called or so it seems I have 2 forms on a page, 1 with a selection of newly registered accounts and another that displays the information on the user. What I need to happen is when a user is selected from the first form, the second form is populated with the data. I'm trying to do this with a combination of php and javascript, however whenever a user is selected the function isn't being called at all as far as I can tell. Can anyone help me get this working please? Code: [Select] <!DOCTYPE HTML> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>Fearless Bandits :: Admin Control Panel</title> </head> <body> <?php //Check for config file and initiate session. require("config.php"); session_start(); //Connect to DB if(!$con) die('Could not connect: ' . mysql_error()); mysql_select_db("$dbname") or die("Cannot select DB"); //Check user authorisation if(!isset($_COOKIE['user'])) { echo "Error: Cookies must be enabled. Please enable cookies in your browser and try again.<br>"; return; } else { $user=$_SESSION['user']; $sql="SELECT * FROM users WHERE username='$user' and access='2'"; $result=mysql_query($sql); $count=mysql_num_rows($result); if($count == 0) { echo "Error: Unauthorised access detected."; return; } } include("header.php"); echo "Admin Control Panel<br>"; //Check for mode, if no mode set to 0 if(isset($_GET['mode'])) $mode=$_GET['mode']; else $mode=0; //Display information based on mode switch($mode){ //Check for new applications case 1: echo "<a href=\"admin.php?mode=0\">Back</a><br>"; $sql="SELECT * FROM users WHERE newreg='1'"; $result=mysql_query($sql); $count=mysql_num_rows($result); $newuser = NULL; $newuid = NULL; $newapi = NULL; $newmember = 0; //If there is more than one load results into an array if($count > 0) { echo "There is at least 1 new user:<br>"; $i = 0; while($row=mysql_fetch_array($result)) { $newaccounts[$i] = $row['username']; $i++; } for($i=0; $i < $count; $i++) { echo "User " . $i . ": " . $newaccounts[$i] . "<br>"; } //Select user echo "<form name=\"selectuser\" action=\"\">"; echo "<select name=\"username\" onChange=\"newaccntsUpdate(this);\">"; echo "<option value=\"\" selected=\"selected\"></option>"; for($i=0; $i < $count; $i++) { echo "<option value=\"" . $newaccounts[$i] . "\">" . $newaccounts[$i] . "</option>"; } echo "</select><br>"; echo "</form>"; //Output array into form. echo "<form name=\"newaccnts\" method =\"post\" action=\"verify_admin.php?form=1\">"; echo "Username: <input name=\"newuser\" type=\"text\" id=\"newuser\" value=\"" . $_SESSION['newuser'] . "\">"; echo "UID: <input name=\"newuid\" type=\"text\" id=\"newuid\" value=\"" . $_SESSION['newuid'] . "\">"; echo "API: <input name=\"newapi\" type=\"text\" id=\"newapi\" value=\"" . $_SESSION['newapi'] . "\">"; if($newmember == 0) echo "Member: <input name=\"newmember\" type=\"checkbox\" id=\"newmember\" value=\"1\"><br>"; else echo "Member: <input name=\"newmember\" type=\"checkbox\" checked= \"checked\" id=\"newmember\" value=\"1\"><br>"; echo "<input name=\"submit\" type=\"submit\" value=\"Submit\">"; echo "</form>"; } break; //Select a mode default: echo "Please select a function below:<br>"; echo "<ul>"; echo "<li><a href=\"admin.php?mode=1\">Check for new applications</a></li>"; echo "<li><a href=\"admin.php?mode=2\">Modify an existing account</a></li>"; echo "<li><a href=\"admin.php?mode=3\">Reset a password</a></li>"; echo "<li><a href=\"admin.php?mode=4\">Delete an account</a></li>"; echo "<ul>"; break; } mysql_close($con); //Update newaccnts function. Pull user info from databse and then run javascript function newaccntsUpdate() { echo "newaccntsUpdate executed<br>"; //Error checking //Identify username $newuser=identifyUser(); //If username is NULL or blank return if($newuser == NULL || $newuser == "") return; $sql = ("SELECT * FROM users WHERE username='$newuser'"); $result = mysql_query($sql); $row = mysql_fetch_array($result); $_SESSION['newuser'] = $newuser; $_SESSION['newuid'] = $row['uid']; $_SESSION['newapi'] = $row['api']; $_SESSION['newmember'] = $row['member']; //Update form with details updateForm(); return; } ?> <script language = "Javascript"> //Identify which user has been selected function identifyUser() { $newuser = document.selectuser.username.value; alert('identifyUser executed'); //Error checking return($newuser); } //Update form function updateForm() { document.newaccnts.newuser.value = $newuser; document.newaccnts.newuid.value = $_SESSION['newuid']; document.newaccnts.newapi.value = $_SESSION['newapi']; alert('updateForm executed'); //Error checking return; } </script> </body> </html> I apologise if I've butchered the code, I'm still learning. |