PHP - Security Issues
Hello, I am using <?=$PHP_SELF?> in a search form so it will stay on the same page. I have been advised that there are security risk to using that and that is is susceptible to sql injections and my database can be at risk. I have read about using the following code instead:
htmlentities($_SERVER['PHP_SELF']) Is that more secure or are there other code that is more secure? Also could someone look at my database connection and see if there are any issues with it? Code: [Select] <?php $db_host = "localhost"; $db_user = "user"; $db_pass = "password"; $db_name = "database"; function db_connect() { global $db_host; global $db_user; global $db_pass; global $db_name; $connection = mysql_connect($db_host,$db_user,$db_pass); if (!(mysql_select_db($db_name,$connection))) { echo "Could not connect to the database"; } return $connection; } // Connect to the database db_connect(); ?> Thank you for any help you can provide. Similar TutorialsHi everybody !
Am back with the never ending security issues, just that this time it has to do with the character set related security issues. I read the whole day on utf-8 and am still lost on certain aspects related to PHP security.
Consider the simple script below:
<?php //error_reporting(E_ALL & ~E_NOTICE); session_start(); if(isset($_POST['login'], $_POST['password'])) { $login = $_POST['login']; $password = $_POST['password']; if(!empty($login) && !empty($password)) { //echo "Ok"; echo "Welcome ". $login; echo "<br> You password is.$password "; } } ?> <html> <body> <form action="welcome2.php" method="post"> Name: <input type="text" name="login" /> Password: <input type="password" name="password" /> <input type="submit" name="submit"/> </form> </body> </html>It is not a login script, but assuming that it was one, I would like to know that if UTF-8 was the charset that was selected for this script, then : 1. how could it be exploited to pass a string that would effectively break thorugh this login. It would be great if someone can demonstrate the hack using the above script example. 2. Could the same be thwarted by the use of input filters? 3. I also read that the use of a regex to limit the use of special characters in passwords is not good . So in case the hack can be thwarted by the use of regex and that is a bad idea in the first place what should be done? There are a few more questions that are on my mind but I would only ask those once I am clear on these that I have just asked. Thanks all. Hi Chaps, I'm about to start building a MySQL/PHP forum but would like to know what are the best administration steps to take. Basically it'll be open to members of a site to share info (as like many forums out there), but obviously I don't want anybody to post either harmful content or offensive material. Can someone point me in the right direction, or give me a basic outline of what I have to look out for? Many thanks if i use code as follows, This is a safe way to take the value of the form ?
<html> <head></head> <body> <form method='post'> <input type='text' name='name' value='akli'> <input type='submit' name ='view' value='view'> </form> </body> </html> <?php extract($_POST); if($view) echo $name; ?>please healp me Hi all, if someone of you has a little spare time i would love to hear what you find about the small code below. I combined some scattered stuff around the internet. and was hoping some guru could tell me if its ok to output without any sneaky javascript to get inserted within the tags or other nasty stuff. Its a bb code that first trims the string, applies html entities than puts newlines to breaks and finishes it of with a little bbcode in the end. I was hoping if this is secure enough to output text in this case a post var but am aiming for data from the database. Thanks in advance Code: [Select] <?php //replace stuff //bb function function bbcode($data) { $input = array( '/\[b\](.*?)\[\/b\]/is', '/\[i\](.*?)\[\/i\]/is', '/\[u\](.*?)\[\/u\]/is', '/\[img\](.*?)\[\/img\]/is', '/\[url\](.*?)\[\/url\]/is', '/\[url\=(.*?)\](.*?)\[\/url\]/is' ); $output = array( '<strong>$1</strong>', '<em>$1</em>', '<u>$1</u>', '<img src="$1" />', '<a href="$1">$1</a>', '<a href="$1">$2</a>' ); $rtrn = preg_replace ($input, $output, $data); return $rtrn; } // if(isset($_POST['submit'])&& !empty($_POST['textvar'])){ $error_message = ''; $string = trim(htmlentities($_POST['textvar'], ENT_QUOTES)); $clean = nl2br($string); $super_clean = bbcode($clean); }else{ $error_message = 'enter some text'; $clean = ''; $super_clean =''; } Hello, I'm creating an application where a user can input there own CSS. The problem I'm having is understanding if this will open security holes if... 1. Users input is saved to a file called style.css 2. Each user is on their own a sub-domain from my reseller hosting plan. 3. The style.css file will be included in the page code like so: Code: [Select] <link type='text/css' rel='stylesheet' href='style.css' /> Any advice? I have made a classified website. it works and I am proud of it. But as far as securing it goes, I have done almost nothing and I am sure, if in case the site becomes popular, it would be compromised with ease. So I have started reading a book ' essential php security' and am reading several articles on php security online , but am still unable to wrap my head around the whole security issue. Can someone help me ? there are a lot of unfamiliar topics, filtering, escaping , validating, session hijacking etc etc and it all goes over my head. Its a classified website , considering this on what should I concentrate on as far as security goes ? btw what I have managed to do is use mysql_real_escape_string on every var going into a mysql $query. Thanks I'm building an e-commerce website using php and mysql and I'm a bit worried about security issues. The website is going to be handling personal information so I want to make sure that it's secure and that no-one can get hold of it. I don't really have any idea about and security issues or problems that I could run into and perhaps you could point me in the direction or some tutorials that would be really great. Also if anyone here has been in the same situation what did you do to make your site as secure as possible? Thanks for any help. Hi there, I'm in serious need to find a way to block people from a website I code for. The thing is, we have a jailing system, nice and simple, and IP/email ban system too. But with proxies, advertisers and repeated troublemakers keep coming back because we just get the new proxy IP each time and it's a losing battle. What I need is a way to ban them properly from the site, like somehow stopping the computer they use from accesing the site. someone once said you can use a cookie to stop a browser getting on the site, but I don't know how to set it up to give the cookies out upon login and find the one associated to an account we don't want (by "cookie" banning I guess?") and stop them from logging in. hi php freaks I am using pdo as the driver for my new app the issue is I can't seem to find a clear answer. I want to sanise the vars that are coming into the database but pdo is suppose to fix all the issues. Is this true what other things do I need to watch for when using pdo they must have some flaws. Thanks Besides "mysql_real_escape_string"ing all the user input what other security strings should you definitely include n your site? I really have less idea about website security. Yesterday for the first time I learned website hacking and applied that method to my web page. My webpage was completely down after applying that. Q) To free a site from hacking what techniques are followed? I want to create an ADMIN directory with several directory under that. I want to be certain that the user cannot log into any of the directory unless they have confirmed login. Is $_session id's the best way to go? Should I create on the flyer and attached to username? What is the best practice for this? Regards, DED Hi, I am looking to create a directory that can not be accessed using .htaccess and neither can files directly. But I want to make it so when you are signed into joomla you can access the files via a mp3 player on the sight. My mp3 extention is joomline player flplayer. And I heard that if I cange the name of the file in joomla fomr lovelove.com/audio/love/abc.mp3 to lovelove.com/audio/love/abc.php?name=abc and then that abc.php script (inside the script it checks if you are logged in) will retrieve the file name, and the joomline will play it it will work. is this possible? Also, if not what can I do for this to work? Right now my script is not working as the joomline looks up all the mp3 files as one big string. this is the abc.php which on my site its calld psp.php <?php define( '_JEXEC', 1 ); define( 'JPATH_BASE', realpath(dirname(__FILE__).'/../../' )); require_once ( JPATH_BASE .'/includes/defines.php' ); require_once ( JPATH_BASE .'/includes/framework.php' ); $mainframe =& JFactory::getApplication('site'); if( !empty( $_GET['name'] ) ) { // check if user is logged if(JFactory::getUser()->guest) { die( "ERROR: invalid song or you don't have permissions to download it." ); } else { $psp = preg_replace( '#[^-\w]#', '', $_GET['name'] ); $psp_file = "{$_SERVER['DOCUMENT_ROOT']}/audio/live/{$psp}.mp3"; if( file_exists( $psp_file ) ) { header( 'Cache-Control: public' ); header( 'Content-Description: File Transfer' ); header( "Content-Disposition: attachment; filename={$psp_file}" ); header( 'Content-Type: application/mp3' ); header( 'Content-Transfer-Encoding: binary' ); readfile( $psp_file ); exit; } } } ?>then I have joomline player jlplayer <?php /** * JoomLine mp3 player - Joomla mp3 player * * @version 1.5 * @package JoomLine mp3 player * @author Anton Voynov (anton@joomline.ru), Sergii Gaievskiy (shturman.kh@gmail.com) * @copyright (C) 2010 by Anton Voynov(http://www.joomline.ru) * @license GNU/GPL: http://www.gnu.org/copyleft/gpl.html * * If you fork this to create your own project, * please make a reference to JoomLine someplace in your code * and provide a link to http://www.joomline.ru **/ defined('_JEXEC') or die('Restricted access'); function ascii2hex($ascii, $reverse = false) { $hex = array(); for ($i = 0; $i < strlen($ascii); $i++) { $byte = strtoupper(dechex(ord($ascii{$i}))); $byte = str_repeat('0', 2 - strlen($byte)).$byte; $hex[] = $byte; } if ($reverse) $hex = array_reverse($hex); return implode(" ",$hex); } function read_frame (&$f, &$tagdata, $frame) { $pos = strpos($tagdata,$frame); if ( $pos !== FALSE) { // frame found. read length of this frame fseek($f, 10+$pos+4); $frame2len = hexdec(ascii2hex(fread($f,4))); if (($frame2len-1) > 0) { // read frame data fseek($f, 10+$pos+4+2+4+1); $data = trim(fread($f,$frame2len-1)); $hexfdata = ascii2hex($data); if ( substr($hexfdata,0,5) == 'FF FE' or substr($hexfdata,0,5) == 'FE FF' ) { $data = iconv("UCS-2","UTF-8",$data); } else { if (!preg_match('//u', $data)) { $data = iconv("cp1251", "UTF-8",$data); } } return $data; } else { return false; } } else { return false; } } function readmp3tag($file) { $f = fopen($file, 'rb'); rewind($f); fseek($f, -128, SEEK_END); $tmp = fread($f,128); if ($tmp[125] == Chr(0) and $tmp[126] != Chr(0)) { // ID3 v1.1 $format = 'a3TAG/a30NAME/a30ARTISTS/a30ALBUM/a4YEAR/a28COMMENT/x1/C1TRACK/C1GENRENO'; } else { // ID3 v1 $format = 'a3TAG/a30NAME/a30ARTISTS/a30ALBUM/a4YEAR/a30COMMENT/C1GENRENO'; } $id3v1tag = unpack($format, $tmp); // read tag length fseek($f, 8); $tmp = fread($f,2); $tmp = ascii2hex($tmp); $taglen= hexdec($tmp); $tagdata = ""; if ($taglen > 0) { //read tag data fseek($f, 10); $tagdata = fread($f,$taglen); } // find song title frame $title = read_frame ($f, $tagdata, "TIT2"); if (!$title) { if ($id3v1tag['TAG']== 'TAG' && ascii2hex(substr($id3v1tag['NAME'],0,1)) != '00' ) { $title = $id3v1tag['NAME']; } else { $title = explode(DS,$file); $title = $title[count($title)-1]; $title = explode('.',$title); $title=$title[0]; } if (!preg_match('//u', $title)) $title = iconv("cp1251", "UTF-8",$title); } $artist = read_frame ($f, $tagdata, "TPE1"); if (!$artist) { if ($id3v1tag['TAG']== 'TAG' && ascii2hex(substr($id3v1tag['ARTISTS'],0,1)) != '00') { $artist = $id3v1tag['ARTISTS']; } else { $artist = ""; } } if (!preg_match('//u', $artist)) $artist = iconv("cp1251", "UTF-8//TRANSLIT",$artist); $id3tag['NAME'] = $title; $id3tag['ARTIST'] = $artist; return $id3tag; } if (DS == "/") $dir = str_replace("\\",DS,$music_dir); else $dir = str_replace("/",DS,$music_dir); $dir = JPATH_ROOT.DS.$dir; if (!is_dir($dir)) { echo "Wrong dir in settings"; } else { $files = glob($dir.DS."*.{mp3,MP3}",GLOB_BRACE); if (count($files) > 0) { sort($files); $host = $base_uri; foreach ($files as $file) { $tags = readmp3tag($file); $file = explode (DS, $file); if ($server_utf8 == 1) { $fname = rawurlencode($file[count($file)-1]); } else { $fname = rawurlencode($file[count($file)-1]); } $fname = substr($fname, 0, -4); $file = $host."/".$music_dir."/psp.php?name=".$fname; echo $file; $artist = trim($tags['ARTIST']); $artist = $artist == "" ? "" : "{$tags['ARTIST']} - "; $playlist[] = '{name:"'.$artist.$tags['NAME'].'",mp3:"'.$file.'"}'; } } /* * //if(!window.jQuery) { document.write(unescape('<script type="text/javascript" src="<?=$base_uri?>/modules/mod_jlplayer/js/jq.js">%3C/script%3E')); document.write(unescape('<script type="text/javascript">jQuery.noConflict();%3C/script%3E')); //} * */ ?> <script type="text/javascript"> var myPlayList = [ <?php echo implode(",\n ",$playlist)."\n"; ?> ]; Array.prototype.find=function(v){ for (i=0;i<this.length;i++){ if (this[i]==v) return i; } return 0; } var plIndex = []; for (i=0;i<myPlayList.length;i++) { plIndex[i] = i; } <?php if ($shfl == 1) : ?> //shuffle function randOrd(){ return (Math.round(Math.random())-0.5); } plIndex.sort(randOrd); <?php endif; ?> function setCookie (name, value) { document.cookie = name + "=" + escape(value) + "; expires=Thu, 01-Jan-2055 00:00:01 GMT; path=/"; } function getCookie(name) { var cookie = " " + document.cookie; var search = " " + name + "="; var setStr = null; var offset = 0; var end = 0; if (cookie.length > 0) { offset = cookie.indexOf(search); if (offset != -1) { offset += search.length; end = cookie.indexOf(";", offset) if (end == -1) { end = cookie.length; } setStr = unescape(cookie.substring(offset, end)); } } return(setStr); } function changeShflStatus(el) { nowPlay = plIndex[playItem]; if (el.checked) { setCookie("jlp_shfl","shuffle"); plIndex.sort(randOrd); } else { setCookie("jlp_shfl","notshuffle"); plIndex.sort(); } playItem = plIndex.find(nowPlay); } </script> <script type="text/javascript" src="<?=$base_uri?>/modules/mod_jlplayer/js/jq.js"></script> <script type="text/javascript">jQuery.noConflict();</script> <link href="<?=$base_uri?>/modules/mod_jlplayer/skin/skin.css" rel="stylesheet" type="text/css" /> <script type="text/javascript" src="<?=$base_uri?>/modules/mod_jlplayer/js/jquery.jplayer.min.js"></script> <script type="text/javascript"> var playItem = 0; jQuery(function(){ var jpPlayTime = jQuery("#jplayer_play_time"); var jpTotalTime = jQuery("#jplayer_total_time"); var jlp_shfl = getCookie("jlp_shfl"); if (jlp_shfl == "shuffle") { document.getElementById('jlp_shfl').checked = true; } else if (jlp_shfl == "notshuffle") { document.getElementById('jlp_shfl').checked = false; } jsuri = baseuri+"/modules/mod_jlplayer/js/"; jQuery("#jquery_jplayer").jPlayer({ ready: function() { displayPlayList(); playListInit(enable_autoplay); // Parameter is a boolean for autoplay. }, errorAlerts:true, warningAlerts:true, swfPath: jsuri }) .jPlayer("onProgressChange", function(loadPercent, playedPercentRelative, playedPercentAbsolute, playedTime, totalTime) { jpPlayTime.text(jQuery.jPlayer.convertTime(playedTime)); jpTotalTime.text(jQuery.jPlayer.convertTime(totalTime)); }) .jPlayer("onSoundComplete", function() { playListNext(); }); jQuery("#jplayer_previous").click( function() { playListPrev(); return false; }); jQuery("#jplayer_next").click( function() { playListNext(); return false; }); }); function displayPlayList() { for (i=0; i < myPlayList.length; i++) { jQuery("#jplayer_playlist").append("<div id='jplayer_playlist_item_"+i+"'>"+ myPlayList[i].name +"</div>"); jQuery("#jplayer_playlist_item_"+i).data( "index", i ).click( function() { var index = jQuery(this).data("index"); if (plIndex[playItem] != index) { _index = plIndex.find(index); playListChange( _index, index ); } else { jQuery("#jquery_jplayer").jPlayer("play"); } }); } } function playListInit(autoplay) { if(autoplay) { playListChange(0, plIndex[0] ); } else { playListConfig(0, plIndex[0] ); } } function playListConfig(_index, index ) { jQuery("#jplayer_playlist_item_"+plIndex[playItem]).removeClass("jplayer_playlist_current"); jQuery("#jplayer_playlist_item_"+index).addClass("jplayer_playlist_current"); playItem = _index; jQuery("#jquery_jplayer").jPlayer("setFile", myPlayList[plIndex[playItem]].mp3); } function playListChange(_index, index ) { playListConfig(_index, index ); jQuery("#jquery_jplayer").jPlayer("play"); } function playListNext() { var _index = (playItem+1 < myPlayList.length) ? playItem+1 : 0; var index = plIndex[_index]; playListChange(_index, index ); } function playListPrev() { var _index = (playItem-1 >= 0) ? playItem-1 : myPlayList.length-1; var index = plIndex[_index]; playListChange(_index, index ); } </script> <?php include_once(JPATH_ROOT.DS.'modules/mod_jlplayer/skin/tpl.php'); ?> <?php }I was messing around in there with $file if ($server_utf8 == 1) { $fname = rawurlencode($file[count($file)-1]); } else { $fname = rawurlencode($file[count($file)-1]); } $fname = substr($fname, 0, -4); $file = $host."/".$music_dir."/psp.php?name=".$fname; echo $file;I am unsure how to retreive a file title only, with out the whole path, just the name and not even the file ext. It comes up with all the files names in the echo. Also I am not sure how joomline chooses just one file. I am not a php designer and I am quite confused lol Any help would be appreciated! Thank you. Hey, so basically this is what im trying to do: I'm writing an mp3 store, and want the user to be able to play the whole track before purchase. Currently all the music files are in a protected folder with permissions set so access isnt possible. The mp3 player calls play.php?fid=encryptedfileid rather than the direct music link. This is all working perfectly. The bit i am now stuck on is stopping the users going to play.php?fid=encryptedfileid directly and downloading the mp3 directly. How do I make it so the server can execute the play.php file, but the user cannot? I attempted to set a cookie in play.php and deny access if cookie was present, however the server also set the cookie, so this didnt work. See play.php code (in this example, fid is just the filename, but it will be more encrypted, calling to a special md5 hash, albumid and artistid). <?PHP // Define the path to file $filename=$_GET[fid]; $file = "music/$filename.mp3"; if(!$file) { // File doesn't exist, output error die('file not occupied'); } elseif(!file_exists($file)) { die('Error: File not found.'); } else { // Set headers header("Cache-Control: public"); header("Content-Description: File Transfer"); header("Content-Disposition: attachment; filename=$file"); header("Content-Type: application/octet-stream"); header("Content-Transfer-Encoding: binary"); // Read the file from disk readfile($file); } ?> So to clarify, I need the server to access and execute this script with the mp3 player (simple javascript player) and the server not be able to visit play.php?fid=xxx directly to download. Thanks I have been working on a website for some time now. My work is now 95% finished and now I am starting to look at security, as I am using PHP. My webpage uses HTML FORMS. When most of these forms get send back to the server, 50% of the time PHP is inserting the value of the FORM inputs into MySQL. To give a basic run down, I have a newsletter sign up system. "Enter your e-mail address"... and then the user enters their e-mail and submits.. PHP runs a MySQL query to insert that FORM value into the database along the lines of this: Quote insert into newsletters (email) values ('.$POST['email'].') I fear this is very vulnerable to injection attack as it means a trouble maker can come along and enter anything they want into my database, potentially wiping it out. I believe I need to "sanitize" my input with a MySQL "real_escape_string" or something? Is there anything real obvious I should look out for when it comes to PHP security? Is there a way to forbid all strings/arguments except the few I need or something perhaps? Hi everyone, So, like my name says, I'm just a hobbyist PHPer, but I write the occassional PHP application for people, I've been doing it for quite a while and I fear that perhaps my way of securing my applications may be a bit antiquated... I was hoping that you guys/gals might be able to take a look and give me some help with perhaps how I could go about making these apps more secure... So, without further ado, here it is... standard application page, e.g. index.php Code: [Select] <? session_start(); if(!$_SESSION['Condition'] == 'Logged') { header("Location: login.php"); } elseif($_SESSION['Condition'] == 'Logged') { require "connection.inc"; ?> <? } ?> login.php page Code: [Select] <? if(isset($_POST['Login'])) { include_once 'connection.inc'; $count = 0; $query = "SELECT UserID FROM Users WHERE UserName = '$_POST[username]' AND UserPassword = '$_POST[password]'"; $results = mysql_query($query)or die(mysql_error()); $count = mysql_num_rows($results); while($row = mysql_fetch_array($results)) { $UserID = $row['UserID']; } if ($count == 1) { header("Location: loginaction.php?UserID=$UserID"); } } ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head> <title></title> <link rel="stylesheet" type="text/css" href="StyleSheet.css" /> <script language="javascript" type="text/javascript"> function loginValidate(form) { if (form.username.value == '') { alert('You must supply a Username.'); form.username.focus(); return false; } if (form.password.value == '') { alert('You must supply a Password.'); form.password.focus(); return false; } else { return true; } } </script> </head> <body> <? include_once 'header.inc'; ?> <div id="LoginBox"> <div id="SubFormBoxHeading"> Log In </div> <form id="thisform" action="<? echo $_SERVER['PHP_SELF']; ?>" onsubmit="return loginValidate(this)" method="post"> <table> <tr> <td colspan="2"> <? if (isset($_POST['Login']) && !$count == 1) { echo '<h3>Wrong Username and/or Password</h3>'; } ?> </td> </tr> <tr> <td class="Labels">Username:</td> <td><input type="input" id="username" name="username" size="20" /></td> </tr> <tr> <td class="Labels">Password:</td> <td><input type="password" id="password" name="password" size="20" /></td> </tr> <tr> <td colspan="2"> <div style="text-align: center; margin-top: 20px; margin-bottom: 20px;"> <input type="submit" id="Login" name="Login" value="Log In" /> </div> </td> </tr> </table> </form> </div> <? include_once 'footer.inc'; ?> </body> </html> loginaction.php page Code: [Select] <? session_start(); $_SESSION['Condition'] = 'Logged'; $_SESSION['UserID'] = $_GET['UserID']; header("Location: index.php"); ?> and finally, the logout.php page Code: [Select] <? session_start(); unset($_SESSION['Condition']); unset($_SESSION['UserID']); session_destroy(); header("Location: index.php"); ?> Hi, I am currently working on an Invoice System using PHP and MySQL. However I was just wondering if the system I am using is secure enough. The Client gets a link like this: Code: [Select] mysite.com/?customerid=b3e470c55aad30eb38ee52eec1d8cb52 Each client has a unique "id" I also have an ID for the administrative back-end. I do clean the GET variable before querying the database though. Do I need to secure this with anything else or is this enough, as this is my first time creating anything with PHP and MySQL together. Thanks, mme I have just made a couple of forms that submit data to a mysql database. I was wondering what measures I need to make to in order to keep the whole thing very secure. At the moment I have stripped the inputs of tags and forward slashes. Is there anything else I should do? Also some field in the form allow the user to enter a url. With these fields I have not stripped them of forward slashes. Is this a bad idea? Should I do something like replace the forward slashes with something else and then reverse this process every time I extract that data from the database? Hi everyone I'm kinda new to PHP and have a couple of questions; 1: How secure is PHP, is it very hackable? Are there things you recommend to make it more secure? 2: I am building a little employee system for staff at a friends company and they can view personal information when they login, as well as ordering stuff with online payment through WorldPay. What is therefore the best and most secure way of handling passwords, logins, data, insert statements etc. I basically want to make it as secure as possible and hopefully learn some new skills Any tips or help would be great Thanks |