digital-ether 399 Nearly a Posting Virtuoso Team Colleague

The simple answer to your question. On every page you want to protect, you need to check if the user is logged in.

How to check if the user is logged in depends on your implementation.

Heres is a simple login scenario:


1) Login page with {user} and {pass}
2) Validate {user} and {pass} and issue that user a {session_key}
3) On every page you protect, check for valid {session_key}

That is all there is to password protected pages.

digital-ether 399 Nearly a Posting Virtuoso Team Colleague

Do a var_dump() on your array to be sure of it's structure.

You can also do this within your loop. Then it is just making sure you write the correct notation to reference the index you need.

digital-ether 399 Nearly a Posting Virtuoso Team Colleague

Do a var_dump() on your array to be sure of it's structure.

You can also do this within your loop. Then it is just making sure you write the correct notation to reference the index you need.

digital-ether 399 Nearly a Posting Virtuoso Team Colleague

A good place to start is http://php.net/oop

digital-ether 399 Nearly a Posting Virtuoso Team Colleague

You can use proc_open() to open multiple php processes. You can open a process to a PHP file that will run the server online test. You don't have to wait for proc_open() to return, so you can run it multiple times.

If you want to read the returns async, then use stream_select(). Otherwise you can just have the php scripts called by proc_open() write to persistent storage, like a db or file with the results.

You can also use exec() to execute processes async. eg:

exec('php /path/to/server_online_test.php http://example.com &');

That would call /path/to/server_online_test.php passing it "http://example.com" as an argument. You can retrieve the argument via $argv[1]

digital-ether 399 Nearly a Posting Virtuoso Team Colleague

The $pattern must be a regular expression. It must have delimiters around the pattern, and optional modifiers after the second delimiter.

Example patterns:

"/cb/" - matches cb
"/cb/i" - matches upper and lower case cb

see the docs for preg_match. http://php.net/preg_match

digital-ether 399 Nearly a Posting Virtuoso Team Colleague

Warning: sprintf() [function.sprintf]: Too few arguments in C:\xampp\htdocs\folder\search.php on line 62
Query was empty

Are you using a PHP framework? Or a custom database class?

Whats happening is that your SQL query is being run through sprintf() function, which will try and replace the special keys that start with the '%' signs with the variables passed in. See: http://php.net/sprintf

digital-ether 399 Nearly a Posting Virtuoso Team Colleague

What is the error. Do you get the error in PHP or in MySQL?

digital-ether 399 Nearly a Posting Virtuoso Team Colleague

I'm impressed with Aptana Studio 3 and it is wonderful. I have decided to go back to eclipse after years of using Netbeans. In NB I was having option of separating my files from project meta data but I cannot find how to do it with AS. Also in Netbeans debugging and running server is breeze but cannot find it in Eclipse. So any help in the aspects is appreciated
Thanks

I don't think Aptana3.0 has PHP debugging. Try installing 2.0.

Apatana3.0 tries to do too much (has too much built in) and less ability to use external plugins which makes it less customizable. I'm using the prebuilt version however, maybe you can get better results with the Eclipse plugin version.

digital-ether 399 Nearly a Posting Virtuoso Team Colleague

From the docs it seems it should work.

Try taking a look at the HTTP request with a tool like Wireshark so see if you're actually getting a HTTP request.

Also if you use a try/catch block around the xmlhttprequest open method you should see the error mesage.

digital-ether 399 Nearly a Posting Virtuoso Team Colleague

Are you aware that XMLHTTPRequest can only be made to the same domain?

You need the domain you're requesting from to grant cross domain access somehow or you will have to proxy the request.

digital-ether 399 Nearly a Posting Virtuoso Team Colleague

You'll need a tool like ffmpeg to do the video conversion.
http://www.ffmpeg.org/

You can use the command line or through PHP with an extension such as: http://ffmpeg-php.sourceforge.net/

digital-ether 399 Nearly a Posting Virtuoso Team Colleague

I don't want to have the submit button. Is it possible? If it can, how to rewrite the code? Thanks!

You can use a redirect, with cookies or session.

eg:

<?php 
@session_start();
if (isset($_GET['tz'])) {
  $_SESSION['tz'] = $_GET['tz'];
} else if (!isset($_SESSION['tz'])) { ?>
<script>
window.location = '<?php echo htmlentities($_SERVER['PHP_SELF']); ?>?tz=' + (new Date().getTimezoneOffset()/60);
</script>
<?php } ?>

Note that using JS assumes the clients clock is set to the correct timezone. Another option is to use the users IP and a geocoding service to guess their timezone.

digital-ether 399 Nearly a Posting Virtuoso Team Colleague

In short, it is up to you what your logic is, just don't worry about optimization as an issue preventing you from writing it out to cover all scenarios. Test it afterwards for performance issues, not theoretically during your coding process. It usually makes development a lot more efficient.

digital-ether 399 Nearly a Posting Virtuoso Team Colleague

For the first issue, where you have duplicates. What you can do is put a unique index on the user_id row. That way a duplicate creates an error and can never exist.

Do not worry about the extra load on the db when you check if an entry exists. It is a necessary part of your logic, so do it. Foremost is that your application works well.

If you have problems later on, it most likely will not be because you're checking for an existing entry. Read some posts online on "premature optimization". You can wonder about design all day if you think of every small decision and how it affects load.

On fail of the insert, you will have to figure out what went wrong. You can either change your onstoreuser to onbeforestoreuser or whatever it is called. Then do your insert before user is stored, and if it fails, return false so that the user registration fails. Then send yourself an email, or other notice or log the error somewhere for notification later.

When updating the credits row, you should check how many rows were affected in the update. If the update did not affect any rows, then something is wrong, so notify the user and yourself.

You can also hook into the user login through a plugin. When the user logs in, check if their credits row exists. If not, create it. This works for users that already exist in the db …

digital-ether 399 Nearly a Posting Virtuoso Team Colleague

Hi, where is the best practice to put js, image, css files when you make component? I put them in the same directory as component is. Is it good practice? Or should they be in media directory?

A lot of components will have a js/, image/ and css/ folder under the root of the component. I believe it just depends on what you feel is the best structure.

digital-ether 399 Nearly a Posting Virtuoso Team Colleague

Hi,

would it be difficult to let's say add a record to another table on user registration? Lets say I want to add a records how many credits the user has in jos_credits table when user registers, in other words - add record with that user id and set credits to 0 initially. When they add money to a website, they will get credits.

One thing I can think of is use database trigger, but I don't like them very much. Is there another way to do it with a component for example?

Another way to partialy solve that problem would be not to add record to a credits table, and only add it when the user deposits money. The problem is - we will have to check if there is already a record created when the user adds money, so do we have insert new or update an existing, so it is waste of recourses.

Joomla has a plugin system that will trigger certain events in the Joomla Framework.

The User plugins have events for saving user data, authentication etc.

see: http://docs.joomla.org/Reference:User_Events_for_Plugin_System#5.3.7_onAfterStoreUser

Here is a bit on creating a plugin: http://docs.joomla.org/Tutorial:Creating_a_Plugin_for_Joomla_1.5

Basically you will create a plugin which is an xml file and a php file. The PHP file contains a class that extends the plugin base base class. Then you define functions which handle the different events. You're interested in the onAfterStoreUser() method.

digital-ether 399 Nearly a Posting Virtuoso Team Colleague

Just to make sure:

if(!isset($_POST['anything'])){

will return TRUE if $_POST is NOT set right?

Are you sure you aren't confusing it somehow? It would be very improbable that something so unique would happen both on your server, and on your localhost at the same time.

If it was a coincidence, then it probably is not the ! operation, but a problem with $_POST or something similar.

When dealing with bugs like this, the last thing you want to blame is the internals of the programming language, as those are hardly ever the cause of the error.

digital-ether 399 Nearly a Posting Virtuoso Team Colleague

Try debugging your code. Make sure you're getting the correct list/array of passwords.

eg:

$var_list = explode("\n",$var_data);
var_dump($var_list);

or:

print_r($var_list);

Zero13 recommended using:

$var_list = explode("\r\n",$var_data);

Instead since Windows line breaks are \r\n instead of just \n in Linux. However, to work with both Windows and Linux you need something like:

$var_list = explode("\n",$var_data);
// trim each value in the data
$var_list = array_map('trim', $var_list);

However, if spaces mean something in each line you need to only trim the \r character.

Just a note, instead of using:

echo ( '<meta http-equiv="REFRESH" content="0;url=WinthropPoll01.html">');

You can use:

header('Location: WinthropPoll01.html');

That sends a HTTP redirect which is followed without displaying any content. However, that only works if you have yet to display any content at all.

To solve that you usually use output buffering to buffer your content (see: ob_start() ) or you can test for output using headers_sent().
http://us2.php.net/manual/en/function.headers-sent.php

eg:

if (!headers_sent()) {
   header('Location: WinthropPoll01.html');
} else {
   echo ( '<meta http-equiv="REFRESH" content="0;url=WinthropPoll01.html">');
}
digital-ether 399 Nearly a Posting Virtuoso Team Colleague

I wrote a Class to read sessions from the PHP session files:
http://www.daniweb.com/code/snippet317107.html

Thought it would be useful to others trying to do the same.

Aamit commented: Thanks for greate help +0
digital-ether 399 Nearly a Posting Virtuoso Team Colleague

Here is an example of decoding all the session files (limited to 10 here). Comments explain what each block does.

<?php

session_start();

// what is handling the sessions
$session_type = ini_get('session.save_handler');

// with files, session data files will be in session.save_path directory
if ($session_type == 'files') 
{
  // directory where session files are in
  $session_path = ini_get('session.save_path');
  
  // get the files in session directory
  $files = glob($session_path . '/sess_*');
  
  /*
   * Iterate over each file and decode sessions
   */
  $i = 0;
  foreach ($files as $file) 
  {
    
    echo 'Decoding session data in ' . $file . '<br />';
    
    // file contains session data, get it
    $encoded_session = file_get_contents($file);

    // unset the current session
    $_SESSION = array();
    
    // decode the file data into $_SESSION
    session_decode($encoded_session);
    
    // lets look at the data
    echo '<pre>' . print_r($_SESSION, 1) . '</pre>';
    
    // limit to 10 files
    $i++;
    if ($i == 10) break;
    
  }
  
  
}
// for other session handlers we have to look elsewhere (such as db etc.)
else 
{
  
}


?>
digital-ether 399 Nearly a Posting Virtuoso Team Colleague

These are the PHP session files in serialized (encoded) form. Note that is it not encrypted, it is just encoded. The strings represent objects in PHP, and PHP knows how to turn it back into actual Objects.

The value of this file is available for the specific user through the $_SESSION global array. More of this is in the PHP sessions manual: http://www.php.net/manual/en/book.session.php

The session data is serialized in a format different from the serialize() function. It uses the format in session_encode().
see: http://www.php.net/manual/en/function.session-encode.php

The opposite function session_encode() takes a string encoded with session_encode() and populates the $_SESSION with its unserialized values.
see: http://www.php.net/manual/en/function.session-decode.php

digital-ether 399 Nearly a Posting Virtuoso Team Colleague

You can use SET in a MySQL insert statement:
http://dev.mysql.com/doc/refman/5.1/en/insert.html

The best way to see what that error is, is to check for errors when you execute a query. Eg:

$result5=mysql_query($query5);
if (!$result5) {
   echo mysql_error();
}

Calling mysql_query() should automatically trigger an error. But if you have error output turned off (php.ini config value display_errors) then look into your error logs.

digital-ether 399 Nearly a Posting Virtuoso Team Colleague

The PHP script is not responding when the JSON request is made.

ie: $.getJSON()

This happens in the client side JS, but your PHP script on the server, will just hang. You'll have to figure out what is hanging. I'm guessing it is the HTTP requests made in the PHP script to the URL shortening services.

Try adding some debugging to your PHP script, like:

function getContent($url) {

echo "calling getContent with URL: $url\n";

etc.

digital-ether 399 Nearly a Posting Virtuoso Team Colleague

It would really help you if you looked into XMLHttpRequest. There are a lot of tutorials and examples online to guide you. It is the basis of "AJAX".

xmlhttp.open("GET","livesearch.asp?q="+str,true);

That just opens a HTTP connection to the URL given: livesearch.asp?q="+str
The q is the HTTP query parameter that holds the search you typed in. This is what is passed to PHP, and PHP should base it's response on.

xmlhttp.send();

Will send the HTTP request through the HTTP connection opened.

The

xmlhttp.onreadystatechang

e is a function that will be called, then the HTTP response/reply changes state.

xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("livesearch").innerHTML=xmlhttp.responseText;
    document.getElementById("livesearch").style.border="1px solid #A5ACB2";
    }
  }

The above code listens for the HTTP response, and when it receives the full response with a successful HTTP status (200) it writes the HTML received in the HTTP request to the div with id="livesearch".

digital-ether 399 Nearly a Posting Virtuoso Team Colleague

The JavaScript in the page should do that:

<html>
<head>
<script type="text/javascript">
function showResult(str)
{
if (str.length==0)
  { 
  document.getElementById("livesearch").innerHTML="";
  document.getElementById("livesearch").style.border="0px";
  return;
  }
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("livesearch").innerHTML=xmlhttp.responseText;
    document.getElementById("livesearch").style.border="1px solid #A5ACB2";
    }
  }
