Recent Entries 10
- pattern minor 112d agoInserting users using PDO prepared statementsI made a small script to update fields in a database. I'm using PDO to connect to MySQL. All the business logic of PHP is in the top half of the file, and the form is at the bottom. Here is the full code. If it's a POST request, it opens the PDO connection and inserts the values from the form. ``` prepare($sql); $statement->execute(array( "firstname" => $_POST['firstname'], "lastname" => $_POST['lastname'], "email" => $_POST['email'], "age" => $_POST['age'], "location" => $_POST['location'] )); } catch(PDOException $error) { echo $sql . "" . $error->getMessage(); } } ?> Update Users Add a user First Name Last Name Email Address Age Location ``` I know I can sanitize HTML input by doing something like: ``` function escape($html) { return htmlspecialchars($html, ENT_QUOTES | ENT_SUBSTITUTE, "UTF-8"); } // example use escape($_POST['firstname']); ``` I'm wondering how necessary it is when I'm using a prepared statement. I'm still a bit confused about sanitization and filtering, and when it's necessary. I know it's necessary when printing data out to HTML, but not sure how much when receiving input to PDO. Please forgive any and all ignorance. I'm writing this from scratch and doing my best to teach myself PHP without frameworks.
- pattern minor 112d agoUser Avatar uploadI have been looking at some coding videos on Laracasts and the focus seems to be very readable code and keeping the controller clean. How can I clean this up? This code takes an uploaded user avatar, stores the avatar image on the file system and stores the name in a database. ``` public function update(Request $request, $id) { $this->validate($request, [ 'avatar' => 'required|image|max:10000|mimes:jpg,jpeg,gif,bmp,png' ]); $UploadedFile = $request->file('avatar'); $name = renameFile($UploadedFile); // helper function. $user = User::where('id', '=', $id)->first(); if(!is_null($user->avatar)){ // avatar's name stored in user table Storage::disk('public')->delete('avatars/' . $user->avatar); }; $image = Image::make($UploadedFile) ->resize(400, null, function ($constraint) { $constraint->aspectRatio(); } ) ->encode('jpg', 80); Storage::disk('public')->put('avatars/' . $name, $image); $user->avatar = $name; $user->save(); return back()->with(message('User Profile Photo has been updated!', 'success')); }; ``` It works fine. It's just the presentation that's bothering me. I have looked into repositories, interfaces etc but can't seem to figure out when to use what.
- pattern minor 112d agoHTTP redirects after login, registration, and logoutI am using following classes/interface to redirect user (after login, register, logout etc.) File: RedirectInterface.php ``` interface RedirectInterface { public function getUrl($customerId = null); } ``` File: LoginRedirect.php ``` class LoginRedirect implements RedirectInterface { public function getUrl($customerId = null) { // do some business logic here to get url $url = '/account/some-customer'; return $url; } } ``` File: RegisterRedirect.php ``` class RegisterRedirect implements RedirectInterface { public function getUrl($customerId = null) { // do some business logic here to get url $url = '/welcome/some-customer'; return $url; } } ``` File: RedirectFactory - Creational design pattern (static factory) ``` class RedirectFactory { public static function build($type, $customerId) { if ($type == 'login') { return new LoginRedirect($customerId); } else if ($type == 'register') { return new RegisterRedirect($customerId); } throw new InvalidArgumentException ('Invalid redirect type.'); } } ``` Usage: ``` // 1. Usage: Somewhere in customer registration code $redirectUrl = RedirectFactory::build('register', 102)->getUrl(); header('Location: ' . $redirectUrl); // 2. Usage: Somewhere in customer login code $redirectUrl = RedirectFactory::build('login', 102)->getUrl(); header('Location: ' . $redirectUrl); ``` If you were given a chance to refactor this code. How would you have re-developed it?
- pattern minor 112d agoCompress svg files in PHPI wrote something to "compress" svg files. The svg files I am using often have comments and empty `` tags, and I want to remove them. My main goal is not the speed of the compression, but the size of the compressed svg file. Here is an example svg file: https://image.flaticon.com/icons/svg/222/222436.svg And here is the code I am using: ``` public function compress($svg) { $svg = preg_replace('//', '', $svg); $svg = preg_replace('/[\n\r\s]*/', '', $svg); $svg = preg_replace('/\n/', ' ', $svg); $svg = preg_replace('/\t/', ' ', $svg); $svg = preg_replace('/\s\s+/', ' ', $svg); $svg = str_replace('> <', $svg); $svg = str_replace(';"', '"', $svg); return $svg; } ``` - Do you see any dangers here, perhaps this could ruin some svg files? - Is there something I could do to compress the file even more? - Is there any way to speed this up?
- pattern minor 112d agoSeparating PHP code and logicI am new to OOP and slowly starting to learn it to increase my PHP. This is my first attempt at writing something using OOP. Now people always talk about separating the logic and php code from the HTML / views. This is a rather difficult concept for me to grasp thus, I tried making my own little MVC "framework" simply to fool around in an attempt to learn new concepts. I came up with the following. CONTROLLER ``` require_once("../config/db.php"); class Employer { public $name, $location, $email; private $password; function setPword($newPword){ $this->password = $newPword; } function getPword(){ return $this->password; } function setEmployerName($newName) { $this->name = $newName; } function getEmployerName() { return $this->name; } function getEmployerFirstname(){ $fullname = $this->getEmployerName(); $fullname = explode(' ', $fullname); return $firstname = $fullname[0]; } function getEmployerLastName(){ $fullname = $this->getEmployerName(); $fullname = explode(' ', $fullname); return $lastname = $fullname[1]; } function setEmail($newEmail){ $this->email = $newEmail; } function getEmail(){ return $this->email; } public function isRegistered(){ global $db; $email = $this->getEmail(); $sql="SELECT email FROM users WHERE email = :email"; $stmnt = $db->prepare($sql); $stmnt->bindValue(":email", $email); $stmnt->execute(); $stmnt->fetchAll(); if($stmnt->rowCount() > 0){ return die("Email Already Registered"); } return ''; } function registerNewEmployer(){ global $db; try { $firstname = $this->getEmployerFirstname(); $lastname = $this->getEmployerLastName(); $email = $this->getEmail(); $location = $this->getLocation(
- debug minor 112d agoMy PHP function that reads names and attempts to fix the suffixesI am reading a text file that has some name inconsistencies. For example I have names like: ``` MILLERS, WALTER M IV DUPONTE, THOMAS B. II HARDIWAY, GRANT U. SR. GUIDRY, PAUL JOHN ``` As you can see I can split the name by first name and last name however the suffixes are placed incorrectly. Ideally the names should be: ``` WALTER M MILLERS IV THOMAS B. DUPONTE II GRANT U. HARDIWAY SR. PAUL JHN GUIDRY ``` That being said this is what I have but I feel Im over complicating something simple. Any tips? Also my logic does not account for the suffix of V since that could be a middle initial also. ``` private function extractFullName($name){ $suffix = collect(['II', 'III', 'IV', 'JR.', 'SR.']); // lets first assemble a full name from the row $fullNameArray = explode(",", $name); $firstName=trim($fullNameArray[1]); $lastName=trim($fullNameArray[0]); //lets look at the FIRST NAME for II/III/IV/JR./SR. $suffix->each(function ($item, $key) use ($firstName, $lastName) { if (strpos($firstName, " ".$item)){ $firstName = preg_replace('/ '.$item.'$/', '', $firstName); $lastName.=' '.$item; return false; } }); //Basically arranging it in a 'firstname lastname II/III/IV/JR./SR.' format $name = $firstName." ".$lastName; $name = ucwords(strtolower($name)); return $name; } ```
- pattern minor 112d agoNoughts and Crosses winner declaration in a game of variable square board sizeI have made a tic tac toe for two players and written down some functions to do the decision making about who is the winner. I have gone through some cases while testing but need advice to see if I am in the right track and also if all the winning positions are being taken care of. I would like to know even if this can be simplified. Here: `$state = ["✘","-","-","-","-","✘","-","-","-","-","✘","-","-","-","-","✘"]` The function is for grids starting from 3X3 to 7X7. PHP ``` function whoIsWinning($state) { $n = sqrt(count($state)); $rows = $this->isWin($state, $this->genPaths($n, 0, 1, $n, $n)); $cols = $this->isWin($state, $this->genPaths($n, 0, $n, 1, $n)); $diUp = $this->isWin($state, $this->genPaths(1, $n-1, $n-1, 0, $n)); $diDn = $this->isWin($state, $this->genPaths(1, 0, $n+1, 0, $n)); if ($rows !== '-') return $rows; if ($cols !== '-') return $cols; if ($diUp !== '-') return $diUp; return $diDn; } /** * Function to generate the paths to win * @param $count * @param $start * @param $incrementA * @param $incrementB * @param $lengthToWin * @return array */ function genPaths($count, $start, $incrementA, $incrementB, $lengthToWin) { $paths = []; if($lengthToWin > 3) { $lengthToWin = $lengthToWin - 1; } for ($i = 0; $i isPathWin($state, $paths[$i]); if ($currentPathResult != '-') return $currentPathResult; } return '-'; } /** * @param $state * @param $path * @return string */ function isPathWin($state, $path) { $first = $state[$path[0]]; for ($j = 1; $j < count($path); $j++) { $compareToFirst = $state[$path[$j]]; if ($compareToFirst != $first) return '-'; } return $first; } ```
- pattern minor 112d agoFunction to get URLThis is a function I wrote which has the intention of extracting bits of the URL. For the latest version visit my GitHub. ``` function getPage($options = "", $page = "") { $self = "{$_SERVER["REQUEST_SCHEME"]}://{$_SERVER["HTTP_HOST"]}{$_SERVER["REQUEST_URI"]}"; /* * - return the string untouched * a - return the page name, extension, and get variables * b - no extension, no get variable * c - url up to extension, no get variable * d - all get variables (everything after "?" excludes the "?") (if no "?" then sets to "") * e - domain name e.g. google * f - full domain without any page information e.g. http://www.google.com * g - full domain e.g. http://www.google.com/search?q=query (overwrites all other options) */ if (empty($options)) return $self; $options = str_split($options); $page = ($page !== "") ? $page : $self; if (in_array("a", $options)) $page = substr($page, strrpos($page, "/") + 1); if (in_array("b", $options)) $page = substr($page, 0, strrpos($page, ".php")); if (in_array("c", $options)) $page = substr($page, 0, strrpos($page, "?")); if (in_array("d", $options)) $page = (strpos($page, "?")) ? substr($page, strrpos($page, "?") + 1) : ""; if (in_array("e", $options)) $page = (strpos($page, "www.")) ? substr($page, strpos($page, "www.") + 4, strpos($page, ".", strpos($page, "www.")) + 4) : ((strpos($page, "/localhost/")) ? substr($page, strpos($page, "://") + 3, strpos($page, "localhost/") + 2) : (strpos($page, "www") ? substr($page, strpos($page, "://") + 3, strlen($page) - strpos($page, "www.") + 5) : substr($page, strpos($page, "://") + 3, strpos($page, ".") - strpos($page, "://") - 3))); if (in_array("f", $options)) if (preg_match("/^(?:https?:\/\/)?(?:[^@\n]+@)?(?:www\.)?([^:\/\n]+)/", $page, $matches)) $page = $matches[0]; if (in_array("g", $options)) return $self; return $page; } ``` I'm not sure if I am creating this in the best way (there are l
- pattern minor 112d agoSimple calendar in PHPI made a simple calendar in PHP 7.0, could anyone help with simplification? Any advice appreciated. It works, but I totally believe it can be improved. I am a beginner. ``` " selected = "selected"> = 2000; $year--) { $years .= $year . " "; } return $years; } $years = explode (" ", getYear()); foreach ($years as $number => $chose_year) { ?> " selected = "selected" selected ='selected'> "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"); foreach($months as $number2 => $chose_month) { ?> " selected = "selected"> Mon TueWedThuFriSatSun "; } else if ($i != 1) echo "\n"; echo ""; if (($chosen_year == date('Y')) and ($chosen_month == date('n')) and date('j') == $array_of_days[$i]) { echo '' .$array_of_days[$i]. ''; } else { echo $array_of_days[$i]; } if (($i % 7 == 0) || ($i == $lastDay)) { $DayToBrake = $i; echo ""; } $i++; } echo "\n"; ?> '." Is"." ".$months[$m]." ". date('Y').'';} ?> ```
- pattern minor 112d agoUnique everlasting session with low collision rate and is set across sub-domainsThe goal is to try and make an everlasting SESSION without too much or unnecessary scripting for updating of sessions. And at the same time to avoid session collision as session collisions could lead to 2 users trying to make use of the same session. That would not look pretty! And it does happen. Also for websites that use different language sub-domains, it would be useful if session did not change so that you can easily go from one sub-domain to another without requiring new sessions. STEP 0: ``` function getUserIP(){ $client = @$_SERVER['HTTP_CLIENT_IP']; $forward = @$_SERVER['HTTP_X_FORWARDED_FOR']; $remote = $_SERVER['REMOTE_ADDR']; if(filter_var($client, FILTER_VALIDATE_IP)){ $ip = $client; }else if(filter_var($forward, FILTER_VALIDATE_IP)){ $ip = $forward; }else{ $ip = $remote; } return $ip; } $ip = getUserIP(); ``` STEP 1: ``` ini_set('session.gc_probability', 0);// 0% probability of purging session log files, in this case on startup we preventing sessions from ever being deleted! session_set_cookie_params(0, '/', '.website.com');// allow same session to be set across sub-domains! session_name('session');// now make sure that the same session will not be regenerated across sub-domains and stay the same! session_save_path($_SERVER['DOCUMENT_ROOT'].'/SESSION');//finally sessions are stored in a folder of choice in say public_html folder.. session_start();// we allow sessions to be read or changed.. ``` STEP 2: ``` if(isset($_SESSION['ip'])){// if IP session in session log exist, do.. if($ip!=$_SESSION['ip']){// if the current IP is not in the session log, then user privileges hasn't been confirmed! session_regenerate_id();// make sure that current visitor will be forced to use a different session_id! // new session copy is generated! session_destroy();// new session copy will be cleansed from previous data to be ready for use! header('Location: .');// reload the cu