PHP - Help Improve My Security
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? Similar TutorialsHello. 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());} ?> 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. 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! 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(); ?> 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 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 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? 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 Besides "mysql_real_escape_string"ing all the user input what other security strings should you definitely include n your site? 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 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, 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 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? 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 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 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, 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. |