xmlhttp.open("GET","livesearch.asp?q="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>

<form>

<input type="text" size="30" onkeyup="showResult(this.value)">
<div id="livesearch"></div>
</form>

</body>
</html>

The input field has an onkeyup event handler attached to it:

<input type="text" size="30" onkeyup="showResult(this.value)">

This will fire the showResults() function every time a key is pressed while focus is on the textbox (writing in the textbox).
showResults() will then grab the PHP page from the server and display the results in

<div id="livesearch"></div>

Do you have Firefox? When working with Javascript it is good to have Firefox and Firebug. Firebug is about the best (browser based) JavaScript debugger out there.

digital-ether 399 Nearly a Posting Virtuoso Team Colleague

I'd advise using PHP if you post here, and you can post your ASP version in the ASP forum. :)

With PHP, you'll have to connect to the database
http://php.net/manual/en/function.mysql-connect.php

Then make the search query:
http://php.net/manual/en/function.mysql-query.php

Retrieve the results of the query:
http://www.php.net/manual/en/function.mysql-fetch-array.php
or
http://www.php.net/manual/en/function.mysql-fetch-assoc.php

Then display your results as HTML.

The JavaScript portion takes care of retrieving your PHP page, and adding the HTML send by your PHP page to the DIV of id "livesearch".
ie:

xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("livesearch").innerHTML=xmlhttp.responseText;
    document.getElementById("livesearch").style.border="1px solid #A5ACB2";
    }
  }

You may want to do some research on XMLHttpRequest if you are not familiar with it.

:)

digital-ether 399 Nearly a Posting Virtuoso Team Colleague

What programming language are you using on the server side? I think you'll have more help in the appropriate forum for that language.

digital-ether 399 Nearly a Posting Virtuoso Team Colleague

Please post problems you're having, instead of the whole task. I'm sure no-one will want to do the work you're getting paid for, for free. :)

digital-ether 399 Nearly a Posting Virtuoso Team Colleague

After the mysql_query() do some error checking. It will let you know what went wrong with the query. Example:

if (!$result) {
  trigger_error("MySQL error: ".mysql_error(), E_USER_ERROR);
}

I believe the problem is that DATE is a function so you need to escape it in the SQL query.

digital-ether 399 Nearly a Posting Virtuoso Team Colleague

You can use file_get_contents(). Just add the user and password to the url in the form:

http://user:pass@example.com/path/to/file.xml

Or you can specify the http header to send in the stream context parameter.

eg:

$context = stream_context_create(array( 
    'http' => array( 
      'method'  => 'GET', 
      'header'  => sprintf("Authorization: Basic %s\r\n", base64_encode($username.':'.$password)), 
      'timeout' => 5, 
    ), 
  )); 
  $xml = file_get_contents('http://example.com/path/to/file.xml', false, $context);

see: http://www.php.net/manual/en/function.stream-context-create.php

Also lookup Basic Authentication in a search engine to get an idea of the headers being sent/received in the http request/response. :)

digital-ether 399 Nearly a Posting Virtuoso Team Colleague

The two main things here is:

1) Saving the form field values added by the user
2) Returning to the form without the "resend post" message

Saving the form field values added by the user
The only way to save the values effectively is to save them server side (or client side) and populate the form with those values when returning the user to the form.

So you can save the form values when the user submits, to their session for instance.

Returning to the form without the "resend post" message
To return without a post message, you have to use a direct link, instead of the browser back feature.
The other way to do it, is impose a HTTP redirect in between the form processing page, and the actual page displayed to the user.

So for instance when the user submits the form at form.php, you validate it on a page called validate.php, and then redirect to a page called results.php. That way, when the user hits the back button, they are taken directly back to the form.php page bypassing the process.php form submit.

digital-ether 399 Nearly a Posting Virtuoso Team Colleague

hi there,
I have one question
here is my code taken from the internet which is about the static function
but i dont exactly understand for what reason we use here static function and
what does mean self and code which is below
can anyone explain it to me

<?php
class Dynamic {
  static protected $methods = array();

  public static function registerMethod($method) {
    self::$methods[] = $method;
  }

  private function __call($method, $args) {
    if (in_array($method, self::$methods)) {
      return call_user_func_array($method, $args);
    }
  }
}

function test() {
  print "Hello World" . PHP_EOL;
}

