I am very new to PHP, so forgive me my ignorance.
I have HTML for for upload:
<form action="upload.php" method="post" enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="file" id="file" /><br />
<input type="submit" name="submit" value="Submit" />
</form>
My PHP is (It doens’t know, but hopefully it shows what I want):
<?php
if ($_FILES["file"]["error"] > 0)
{
echo "Error: " . $_FILES["file"]["error"] . "<br />";
}
else
{
$content = fread($_FILES["file"],10);
echo $content;
echo "byte10 is: " ???
}
?>
I want to: From this uploaded file, I want to read a single byte (say byte 10). I want to print out the acscii (HEX) code for this byte. How do I do that? Do I need to save the file to the server?
(The untimate goal is to encrypt the file and send th eencrypted file back to the user. So I want (1) upload file (2) read each individual byte (2) perform encryption on byte level (3) save file and send it back to the user)
Thank you very much for the "ultimate goal" — it will help us make sure that you don’t do something silly by accident.
Encryption is a very complex topic. You should not write your own encryption routine. Use a complete, pre-built solution.
Mcrypt is PHP’s best encryption extension. Mcrypt supports multiple common ciphers including AES ("Rijndael"). Encryption is pretty darn easy — use "CBC" mode for your file.
The Vigenère cipher is a 460-ish year old substitution cipher based on a simple lookup table.
This explains the whole one-character-at-a-time thing.
While you can read the whole file one byte at a time, you might find it more convenient to work with a string. You can read the entire file into a variable (through
file_get_contentsor whatever), and then usesubstror the square bracket substring syntax to read the string one byte at a time. Remember, PHP strings are just simple lists of bytes.Given
$datais the complete data in the file, you can process every byte thusly:This is only practical for small files (smaller than a few megabytes), as it requires loading the whole file into memory.
You can get the decimal value using
ord, then convert that to a hexadecimal string usingdechex:Post-substitution, you can reverse it — use
hexdecto go from hex to decimal, thenchrto go from decimal to byte: