PHP - Critique And Help Improve My Uri Class
I am fairly comfortable with procedural PHP but when it comes to classes and OO I am learning.
I have written a small class to get all of the information from the URL. I am sure I have added my own style and broken about a million rules. I have already found places to improve this but I thought I would bounce it off everyone here before I started to make changes and started expanding it. I am also aware that there are classes that I can download that do this much better but I am trying to better understand how they work so I think this is a good start. Can you just look it over and point out things that I have done wrong and give me some general pointers on how to improve it. class uri extends mainframe{ private $path = null; private $pathParse = array(); private $component = null; private $view = null; private $host = null; private $dirDepth = null; public $queryString = array(); function __construct() { $this->getHost(); $this->getPath(); $this->getView(); $this->getQueryString(); } /* * Check to see if we are in the base folder */ function dirDepth($base) { $this->dirDepth = config::DDEPTH + $base; return $this->dirDepth; } /* * return the host address */ function getHost() { $this->host = $_SERVER['HTTP_HOST']; return $this->host; } /* * return the path information */ function getPath() { $this->path = $_SERVER['REQUEST_URI']; return $this->path; } /* * returns the query string in an array * * I am sure this isn't the right way to do this * but it is working. */ function getQueryString() { $this->getPath(); preg_match('/\?(.*)/', $this->path, $queryString); if ($queryString == true) { $queryPairs = array(); $queryString = (isset($queryString['1']) ? $queryString['1'] : null); $queryPairs = explode('&', $queryString); $queryStrings = array(); $pairs = array(); foreach ($queryPairs as $queryPairs) { preg_match('/(.*)=(.*)/', $queryPairs, $pairs); array_push($queryStrings, $pairs); } $key = array(); $value = array(); foreach ($queryStrings as $queryStrings) { array_push($value, (isset($queryStrings['2']) ? $queryStrings['2'] : null)); array_push($key, (isset($queryStrings['1']) ? $queryStrings['1'] : null)); } $this->queryString = array_combine($key, $value); return $this->queryString; }else{ unset($this->queryString); } } /* * returns the path in an array and removes the query string */ function pathParse() { self::getPath(); $this->pathParse = explode('/', $this->path); $endCheck = preg_replace('/\?(.*)/','', array_pop($this->pathParse)); array_push($this->pathParse, $endCheck); $this->pathParse = array_filter($this->pathParse); if(!empty($this->pathParse)) { return $this->pathParse; }else{ unset($this->pathParse); } } /* * returns the first part of the path */ function getComponent() { self::pathParse(); self::dirDepth('1'); if(!empty($this->pathParse[$this->dirDepth])) { $this->component = $this->pathParse[$this->dirDepth]; return $this->component; }else{ unset($this->component); } } /* * returns the second part of the path */ function getView() { self::pathParse(); self::dirDepth('2'); if(!empty($this->pathParse[$this->dirDepth])) { $this->view = $this->pathParse[$this->dirDepth]; return $this->view; }else{ unset($this->view); } } /* * Ummmmm need some help here for sure. */ function __destruct() { } } $uri = new uri(); Thank you in advance for your help! Similar TutorialsI am in the process of building my own MVC framework (just to learn the concepts) and I decided to throw some libraries and helpers in the mix to make things more convenient. Below is my email helper in which I want to be able to use an array as the "to" part of the mail() function. I was wondering what everyone thought of my class and if I can improve upon it. Thanks! Code: [Select] <?php /** * To use this email class in it's most basic form: * * $to must be an array even if you are sending to only one recipient. * You declare it like so: * $to = array('recipient'); * or * $to = array('one', 'two', 'three'); * $sendMail = new Email($to, 'subject', 'message'); * if ($sendMail->send()) { * // success * } else { * // failure * } * * To add various features (declare these before using $sendMail-send()): * To add a CC address: * $sendMail->setCC('email address'); * To add a BCC address: * $sendMail->setBCC('email address'); * To set the from name: * $sendMail->setFromName('name of sender'); * To set the from email: * $sendMail->setFromEmail('email of sender'); * To set a content type (default is text/html): * $sendMail->setContentType('content type'); * To set a charset (default is iso-8859-1): * $sendMail->setCharset('charset'); */ class Email { public $to = array(); public $subject; public $message; public $fromName; public $fromEmail; public $cc; public $bcc; public $contentType; public $charset; private $_headers; public function __construct($to, $subject, $message) { if (!is_null($to) && !is_array($to)) { throw new Exception('The recipient names must be an array, even if there is only one recipient.'); } if (is_null($to) || is_null($subject) || is_null($message)) { throw new Exception('There must be at least one recipient, a subject, and a message.'); } $this->to = $to; $this->subject = $subject; $this->message = $message; } public function setCC($cc = NULL) { $this->cc = $cc; } public function setBCC($bcc = NULL) { $this->bcc = $bcc; } public function setFromName($fromName = 'Website Name') { $this->fromName = $fromName; } public function setFromEmail($fromEmail = 'admin@website.com') { $this->fromEmail = $fromEmail; } public function setContentType($contentType = 'text/html') { $this->contentType = $contentType; } public function setCharset($charset = 'iso-8859-1') { $this->charset = $charset; } private function _setHeaders() { $this->_headers = "Content-type: " . $this->contentType . "charset=" . $this->charset . "\r\n"; $this->_headers .= "From: " . $this->fromName . "<" . $this->fromEmail . "> \r\n"; if ($this->cc != NULL) { $this->_headers .= "CC: " . $this->cc . "\r\n"; } if ($this->bcc != NULL) { $this->_headers .= "BCC: " . $this->bcc . "\r\n"; } } public function send() { $this->_setHeaders(); $this->setFromName(); $this->setFromName(); $sent = FALSE; foreach ($this->to as $recipient) { if (mail($recipient, $this->subject, $this->message, $this->_headers)) { $sent = TRUE; continue; } } if ($sent = TRUE) { return TRUE; } else { return FALSE; } } } As some of you know, I am still learning the fundamentals of good php code practice and have been working on a custom application for my own practice and personal schooling. My below code IS working as expected, but I wanted any ideas or critique on better, more secure, faster, etc methods of it.. Thanks for any input: <?php $id = mysqli_real_escape_string($cxn, $_GET['id']); $city_name = mysqli_real_escape_string($cxn, $_GET['city_name']); $posts_by_city_sql = "SELECT id, city_id, title FROM postings WHERE city_id='$id'"; $posts_by_city_results = (mysqli_query($cxn, $posts_by_city_sql)) or die("Was not able to grab the Postings!"); $row_cnt = mysqli_num_rows($posts_by_city_results); if ($row_cnt == 0) { printf("We're sorry. There are %d postings in: <strong>$city_name</strong>", $row_cnt); } else { printf("Congratulations! There are %d postings in: <strong>$city_name</strong>", $row_cnt); echo "<ul>"; while ($posts_by_city_row = mysqli_fetch_array($posts_by_city_results)) { echo "<li><a href='posting_details.php?id=$posts_by_city_row[id]'>$posts_by_city_row[title]</a></li>"; } // end while loop echo "</ul>"; } // end row_cnt if mysqli_free_result($posts_by_city_results); mysqli_close($cxn); ?> Hi,
I have a built a website and I want to get some feedback from the members at this forum. I can't seem to post this topic in the Website Critique forum.
Thanks
Moved by Ch0cu3r
Edited by Ch0cu3r, 10 December 2014 - 06:25 AM. Hi, I hope this is still a relevant topic here. I don't have a lot of coding experience and haven't studied it a college -- I'm just self taught hobbyist. I was wondering what your opinion is of the way I have structured my code and solved what I needed to do. Any tips or feedback is greatly appreciated. Thanks. Code: [Select] <?php $form_submission=$_POST["query"]; $lines = file('eo_dic.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES); preg_match_all('/[\w\'\ŝ\ĉ\ĵ\ŭ\ĥ\Ŝ\Ĉ\Ĵ\Ŭ\Ĥ]+|[,.;!"?-\s\\(\\)]/', $form_submission, $matches); foreach ($matches[0] as $value){ // Check if $value is a word or something else. if ($value == " " || $value == "," || $value == "." || $value == "(" || $value == ")" || $value == "!" || $value == "?" || $value == "-" || $value == ";" || $value == '"'){ echo $value; } else { // $value is a word. $titleText = array(); // store results in array. foreach ($lines as $line){ list($field1, $field2) = explode('=', $line); if (strcasecmp($field1, $value) == 0 || strcasecmp($field2, $value) == 0){ // Found string in DB. array_push($titleText, "$field1 = $field2"); // Store all finds in array before outputting. } } if (empty($titleText)) { // $value was not found -- array is empty. echo '<a name="translated" class="translated" title="Not found.">' . $value . '</a>'; } else { $arrayOut = implode(" / ", $titleText); // output the results found in the search. echo '<a name="translated" class="translated" title="' . $arrayOut . '">' . $value . '</a>'; } } } unset($value); ?> This is just my software assignment. We have to create a functioning vending machine. How does it look so far? Code: [Select] <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Vending Machine Assignment</title> <link href="vending.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="vending_machine_base"> <img src="vending_machine_base.gif" alt="Vending Machine Base" title="Vending Machine Base" /> </div> <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post"> <p>Coke<input type="radio" name="item" value="Coke" /></p> <p>Sprite<input type="radio" name="item" value="Sprite" /></p> <p>Fanta<input type="radio" name="item" value="Fanta" /></p> <input type="text" size="15" name="quantity" value="Enter quantity here" /> $<input type="text" value="Enter your financial balance." name="credit_input" size="23" /> <input type="submit" value="Submit" /> </form> <?php error_reporting(E_ALL); // Cost of items $coke_price = "1.25"; $sprite_price = "1.50"; $fanta_price = "1.75"; // Quantity of items $coke_quantity = "7"; $sprite_quantity = "5"; $fanta_quantity = "3"; // Selected radio button into variable $selected_item = $_POST['item']; // Credit into variable $credit = $_POST['credit_input']; // If funds are less than price, dispay error message if (($_POST['submit']) && ($selected_radio = 'coke') && ($credit >= $coke_price)) { echo "You have purchased a $selected_item!"; } else { echo "You do not have sufficient funds to purchase a $selected_item."; } if (($_POST['submit']) && ($selected_radio = 'sprite') && ($credit >= $sprite_price)) { echo "You have purchased a $selected_item!"; } else { echo "You do not have sufficient funds to purchase a $selected_item."; } if (($_POST['submit']) && ($selected_radio = 'fanta') && ($credit >= $fanta_price)) { echo "You have purchased a $selected_item!"; } else { echo "You do not have sufficient funds to purchase a $selected_item."; } // Item quantity if (($_POST['submit']) && ($coke_quantity = 0)) { echo ""; } else { echo "Coke resources depleted."; } if (($_POST['submit']) && ($sprite_quantity = 0)) { echo ""; } else { echo "Sprite resources depleted."; } if (($_POST['submit']) && ($fanta_quantity = 0)) { echo ""; } else { echo "Fanta resources depleted."; } // Item cost subtracted from credit if (($coke_quantity >= 1) && ($credit >= $coke_price)) { $coke_price - $credit; } if (($sprite_quantity >= 1) && ($credit >= $sprite_price)) { $sprite_price - $credit; } if (($fanta_quantity >= 1) && ($credit >= $fanta_price)) { $fanta_price - $credit; } // Funds available echo "Your current funds accumlate to $credit "; ?> </body> </html> I'm developing my own CMS with a few functions and wanted to know how things are looking right now because I can't find a board for strickly CODING CRITIQUE so I put it in this board. There isn't a whole lot to go through. I know there is something wrong with my issets line but other than that just a general critique of how its shaping up? manager.php <?php session_start(); require "dbconfig.php"; require "functions.php"; if ((isset($_POST['username'])) && (isset($_POST['password']))) { $username = $_POST{'username'}; $password = SHA1($_POST{'password'}); validate($username, $password); } elseif ((!(isset('username'))) && (!(isset('password')))) { require_once "login.php"; } $username = stripslashes($username); $password = stripslashes($password); $username = mysql_real_escape_string($username); $password = mysql_real_escape_string($password); $sql="SELECT * FROM dbusers WHERE username='$username' and password='$password'"; $result = mysql_query($sql); ?> functions.php <?php // This page defines functions used by the login/logout process function validate($username, $password) { } ?> login.php <?php include_once ("globals.php"); ?> <html> <head> <title><?php echo $shortsitename; ?> EW Manager</title> <link rel="stylesheet" type="text/css" href="<?php echo "$stylesheet"; ?>" /> </head> <body> <p id="backtosite"><a href="#" title="Are you lost?">← Back to <?php echo $fedname ?></a></p> <div id="login"> <h1><?php echo $shortsitename; ?> Manager</h1> <form id="loginform" action="" method="POST"> <p><label>Username<br /><input type="text" name="username" id="user_login" class="input" size="15" /></label></p> <p><label>Password<br /><input type="password" name="password" id="user_pass" class="input" size="15" /></label></p> <p class="forgetmenot"><label><input name="rememberme" type="checkbox" id="rememberme" /> Remember Me</label></p> <p class="submit"> <input type="submit" value="Login" class="button-primary" /> </p> </form> </div> </body></html> Hello, My script below IS finally working, but I was hoping for some aggressive, anal comments for critique. Keep in mind, I am developing for a php4 platform otherwise I would have used a newer php5 validation function. <?php if (isset($_POST['btnSubmit'])) { $first_name = mysql_real_escape_string($_POST['fname']); $last_name = mysql_real_escape_string($_POST['lname']); $title = mysql_real_escape_string($_POST['title']); $company = mysql_real_escape_string($_POST['company']); $address1 = mysql_real_escape_string($_POST['address1']); $address2 = mysql_real_escape_string($_POST['address2']); $city = mysql_real_escape_string($_POST['city']); $zip = mysql_real_escape_string($_POST['zip']); $phone = mysql_real_escape_string($_POST['phone']); $fax = mysql_real_escape_string($_POST['fax']); $email = mysql_real_escape_string($_POST['email']); if (!preg_match("/^[A-Za-z' -]{1,75}$/", $first_name)) { $error[] = "Please enter a valid first name."; } if (!preg_match("/^[A-Za-z' -]{1,75}$/", $last_name)) { $error[] = "Please enter a valid last name."; } if ($first_name === $last_name && $first_name != "") { $error[] = "First Name and Last Name cannot be the same."; } if (!preg_match("/^[A-Za-z' -]{1,150}$/", $company)) { $error[] = "Please enter a valid company name."; } if (!preg_match("/^[A-Za-z' -.]{1,150}$/", $title)) { $error[] = "Please enter a valid Title."; } if (!preg_match("/^[A-Za-z0-9' - . ]{1,150}$/", $address1)) { $error[] = "Please enter a valid mailing address."; } if (!preg_match("/^[A-Za-z0-9' - . ]{1,150}$/", $city)) { $error[] = "Please enter a valid city."; } if (!preg_match("/^[0-9' - . ( ) ]{1,150}$/", $phone)) { $error[] = "Please enter a valid phone number."; } if (!preg_match("/^[0-9' - . ( ) ]{1,150}$/", $fax)) { $error[] = "Please enter a valid fax number."; } if (!preg_match("/([a-z][a-z0-9_.-\/]*@[^\s\"\)\?<>]+\.[a-z]{2,6})/i", $email)) { $error[] = "Please enter a valid email address in the format: start@middle.end."; } if (is_array($error)) { echo "<div id='errorWrapper'><h2>There are errors in your input. Please correct the following fields:</h2>"; foreach ($error as $err_message) { echo "<span class='errorText'> >> $err_message" . "</span><br />"; } echo "</div>"; include('../includes/attendee_registration_form.php'); // this is the form exit(); } else { include('../includes/attendee_registration_mailer.php'); // this send the email and populates the table } } else { include('../includes/attendee_registration_form.php'); // this is the form exit(); } ?> I am after some advice about doing some rather basic things that wouldnt really be done in OOP and see if there's a better way of doing this. As I just said though I know this is not the required system just one displaying of a form but I think its really cool for just simplying OOP ( ), and I actually understand it, I always need to start off small, understand it all, before I start waffling will show you my code (in no way finished yet, as you can tell from some of the html elements but its principle works: <?php ini_set('display_errors',1); class Form{ public $to; public $user; public $email; public $subject; public $comment; function showForm(){ // displaying of form to the user: echo <<<userform <html> <head> <title>Jez's Contact Form</title> </head> <body> <form id="contact" name="contact" method="post" action="{$_SERVER['PHP_SELF']}"> <label for="">Enter something:</label><input type="text" id="user" </form> </body> </html> userform; } } if(!array_key_exists('submit',$_POST)) { $myForm = new Form; // now we construct the form: $myForm->showForm(); // print_r($myForm); } ?> If a submit button in the form hasnt been hit, then show form, later on going to do and try out some validation, just wanted some advice before I get too big for my boots as such. Any advice on improving it (obviously finishing my form off of course which is what I will do), but any further advice is greatly appreciated, Jez. All criticism/suggestions/improvements appreciated Registration.php Code: [Select] <?php $con = mysql_connect("localhost","","") or die(mysql_error()); mysql_select_db('Users'); if(isset($_COOKIE['ID_my_site'])) { $cookie_username = mysql_real_escape_string(filter_input(INPUT_COOKIE, 'ID_', FILTER_SANITIZE_FULL_SPECIAL_CHARS)); $cookie_password = sha1($_COOKIE['Key_']); $cookie_check = mysql_query("SELECT * FROM Users WHERE username = '$cookie_username'") or die(mysql_error()); $cookie_results = mysql_fetch_array($cookie_check); if ($cookie_password == $cookie_results['Password']) { echo "<div id=\"login_msg\">You are already logged on. Redirecting...</div><br />" && header("location:/index.php"); } } if(isset($_POST['submit'])) { $Username = mysql_real_escape_string(filter_input(INPUT_POST, 'Username', FILTER_SANITIZE_FULL_SPECIAL_CHARS)); $Email = mysql_real_escape_string(filter_input(INPUT_POST, 'Email', FILTER_SANITIZE_FULL_SPECIAL_CHARS)); $Password = sha1($_POST['Password']); $Password2 = sha1($_POST['Password2']); if (!$Username | !$Email | !$Password | !$Passord2) { echo "<div id=\"error_msg\">You did not complete all of the required fields, please try again.</div><br />"; } if ($Password != $Password2) { echo "<div id=\"error_msg\">Your passwords do not match, please try again.</div><br />"; } $check_username = mysql_query("SELECT * FROM Users WHERE (Username = $Username)"); $result_username = mysql_fetch_row($check_username); $check_email = mysql_query("SELECT * FROM Users WHERE (Email = $Email)"); $result_email = mysql_fetch_row($check_email); if ($result_username == true) { echo "<div id=\"error_msg\">The Username: '$Username', already exists. Please enter another username.</div><br />"; } if ($result_email == true) { echo "<div id=\"error_msg\">The Email Adress: '$Email', is already in our Database.</div><br />"; } $sql = "INSERT INTO Users (Id, Username, Email, Password) VALUES ('', '$Username','$Email','$Password')"; $add_member = mysql_query($sql) or die(mysql_error()); if (mysql_query($add_member)) { $week = time() + 604800; setcookie(ID_, $_POST['Username'], $week); setcookie(Key_, $_POST['Password'], $week); echo "<div id=\"login_msg\">Successfully added to our Database.</div><br />" && header ("location:/Login.php"); } else { echo "<div id=\"error_msg\">Invalid input.</div><br />"; } } ?> Login.php Code: [Select] <?php include("db.php"); if(isset($_COOKIE['ID_my_site'])) { $cookie_username = mysql_real_escape_string(filter_input(INPUT_COOKIE, 'ID_', FILTER_SANITIZE_FULL_SPECIAL_CHARS)); $cookie_password = sha1($_COOKIE['Key_']); $cookie_check = mysql_query("SELECT * FROM Users WHERE username = '$cookie_username'") or die(mysql_error()); $cookie_results = mysql_fetch_array($cookie_check); if ($cookie_password == $cookie_results['Password']) { echo "<div id=\"login_msg\">You are already logged on. Redirecting...</div><br />" && header("location:/index.php"); } } if(isset($_POST['submit'])) { $Username = mysql_real_escape_string(filter_input(INPUT_POST, 'Username', FILTER_SANITIZE_FULL_SPECIAL_CHARS)); $Password = sha1($_POST['Password']); if (!$Username | !$Password) { echo "<div id=\"error_msg\">You did not complete all of the required fields, please try again.</div><br />"; } $sql = "SELECT * FROM Users WHERE (Username, Password) = ('$Username', '$Password')"; $db_check = mysql_num_rows($sql) or die(mysql_error()); if (mysql_query($db_check)) { $week = time() + 604800; setcookie(ID_, $cookie_username, $week); setcookie(Key_, $cookie_password, $week); echo "<div id=\"login_msg\">Successfully Logged In.</div><br />" && header ("location:/index.php"); } elseif (($Username | $Password) != $db_check) { echo "<div id=\"error_msg\">Invalid username or password, please try again.</div><br />"; } } ?> Logout.php Code: [Select] <?php include("db.php"); if(isset($_COOKIE['ID_my_site'])) { $cookie_username = mysql_real_escape_string(filter_input(INPUT_COOKIE, 'ID_', FILTER_SANITIZE_FULL_SPECIAL_CHARS)); $cookie_password = sha1($_COOKIE['Key_']); $cookie_check = mysql_query("SELECT * FROM Users WHERE username = '$cookie_username'") or die(mysql_error()); $cookie_results = mysql_fetch_array($cookie_check); if ($cookie_password != $cookie_results['Password']) { header("location:/login.php"); } else { $past = time() - 604800; setcookie(ID_, gone, $past); setcookie(Key_, gone, $past); echo "<div id=\"error_msg\">Sucessfully logged out. Good Bye!</div><br />" && header ("location:/login.php"); } } ?> Part of my class: using PHP5 ( http://php.net/manua...ssword-hash.php) If you know of anything new in PHP5 related to please do share
protected function create_hash($string){ $password = "#" . strrev($password); $grs = $this->grs("|WordToTheWise",rand(22, 50)); $hash = password_hash("_" . strrev($string), PASSWORD_BCRYPT, array('cost'=>rand(4,14),'salt'=>$grs)); return strrev($hash); } public function verifyhash($string, $hash_string){//verifies that the hash is equal to the password return (password_verify("_" . strrev($string), strrev($hash_string)) ? true : false); } private function grs($string_append = "", $length = 22) { $length = $length - strlen($string_append); $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@#$%^&()_*,./;[]|'; $randomString = ''; for ($i = 0; $i < $length; $i++) { $randomString .= $characters[rand(0, strlen($characters) - 1)]; } return $randomString . $string_append; }Okay so u use strrev on my string and hash just to make everything a bit more CONFUSING and i append the string with a "]" just to make the password harder to brute the strrev and append string is not meant to make the hash any more secure. I store the reversed hash in my DB as a varchar The point of the reverse hash is only to make the hash a little more unrecognizable to the human eye. The Const is randomly chosen 4 - 14, and the salt is randomly generated with a special string appended. How would you improve the hashing? Edited by Richard_Grant, 09 September 2014 - 11:48 PM. Hello. I have written this script where user restaurant owner can add his place to the database of all local restaurants. (insert basic information into database, add up to 3 images, thumbnail creation, insert image information to database). It works well on localhost, but i would like some suggestions for improvement. Im not very sure of its structure, it may not execute well once it is online. And i also think there are too many "IF's". But i really have no idea how to do it any other way. Thanks for all the suggestions. Code: [Select] <?php if(!defined('PROTECTION') || constant('PROTECTION') != 'demover') { echo "fuck off intruder!"; exit; } $naziv = mysql_real_escape_string($_POST['Naziv']); $naslov = mysql_real_escape_string($_POST['Naslov']); $kraj = mysql_real_escape_string($_POST['Kraj']); $telefon = mysql_real_escape_string($_POST['Telefon']); $web = "http://www.".mysql_real_escape_string($_POST['Spletna']); $gm = mysql_real_escape_string($_POST['Lokacija']); //$gmaps = gmParse($gm); $gmaps = 10; $fill="INSERT INTO bpoint (sName, sAddr, placeID, sPhone, sWeb, sGMaps, companyID) VALUES ('$naziv','$naslov','$kraj','$telefon','$web','$gmaps','$cID')"; if (mysql_query($fill)) { $lastID=mysql_insert_id(); $path="./truck/".$cID."/".$lastID; $pname=$_FILES["pic"]["tmp_name"]; $num=0; if (count($_FILES["pic"]) && mkdir($path, 0777)) { include "thumbs.php"; foreach($pname as $imag){ $bname=date("YmdHis").$num; $num++; $finalpath=$path."/".$bname.".jpg"; $finalthumb=$path."/".$bname."_thumb.jpg"; if($imag!="") { if (move_uploaded_file($imag, $finalpath)) { make_thumb($finalpath,$finalthumb,150); mysql_query("INSERT INTO images (name, companyID) VALUES ('$finalpath', '$cID')"); } } } } unset($_FILES["pic"]); } else {die(mysql_error());} ?> I need to secure my code more Code: [Select] $_POST['amount'] = intval($_POST['amount']); if ($_POST['amount'] <= 0){ message($lang_common['Bad request']); } if (!is_numeric($_POST['amount'])){ message($lang_common['Bad request']); } $_POST['amount'] will be the amount of gold people will beable to send to each other. any sql injections vulnerability right now? if so, help i casted my intval and is_numeric on it any other ways to secure it with php functions as of right now it can only be numeric right? This contact form works fairly well, but I do get spam.
Can you add something to this existing form that will make it a little better at not letting spam thru?
<form action="../page.php?page=1" method="post" name="contact_us" onSubmit="return capCheck(this);"> <table cellpadding="5" width="100%"> <tr> <td width="10" class="required_field">*</td> <td width="80">Name</td> <td><input type="text" name="name" maxlength="50" style="width:400px; border: 1px solid #696969;" /><br /><br /></td> </tr> <tr> <td class="required_field">*</td> <td>Email Address</td> <td><input type="text" name="email" maxlength="40" style="width:400px; border: 1px solid #696969;" /><br /><br /></td> </tr> <tr> <td></td> <td>Subject:</td> <td><input type="text" name="subject" maxlength="40" style="width:400px; border: 1px solid #696969;"/><br /><br /></td> </tr> <tr> <td class="required_field">*</td> <td>Enter Image Code:</td> <td><input type="text" value="" name="captext" style="width: 100px" maxlength="6" /></td> </tr> <tr> <td></td> <td><a onclick="refresh_security_image(); return false;" style="cursor:pointer;"><u>Refresh Image</u></a></td> <td><img src="../includes/captcha.php" border="0" id="verificiation_image" /></a></td> </tr> </table> <br/> <p> <input type="hidden" name="submited" value="1" /> <input type="submit" name="submit" value="Submit" style="margin:7px 10px 0px 0px; padding:10px 0px 10px 0px; font-size:15px; font-style:Century-Gothic;" /> </p> </form> </td> </tr> </table> </div> <script type="text/javascript"> <!-- function refresh_security_image() { var new_url = new String("../includes/captcha.php?width=132&height=36&charcators="); new_url = new_url.substr(0, new_url.indexOf("width=") + 37); // we need a random new url so this refreshes var chr_str = "123456789"; for(var i=0; i < 6; i++) new_url = new_url + chr_str.substr(Math.floor(Math.random() * 2), 1); document.getElementById("verificiation_image").src = new_url; } --> </script> <!-- captch start --> <script type="text/javascript" id="clientEventHandlersJS" language="javascript"> </script> <!-- captch end -->Thanks Hi Guys, I have a simple PHP search facility (Below this post) for my customer system which uses a input form so users enter a customers name/telephone/address and it echos the result. Its great but I observed as my customer table got bigger the search got less accurate, what i mean is when you search for mr test is give ur mr test along with mr andy and ms danielle. Its ok but those any know how to make my search code better or can y'all help me with a better php search script. Thanks. <?php $query=$_GET['query']; $query= str_replace("'","",$query); // Change the fields below as per the requirements $db_host="localhost"; $db_username="root"; $db_password=""; $db_name=""; $db_tb_name="customer"; $db_tb_atr_name="c_name"; $query= str_replace("'","",$query); //Now we are going to write a script that will do search task // leave the below fields as it is except while loop, which will display results on screen mysql_connect("$db_host","$db_username","$db_password"); mysql_select_db("$db_name"); $query_for_result=mysql_query("SELECT * FROM customer WHERE c_name like '%".$query."%' OR c_telephone like '%".$query."%' OR c_address like '%".$query."%'"); while($row=mysql_fetch_assoc($query_for_result)) { $c_id = $row['c_id']; $c_name = $row["c_name"]; $c_address = $row["c_address"]; $c_postcode = $row["c_postcode"]; $c_city = $row["c_city"]; $c_telephone = $row["c_telephone"]; $c_email = $row["c_email"]; $salesman = $row["salesman"]; echo '<table width="100%" border="0"> <tr> <td><a href="customers.php?id=' . $c_id . '"> ' . $c_name . '</a> - ' . $c_address . ' - ' . $c_city . ' - ' . $c_telephone . '• <a href="customer_edit_index.php?pid=' . $c_id . '">edit</a><br /><br/></td> </tr> </table>'; } mysql_close(); ?> Please feel free to use this code in any way if you need to: I will appreciate any help in rewriting this code to improve it by showing ellipsis. The way the code is now shows this: Previous 1 2 3 4 5 6 7 8 9 10 Next I would like some help in rewriting the code so that we can get an ellipsis and show something like this: Previous 1 ... 4 5 6 7 ... 10 Next Please post your improved version of this code (showing the ellipsis). I would like for it to work when sorting as well thats why the ' &sort=' . $sort . is included in the code. Thank you in advance. Code: [Select] <?php //Number of records from query to display per page $display = 20 ; //Write your code to sort in here and store it $sort if ( isset($_GET['np'])) { // Already been determined. $num_pages = $_GET['np']; } else { //Now we count the number of records in the query $query = "SELECT COUNT(*) FROM postings ORDER BY posted_date DESC"; $result = mysql_query($query); $row = mysql_fetch_array($result, MYSQL_NUM); $num_records = $row[0]; //Now we calculate the number of pages if ($num_records > $display) { //More than 1 page $num_pages = ceil ($num_records/$display); } else { $num_pages = 1; } } // End of np IF //Determine where in the database to start returning results if (isset($_GET['s'])) { $start = $_GET['s']; } else { $start = 0; } //Add code for query here $query = //whatever you need from the database tables while { // show the results from query here } if ($num_pages > 1) { echo '<br /><p>' ; $current_page = ($start/$display) + 1 ; //If it is not the first page, then we make a previous button. if ($current_page != 1 ) { echo ' <a href="viewpostings.php?s=' . ($start - $display) . '&np=' . $num_pages . ' &sort=' . $sort . '">Previous </a>'; } //Make all the numbered pages. for ($i = 1; $i <= $num_pages; $i++) { if ($i != $current_page) { echo '<a href="viewpostings.php?s=' . (($display * ($i - 1 ))) . '&np=' . $num_pages . ' &sort=' . $sort . '"> ' . $i . ' </a>'; } else { echo $i. ' '; } } //If it is not the last page, then we make a Next button; if ($current_page != $num_pages) { echo '<a href="viewpostings.php?s=' . ($start + $display) . '&np=' . $num_pages . ' &sort=' . $sort . '">Next</a>'; } echo '</p>'; } ?> I have a download youtube site http://downloadvideoasmp3.com/ I would like to review an tell me what can be done to be improved. I have started learning OOP, by following a few tutorials, My problem with most tutorial is they show you how, but don't tell you the what and the why. It's all good an well seeing what to do, but if you have no idea why it's being done, you don't learn much. I started a tutorial on Udemy but am not actually gaining a lot from it. I want to alter the code so that it will do it the way I want it to. I am not wanting you to write the code for me, if you do please explain it so that I can understand the logic, preferably show me where to make changes and point me at the php tutorial that can solve my problem. I have been trying to solve this for a couple of weeks now, I tried a few things but none worked.
The full followLinks function function followLinks($url) { global $alreadyCrawled; global $crawling; $host = parse_url($url)["host"]; $parser = new DomDocumentParser($url); $linkList = $parser->getLinks(); foreach($linkList as $link) { $href = $link->getAttribute("href"); if((substr($href, 0, 3) !== "../") AND (strpos($href, $host) === false)) { continue; } else if(strpos($href, "#") !== false) { continue; } else if(substr($href, 0, 11) == "javascript:") { continue; } // I need to change this below somehow, the two arrays are identical, // What I want to do is move $href(crawled) to $alreadyCrawled and remove it from $crawling // I also want to check if the current $href (crawling) is in $alreadyCrawled and if it is skip crawling and move on to the next one. //In essence I want to prevent the crawler from crawling anything already crawled in order to speed up the crawler. $href = createLink($href, $url); if(!in_array($href, $alreadyCrawled)) { $alreadyCrawled[] = $href; $crawling[] = $href; } else { continue;} echo $href . "<br>"; } array_shift($crawling); foreach($crawling as $site) { followLinks($site); } } $startUrl = "https://imagimedia.co.za"; followLinks($startUrl); ?>
Result.
https://imagimedia.co.za/../seo/ https://imagimedia.co.za/../pages/marketing.html https://imagimedia.co.za/../pages/web-design.html http://imagimedia.co.za/ https://imagimedia.co.za/../website-cost-quote.php https://imagimedia.co.za/../blogs/history.html https://imagimedia.co.za/../blogs/payment.html https://imagimedia.co.za/../blogs/copy.html https://imagimedia.co.za/../blogs/cycle.html https://imagimedia.co.za/../blogs/information.html https://imagimedia.co.za/../blogs/privacy.html https://imagimedia.co.za/../blogs/terms.html https://imagimedia.co.za/../blogs/content-is-king.html https://imagimedia.co.za/../blogs/pretoria-north-web-design.html https://imagimedia.co.za/../blogs/annlin-web-design.html https://imagimedia.co.za/../blogs/ http://imagimedia.co.za http://imagimedia.co.za/../seo/ http://imagimedia.co.za/../pages/marketing.html http://imagimedia.co.za/../pages/web-design.html http://imagimedia.co.za/../website-cost-quote.php http://imagimedia.co.za/../blogs/history.html http://imagimedia.co.za/../blogs/payment.html http://imagimedia.co.za/../blogs/copy.html http://imagimedia.co.za/../blogs/cycle.html http://imagimedia.co.za/../blogs/information.html http://imagimedia.co.za/../blogs/privacy.html http://imagimedia.co.za/../blogs/terms.html http://imagimedia.co.za/../blogs/content-is-king.html http://imagimedia.co.za/../blogs/pretoria-north-web-design.html http://imagimedia.co.za/../blogs/annlin-web-design.html http://imagimedia.co.za/../blogs/ I know I am also going to have to exclude duplicates created by the http and https pages. But that is not my main issue. I have mysqli object in Database class base: [color=]database class:[/color] class Database { private $dbLink = null; public function __construct() { if (is_null($this->dbLink)) { // load db information to connect $init_array = parse_ini_file("../init.ini.inc", true); $this->dbLink = new mysqli($init_array['database']['host'], $init_array['database']['usr'], $init_array['database']['pwd'], $init_array['database']['db']); if (mysqli_connect_errno()) { $this->dbLink = null; } } } public function __destruct() { $this->dbLink->close(); } } Class derived is Articles where I use object dBLink in base (or parent) class and I can't access to mysqli methods (dbLink member of base class): Articles class: require_once ('./includes/db.inc'); class Articles extends Database{ private $id, .... .... $visible = null; public function __construct() { // Set date as 2009-07-08 07:35:00 $this->lastUpdDate = date('Y-m-d H:i:s'); $this->creationDate = date('Y-m-d H:i:s'); } // Setter .... .... // Getter .... .... public function getArticlesByPosition($numArticles) { if ($result = $this->dbLink->query('SELECT * FROM articles ORDER BY position LIMIT '.$numArticles)) { $i = 0; while ($ret = $result->fetch_array(MYSQLI_ASSOC)) { $arts[$i] = $ret; } $result->close(); return $arts; } } } In my front page php I use article class: include_once('./includes/articles.inc'); $articlesObj = new articles(); $articles = $articlesObj->getArticlesByPosition(1); var_dump($articles); [color=]Error that go out is follow[/color] Notice: Undefined property: Articles::$dbLink in articles.inc on line 89 Fatal error: Call to a member function query() on a non-object in articles.inc on line 89 If I remove constructor on derived class Articles result don't change Please help me Ok. I know you can pass the object of a class as an argument. Example: class A { function test() { echo "This is TEST from class A"; } } class B { function __construct( $obj ) { $this->a = $obj; } function test() { $this->a->test(); } } Then you could do: $a = new A(); $b = new B($a); Ok so that's one way i know of. I also thought that you could make a method static, and do this: (assuming class A's test is 'static') class B { function test() { A::test(); } } But that is not working. I'd like to know all possible ways of accomplishing this. Any hints are appreciated. thanks Hi Can you call Class A's methods or properties from Class B's methods? Thanks. |