Dynamic::registerMethod('test');
$d = new Dynamic();
$d->test();
?>

and i dont understand here
line 6 (self:: ), 10, 11 and the purpose of __call function
thanks beforehands

The static method is:

public static function registerMethod($method) {
    self::$methods[] = $method;
  }

What it does is take a string $method as parameter, and append it to the array self::$methods . self::$methods refers the static property defined in:

class Dynamic {
  static protected $methods = array();

The method __call defined in:

class Dynamic {
  private function __call($method, $args) {
    if (in_array($method, self::$methods)) {
      return call_user_func_array($method, $args);
    }
  }

Is a "magic" method. It is a method that is called when ever a dynamic method is called on that class but has not been defined.

It is similar to the "__get" and "__set" methods which are used for dynamic properties.
http://php.net/manual/en/language.oop5.magic.php

So if you call a method that doesn't exist, example:

$d = new Dynamic(); …
digital-ether 399 Nearly a Posting Virtuoso Team Colleague

You cannot place statements as parameters.

You need to create your HTML in a string, and then do the replacement with that string as the parameter.

eg:

session_start(); 

if(!session_is_registered(username))
{
 $html = 'href="http://www.mywebsite.com/Login.php" title="Login">Login</a>';
} 
else 
{
 $html = 'href="http://www.mywebsite.com/logout.php" title="Logout">Logout</a>'; 
}

$template = str_replace ("{_SIDE_URL1_}", $html, $template);

Here you create a string and save it to $html. Then replace any instance of the string "{_SIDE_URL1_}" inside $template with $html.

digital-ether 399 Nearly a Posting Virtuoso Team Colleague

hi there,
I have one question
here is my code taken from the internet which is about the static function
but i dont exactly understand for what reason we use here static function and
what does mean self and code which is below
can anyone explain it to me

....

and i dont understand here
line 6 (self:: ), 10, 11 and the purpose of __call function
thanks beforehands

Static and dynamic class methods can be a bit hard to grasp at first. In order to understand them, you have to first understand the "class definition" and the objects created from the class definition.

The class definition, is the actual code you write to define a class. The Objects or Instances of that class definition, are copies of Objects created from the definition you wrote, and exist only in the memory of the program.

Thus when using the terms static and dynamic, you are referring to the static class definition, or the dynamic object created from that class.

Static properties and methods, are the properties and methods defined in the class, while dynamic properties and methods, are the properties and methods that the object creates from the definition of the class.

Note, that every property and method is essentially dynamic or static depending on how it is referenced. If it is referenced as a property of an object, it is dynamic, since the object is dynamic. If it is …

digital-ether 399 Nearly a Posting Virtuoso Team Colleague

Multiple queries are not supported by mysql_query().
see: http://php.net/manual/en/function.mysql-query.php

Also make sure to quote the string you send as well as escape them with mysql_real_escape_string(). For the integers use intval() on them. This prevents sql injection, and ensures the values do cause an error if they contain special characters.

digital-ether 399 Nearly a Posting Virtuoso Team Colleague

I suspect that you are just not getting any results back from your query. I would echo $aid and make sure it is holding a value and work from there.

Also, I should allow D-E to answer but

$filename = "$row['filepath']"."$row['filename']";

is incorrect.

Should be:

$filename = "$row['filepath'].$row['filename']";

Concatenate is merely a way of saying "to join." The period in this case is the operator that is doing the joining. You are joining two strings to create a single string out of them. So, like any other string you only need your opening and closing quotes. "." would be incorrect.

$filename = "$row['filepath']"."$row['filename']";

Is fine.

It could also be:

$filename = "$row['filepath']$row['filename']";

or

$filename = $row['filepath'].$row['filename'];

Double quotes enclose strings. However, the string is then parsed again by PHP before the output is taken as the final stirng.

So if you have anything that "looks like" a variable, PHP will try and make it a variable.

So even if you had "sdofjsodfj$sdojsdoifjsd" PHP would try convert $sdojsdoifjsd to it's value because it see's a $ in there.

With single quotes, the string is taken literally. So 'sdofjsodfj$sdojsdoifjsd' is taken as 'sdofjsodfj$sdojsdoifjsd'.

digital-ether 399 Nearly a Posting Virtuoso Team Colleague

Parse errors happen when the formatting (syntax) of your code incorrect. Because a parse error is only detected once an unexpected piece of code is reached by the PHP intepreter, it often gives you the wrong line number of the error.

The error in this case is with this portion:

echo "<div class='photoThumb'>";
."<a href='$row[\'filepath\']$row[\'filename\']'>";
."<img src='$row[\'filepath\']$row[\'filename\']' rel='lightbox[\'$aid\']' border='0' width='100px' />";
."</a><br/></div>";

The string concatenation operator is the period "."

String concatenation example:
If you want to put two strings together.

$str1 = "first string";
$str2 = "second stirng";

You do so as such:

$str3 = "first string"."second string";

As you have it you're doing:

$str3 = "first string";."second string";

So the semicolon ";" would cause a parse error.

Note: I have the two strings on one line, but PHP doesn't care if it on one line or two lines etc.

I'd recommend looking into string concatenation a bit more. PHP offers many ways to concatenate strings as well as strings and variables.
http://php.net/manual/en/language.operators.string.php

An example of the code formatted correctly:

echo "<div class='photoThumb'>"
   ."<a href='".$row['filepath'].$row['filename']."'>"
   ."<img src='".$row['filepath'].$row['filename']."' rel='lightbox['".$aid."']' border='0' width='100px' />"
   ."</a><br/></div>";

SQL Injection note:

In following piece of code:

$aid = $_GET['aid'];
$select = ("SELECT * FROM 'pictures' WHERE 'aid' = '$aid'");

You'll want to escape any variable you place in an SQL query. Otherwise someone could modify the query in a way you didn't intend.

Example:

$aid = mysql_real_escape_string($_GET['aid'], $con);
$select = ("SELECT * FROM 'pictures' WHERE …
digital-ether 399 Nearly a Posting Virtuoso Team Colleague

ya that function convert string into Hexadecimal..!! and work perfectly with english characters but not with non english char.

wht should i do when string is non english characters like Arabic..??
like مرحبا

how can i convert Arabic string into hexadecimal..?? and how can i insert Arabic string into database..??

You should not be converting to hex to save to the DB. Just make sure your db is saving data in the correct encoding. MySQL is multibyte aware, PHP isn't natively up until PHP5 inclusive. So the only place to take care in is within PHP.

Saving strings as hex makes it very hard to use the MySQL string functions, and string indexing. If you save in the correct encoding to begin with, you do not have to worry about encoding conversion.

PHP5 and lower sees strings as a sequence of bytes. So any operation on the string is done per byte, neglecting any encoding. You will need to avoid using the native PHP string functions.

What I would do is use the UTF-8 functions, since UTF-8 is the defacto standard on the web. To do that first convert to UTF-8:
http://www.php.net/manual/en/function.mb-convert-encoding.php

After you convert all your data to UTF-8, you do not have to anymore if you tell the browser it is UTF-8, since the browser will send you UTF-8. Same for any other encoding.

Rules:

1) Tell the browser your encoding. (header('Content-Type...'))
2) Do not use native PHP …

digital-ether 399 Nearly a Posting Virtuoso Team Colleague

How is it not working? Are you getting errors, if so what are they?

Try turning on error reporting to max, and set display errors to true.

ie:

error_reporting(E_ALL);
ini_set('display_errors', 1);
digital-ether 399 Nearly a Posting Virtuoso Team Colleague

Note: There are 3 hashing methods with 8 characters adler32/crc32/crc32b I am assuming none of these should be used? That begs the question but why were they created in the first place?
I gather any other hashing methods are fine as the next shortest one is 32 characters!

adler32 and crc32 were developed for a different purpose then security. They are used more for verifying data integrity or error detection.

They do not provide means to secure against intentional data modification, since this wasn't the design goal.

Wikipedia explains all this:
http://en.wikipedia.org/wiki/Adler-32
http://en.wikipedia.org/wiki/Cyclic_redundancy_check

As also mentioned, the hashes produced are short enough that all possible hashes can be computed by a single computer in minutes.

Notice that the hashes used today are much longer then those used in the past. We have to keep using longer and longer hashes because computers are becoming more efficient.

The only reason adler and crc is used for data integrity instead of larger hashes is because they are faster, yet do the job of error detection very well.

Anyways, I have made a dehasher that can dehash up to 6 digits depending on what characters are to be dehashed and time allowed. You can grab a copy of the SHA1 dehasher from the attachment on this post to see how insecure SHA1 is IMO. Enjoy dehashing the >=6 digit hashes.

You might be interested in the list of top password crackers published by …

digital-ether 399 Nearly a Posting Virtuoso Team Colleague

I gather what you are saying " Atli ", but if your rehashing a hash from crc32b it is still valid, like as you stated your still making an xxx hashing not shorten the length of a hash but like you stated it would be absurd to use crc32b as your only means of protection.

Salt I can understand, I guess it just comes down to personal taste, depends how much junk you want to add to the end of the string I guess to make it that unique?

At this rate why not quadriple whirlpool and salt a hash, I guess it comes down to the point of meaningful and meaningless code dependent on the coders opinion... lol

CRC32 should NOT be used at all. Not as the last hash output, or before you hash it again with a secure hash. Just not at all.

Even if you take a crc32 hash and rehash it with sha256. It doesn't strengthen the crc32 hash.
The number of different hashes CRC32 can produce is only 2^32 = 16^8 = 4.294.967.296.

So you're basically reducing the number of different hashes someone needs to check, down to 4.294.967.296. This only takes a few minutes on an average PC. If you used a precomputed table of CRC32 hashes, it would take only a few seconds.

The reason they only have to check that number, is that CRC32 thus only produces a subset of the sha256 hashes (4.294.967.296 unique SHA1 …

OmniX commented: Detailed response, Thankyou! +2
digital-ether 399 Nearly a Posting Virtuoso Team Colleague

why not just use the username or one of the existing data base fields as a salt? that way it will be unique for each password.

I was reading up on salts and the consenses is that as long as they are used to stop precomputation attacks (aka rainbow tables, etc) the length required is meaningless only the value of the salt, which should be randomly constructed.

This statement correct?

PS: now dont be trival and start if my salt is only 1,2,3 charcters salt should be 5+ randomly constructed and stored in a database for retrieval.

@OmniX The length of the salt does matter. The salt should be random, yes, but it should also be long enough to make the precomputation attack infeasible.

I've also read those statements that the salt length does not matter, and this is incorrect. See http://en.wikipedia.org/wiki/Password_cracking#Salting

It states that the 12 bit salts used in earlier unix is not long enough to prevent precomputation. BCrypt for example uses a 128 bit salt. A comparatively complex salt in ASCII characters A-Za-z0-9 is about 23 chars.

There are many 14 character long rainbow tables available. So if a salt is not 14 characters, it is open to precomputation attacks by anyone wanting to do so.

@leviathan185 the username is not random enough and also too short.

Anyways what I gathered from 'digital-ether' alone crc32 is faulty but if used in conjunciton with another hashing algorithm, it is fine?

CRC …

Atli commented: Nicely put. +3
digital-ether 399 Nearly a Posting Virtuoso Team Colleague

A hash is meant to be one way. There is no way to actually guarantee it. True one-way functions are only theoretical at this point.

Not that I don't agree with you; that hashes should be considered one-way. Just pointing out that it is not an absolute truth, but rather a practical truth. We could very well see some of the more popular hashing algorithms being "broken" in the future.

Wouldn't you just love to prove it?
http://en.wikipedia.org/wiki/Millennium_Prize_Problems
I think I'll try and solve it tonight. Or maybe just buy a lottery ticket, better chance of winning that.

digital-ether 399 Nearly a Posting Virtuoso Team Colleague
function HASHITBAY_BE($toHash)
{
   $maxLength = 42; //maximum length of the salt
   $hashMethod = 'whirlpool' //encryption method...
   $saltLength = strlen($toHash)*3;
   if($saltLength > $maxLength)
      $saltLength = $maxLength;
   if($saltLength < 10)
      $saltLength = 10;
   $salt = saltGen($saltLength);
   $hash = hash($hashMethod, $toHash . $salt);
   $hash = substr($hash, $saltLength-10);
   $hash = $salt . $hash;
   return $hash;
}

The cool thing about using this method is that, even if the hacker gets access to your database, AND your source code, it's nearly impossible for him to retrieve your original data, as he'd have to already know the length of the password (or whatever the data is), in order to retrieve the salt.

@chaines51 not to be nitpicky but I would not rely on someone not being able to guess the length of the password as a way to increase security. It is even easier to guess the length of a password, then just one char in a password. The idea itself is great, however, I think the practical implication is not that useful.

Based on the max and min length of the salt, it can only be 32 different lengths. But knowing that most passwords are around 6-8 chars, you are only left with about 2 or 3 lengths to guess on average, making it negligible.

I'd also make sure the salt is at least 20 chars. The rainbow tables of 14 chars are common (lookup for an input of combined length of 14 chars is possible). So I'd stay on the safe side …

nav33n commented: Thanks for the informative post digital :) +5
digital-ether 399 Nearly a Posting Virtuoso Team Colleague

Hash one way, your thinking in terms of 1998 technology. Today we have supercomputers with millions of cpus with petaflops whatever that means. So when the performance of the average computer increasing every month it makes it possible for the computer to hash every combination until there is a matching hash. And with today's average home pc, it is possible to crack a hash where the original string was ONLY 3 digits long and that takes about 40 seconds. However with a supercomputer perhaps something like 7 digits could be cracked in that time. Keep up with the technology dude.

Maybe the root cause for all this confusion is the word dehasher. ;) Its not exactly a dehasher, but a hash-matcher ! :icon_cool:

The word to use is: guess

digital-ether 399 Nearly a Posting Virtuoso Team Colleague

Anyone who knows how to apply this in php scripting? the scripts in this site can be xecuted in mysql console but I can't get it working in php script in the website im studying.
I want to create a tree like this: http://sitepointstatic.com/graphics/sitepoint_numbering.gif

The examples at http://www.sitepoint.com/print/1105/ should do...

digital-ether 399 Nearly a Posting Virtuoso Team Colleague
include_once('session.php');
include_once('config.php');
$userid = $_SESSION['userid'] ;
$uname = $_GET['uname'];
 $query= "call sp_active('$uname','$userid',@u_active)";

$result = mysql_query($query) or die('query_error'.''.mysql_error());
  if($result)
  {
    header('location:vagent.php');
  }

simple php code.. but still throwing Cannot modify header information - headers already sent by

i have also use ob_start(); but of no use

Are you using ob_start() before any PHP code?

eg:

<?php
ob_start();
 include_once('session.php');
include_once('config.php');
// .. etc...
?>

Also make sure there isn't any spaces or newlines before the call to ob_start();

The other possible problems is if you have a UTF BOM added by your editor, if you're using windows.
http://en.wikipedia.org/wiki/Byte_order_mark

You can detect this with PHP by making a HTTP request (eg: file_get_contents()) to the page, and checking if the first byte matches unicode point U+FEFF.

Another possibility is if you have errors in your PHP build, or configuration, that makes it spit out an error before PHP scripts are interpreted.

Both of these would cause header() to fail even if ob_start() is used since they occur before any PHP code you write.

digital-ether 399 Nearly a Posting Virtuoso Team Colleague

Sure it may not be possible to store every combination as there are infinit possible hashes due to an infinit length that can be hashed (eg. pi). However, it is still possible to hash at least the first 5 digits and every word from the dictionary. I have a vps for all of this and I have encrypted the hashing data so that it only takes up half the space. I know you may say this is not possible but I am all about doing the impossible and usually I succeed. Also could you give me a reference about rainbow tables as they sound colorful and needed. Currently the technique I'm using is by having 3330 tables each storing a proportion of the data but discovered more would be needed.

There is a finite set of possible hashes, since hashes are of a finite length.

You're right, you don't need to store all the hashes, such as what rainbow tables do
http://en.wikipedia.org/wiki/Rainbow_table

Or special hash indexes probably similar to your approach:
http://www.sha1-lookup.com/
http://tools.benramsey.com/md5/
http://gdataonline.com/seekhash.php
etc.

None of these (precomputation attacks) will work on a salted password as I mentioned before.

digital-ether 399 Nearly a Posting Virtuoso Team Colleague

Are you kidding, no hash is secure unless you hash the hash. If you type in "dehasher" in google my website comes up on the first page "global programming syntax" and with my website, sha1, crc23 and crc23b will have a reverse lookup to at least 4 digits. My database is being populated each day with millions of results and will upload the database late November. So currently the database is not publicly viewable but will be soon and I have plans to expand it to a monster database as I have made the database structure efficient for mysql query lookup. So with plans like mine, no hash is secure as long as it follows a standard format. That's why you hash the hash or use a custom hashing function.

SHA256 are Whirlpool are definitely secure. For most applications sha1 and md5 are also secure, though many will recommend using SHA2 and up. http://en.wikipedia.org/wiki/SHA_hash_functions

You cannot save all the hashes from SHA256 or Whirlpool in a database, or even SHA1.

If you take SHA1 for example, which generates a 160 bit hash, then to store all the possible hashes would require about:

(2^160)*160*2 ~= 10^50

or in PHP:

$bits = pow(2, 160)*160*2; // ~4.68E+50

(multiplied by 2 since the inputs will take up as much space as the hashes)

You can take away 7 decimal points (8*10^6) in order to get the number of gigs which is around 10^43 Gigs. (10 with 43 zeros)