PHP - How To Load File As Binary Data And Operate On It With Bitwise Operators?
Hi all,
Is it possible in php to read data from file as binary and operate on it with bitwise operators and save result as binary. Thanks Similar TutorialsHi every one, I just want to know what is the use of '<<' and '>>' operators in php So I have coded php for about 5-6 yrs and have never really needed to use binary conversions and the bitwise operator like >> or << . I took a php class in college but that basically consisted of the students trying to learn php on their own... So i have never had any exposure to that portion of php coding. I have to take an exam on PHP with a bunch of questions that DO NOT show how good of a coder you are. There are a bunch of questions on bitwise operators and binary conversions... Am I missing something??? Whats the point of converting a string to binary or knowing how to do this in your head? Any help? Here is a simple script which uses bitwise operations to determine whether or not a checkbox has been set. The problem is that if you use the $alpha array, the script doesn't produce the results you should expect. For example, if you set the last checkbox while using the $alpha array, all the checkboxes become set. I partially know why this happens as the PHP-Manual enlightened me: Quote From: http://www.php.net/manual/en/language.operators.bitwise.php Don't right shift for more than 32 bits on 32 bits systems. Don't left shift in case it results to number longer than 32 bits. I attempted to use the GMP_* functions but because those aren't part of the PHP-Standard-Library, I do not wish to rely on them. Is there any way to make these functions work for integers beyond 2^31? Here is a standalone script I'm using to make these tests. $alpha = array('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'); $delta = range('a', 'z'); function generate($array){ $n = count($array); $c = array(); for($i = 0; $i < $n; ++$i){ $c[bcpow(2, $i)] = $array[$i]; } return $c; } function set($array, $post){ $c = 0; foreach($array as $key => $val) if(isset($post['c'.$key])) $c |= $key; return $c; } function check($num, $category){ if($num & $category) return 'CHECKED'; return ''; } function checkboxes($array, $numval=0){ $i = 0; $form = ''; foreach($array as $key => $val){ $checked = check($numval, $key); $form .= '<input type="checkbox" '.$checked.' name="c'.$key.'" id="c'.$key.'">' . '<label for="c'.$key.'"> '.$val.'</label><br />'; ++$i; } return $form; } $array = generate($alpha); $num = 0; if(isset($_POST['action'])){ $num = set($array, $_POST); echo $num; } echo '<form action="y.php" method="post" style="width: 400px; border: 1px solid black;">'; echo checkboxes($array, $num); echo '<input type="submit" name="action" value="Set" />'; echo '</form>'; Is this the correct way to write binary data to a file? $string = 'this is a string'; $handle = fopen('b.dat', 'wb'); for($i=0;$i<strlen($string);$i++){ $hx = bin2hex($string{$i}); fwrite($handle, pack("H*", $hx)); } If so, how do I read it an convert it back to a string? If it is not correct, how do I do it? hi all, I have an array(1,2,3,4) and i make a form and make checkboxes for this array and user selects 2,3 and 4 when user submit form then i save it in table by making selected check boxes and converting selected values into bitwise equivalent value like this foreach($data['meal_types'] as $v){ $mealTypeBits += pow(2,$v-1); } Now when i have to show user his selected data how will i compare table bitwise saved record with array(1,2,3,4) to get the values that he checked while saving. Hi, guys. I'm trying to wrap my head around trying to read a header in a binary file in php. So, far, I have been able to get the data into a string using file_get_contents. Now, I think I need to use unpack, but it's a bit confusing to me still. For example, my file starts by having a 1 byte version number, 4 bytes to represent a number of walls, then "number of walls" * 40 bytes for the actual walls. But, the problem is, the wall itself is a structure composed of various elements to make up that 40 bytes, from which I'll need to pick out a specific area of interest. I can do this easily in C, but in php. I can't think how to grab the info. Any ideas? Maybe just how to read 1 byte, 4 bytes, then "number of walls" * 40 bytes will get me in the right direction. ive been doing some research on this, and i cant seem to find an answer that makes sense. im reading the manual on mysql_real_escape() and I know how to use the function, but in the description: Escapes special characters in the unescaped_string, taking into account the current character set of the connection so that it is safe to place it in a mysql_query(). If binary data is to be inserted, this function must be used. What is an example of inserting "binary data" as described above?? As far as I understand that would be any numerical values and a string would not apply.. But does not seem to add up. A binary file cannot be inserted, so Im a bit lost. Any thoughts welcome. I'm planning on storing RIPEMD-160 passphrase hash's raw binary data in MySQL as BINARY(20). Right now, I'm not sure if one of the following INSERT approach is more preferrable and more efficient: Approach (1) - Using mysqli::real_escape_string() ================================================= Code: [Select] $binhash = $mysqli->real_escape_string(hash('ripemd160', $passphrase, true)); $mysqli->query("INSERT INTO testtbl (Passphrase) VALUES ('" . $binhash . "')"); This approach saves hash() from converting raw binary data to hexadecimal format, but need to process and escape the binary string. Approach (2) - Using UNHEX() on MySQL ===================================== Code: [Select] $hexhash = hash('ripemd160', $passphrase); $mysqli->query("INSERT INTO testtbl (Passphrase) values (UNHEX('" . $hexhash . "'))"); This approach needs hash() to convert binary data to hexadecimal but no need for escaping the string and it put extra load on MySQL to convert the hexadecimal back to binary. hi, I want to write pdf file but it is getting garbage value i check following url http://bugs.php.net/bug.php?id=21904&edit=1 Code: [Select] $fp = fopen($fdirandname,'wb'); fwrite($fp,$pdfcode); fclose($fp); I'm at kind of a loss with this. I've read the docs for ~ bitwise NOT, and for ip2long() and I can't see why this is happening. On 2 machines with 32 bit OSs (one PPC Mac, and one Linux box), this does what I'd expect it to do. On an Intel Mac with a 64 bit version of OS X, it does not. echo abs(~ip2long('255.255.255.0')) + 1; I would expect this to return a value of 256. On a PowerMac, dual G5 OS X 10.5.8, (32 bit) and PHP 5.2.11 it returns 256 On a hosting server (unsure what processors) Linux OS (32 bit) and PHP 5.2.14, it returns 256 On an Intel Mac, Core2 Duo, OS X 10.6.8 (64 bit) and PHP 5.2.17, it returns 4294967042 Have I overlooked something in the manual that would explain this, or am I doing something fundamentally wrong with one of the functions? Hi friends how does this types of array operate ? pls help, I am repeatedly facing this code but my brain can't hold, i am familiar with multi dimensional array but what are these ? $data[$row['id']] $options['data']=$row[0]; Hello. If someone can help me, i'll be grateful So i have a foreach and an $output .= function that fills some infos in a table. Inside it i have a div for each line that when hovering your mouse should get some data .. Here i have a big problem, because for each line it should get some data and i don't know how to do it ... i'll post here some of my code for better understanding. Quote //some java here <?php require "class.php"; $server_list = query_group(); $misc = server_misc($server); foreach ($server_list as $server) { $misc = server_misc($server); $server = server_html($server); $idi = "{$server['o']['id']}"; $harta = "<a onmouseover=\"ShowContent('harta'); return true;\" onmouseout=\"HideContent('harta'); return true;\" href='".link($server['o']['id'])."' target=\"_self\">{$server['s']['map']}</a> <div style=\"position:absolute;\" id=\"harta\" class=\"FAQ\">file_get_contents('http://mysite/player.php?d={$idi}')</div> "; $output .= " <table> ........... some code..... <td> {$harta} </td> ....... so basicly when i hover my mouse over each row it should get data from the file for that id... The problem is that only one page can be loaded with file_get_contents. I read over the internet that some ajax functions can do it but i really don't know how. Please help me, i've been looking for 3 days already without any luck i have a dropdown menu that displays the options i have in a database. i have this all working in mysqli as i didnt write this part on another website. but i am struggling to convert it back to mysql. the original code is: $query = "SELECT gallery_type_id, gallery_type_desc FROM gallery_type ORDER BY gallery_type_id"; /* run the query */ $result = $dbLink->query($query); /* load the query's results into an array */ $i=1; while($row=$result->fetch_assoc()){ $galleryTypes[$i] = $row; $i++; } $num_results = $result->num_rows; <select name="gallery_type" id="gallery_type"> <option>Please Select an Album <?php for($i = 1; $i < $num_results+1; $i++) { echo "<option value=\"" . $galleryTypes[$i]['gallery_type_id'] . "\">"; echo $galleryTypes[$i]['gallery_type_desc']; echo "</option>\n"; } ?> the code i have got so far: $query1 = "SELECT id, question FROM securtiyq ORDER BY id"; /* run the query */ $result= mysql_query($query1); $row = mysql_fetch_array($result); /* load the query's results into an array */ $i=1; while ($row = mysql_fetch_assoc($result)) { $galleryTypes[$i] = $row; $i++; } $num_results = mysql_num_rows($result); <select name="gallery_type" id="gallery_type"> <option>Please Select A Security Question <?php for($i = 1; $i < $num_results+1; $i++) { echo "<option value=\"" . $galleryTypes[$i]['id'] . "\">"; echo $galleryTypes[$i]['question']; echo "</option>\n"; } ?> </option> </select> the only problem is nothing from the database is displayed in the dropdown box. could someone point out where im going wrong thanks in advance This topic has been moved to MySQL Help. http://www.phpfreaks.com/forums/index.php?topic=305885.0 I wonder whether someone may be able to help me please. I'm trying to put together a PHP within Aurigma Image Uploader which will create an image gallery. To do this I need to extract the image from a folder called 'Thumbnails' and image data from a file called 'files.xml'. The code below is an extract of the default script that performs this functionality and I've tested and it works without any issues. Code: [Select] <?php //This variable specifies relative path to the folder, where the gallery with uploaded files is located. //Do not forget about the slash in the end of the folder name. $galleryPath = 'UploadedFiles/'; $thumbnailsPath = $galleryPath . 'Thumbnails/'; $absGalleryPath = realpath($galleryPath) . DIRECTORY_SEPARATOR; $descriptions = new DOMDocument('1.0'); $descriptions->load($absGalleryPath . 'files.xml'); ?> I have now changed my folder and file structure to the following: UploadedFiles (Folder) username (Subfolder containing the 'location' folder) location (Subfolder containing 'Thumbnails folder and image, and 'files.xml') Please note that both the 'username' and 'location' folders are dynamically created when the user initially uploads the images. To try and accomodate the new file structure I changed my code to: Code: [Select] <?php //This variable specifies relative path to the folder, where the gallery with uploaded files is located. //Do not forget about the slash in the end of the folder name. $galleryPath = 'UploadedFiles/'; $absGalleryPath = realpath($galleryPath) . DIRECTORY_SEPARATOR . $usernamefolder . DIRECTORY_SEPARATOR . $locationfolder . DIRECTORY_SEPARATOR; $thumbnailsPath = $galleryPath . 'Thumbnails/'; $descriptions = new DOMDocument('1.0'); $descriptions->load($absGalleryPath . 'files.xml'); ?> But when I run this I receive the following error: Quote d333603417/htdocs/development/UploadedFiles/files.xml" in /homepages/2/d333603417/htdocs/development/gallery.php on line 14 Line 14 is this line: Code: [Select] $descriptions->load($absGalleryPath . 'files.xml'); I've been working on this for days and I just can't seem to find the answer. I just wondered whether someone could possibly look at this and let me know where I'm going wrong. If it helps, I've added the upload script below. Code: [Select] <?php require_once 'Includes/gallery_helper.php'; require_once 'ImageUploaderPHP/UploadHandler.class.php'; $galleryPath = 'UploadedFiles/'; function onFileUploaded($uploadedFile) { global $galleryPath; $packageFields = $uploadedFile->getPackage()->getPackageFields(); $username=$packageFields["username"]; $locationid=$packageFields["locationid"]; $username = preg_replace('/[^a-z0-9_\-\.()\[\]{}]/i', '_', $_POST['username']); $location = preg_replace('/[^a-z0-9_\-\.()\[\]{}]/i', '_', $_POST['locationid']); $dirName = preg_replace('/[^a-z0-9_\-\.()\[\]{}]/i', '_', $_POST['folder']); $absGalleryPath = realpath($galleryPath) . DIRECTORY_SEPARATOR . $username . DIRECTORY_SEPARATOR . $location . DIRECTORY_SEPARATOR; $absThumbnailsPath = $absGalleryPath . 'Thumbnails' . DIRECTORY_SEPARATOR; if (!is_dir($absGalleryPath)) mkdir($absGalleryPath, 0777, true); chmod($absGalleryPath, 0777); if (!is_dir($absGalleryPath . $dirName)) mkdir($absGalleryPath . $dirName, 0777, true); chmod($absGalleryPath . $dirName, 0777); if ($uploadedFile->getPackage()->getPackageIndex() == 0 && $uploadedFile->getIndex() == 0) initGallery($absGalleryPath, $absThumbnailsPath, FALSE); $originalFileName = $uploadedFile->getSourceName(); $files = $uploadedFile->getConvertedFiles(); $sourceFileName = getSafeFileName($absGalleryPath, $originalFileName); $sourceFile = $files[0]; if ($sourceFile) $sourceFile->moveTo($absGalleryPath . $sourceFileName); $thumbnailFileName = getSafeFileName($absThumbnailsPath, $originalFileName); $thumbnailFile = $files[1]; if ($thumbnailFile) $thumbnailFile->moveTo($absThumbnailsPath . $thumbnailFileName); $descriptions = new DOMDocument('1.0', 'utf-8'); $descriptions->load($absGalleryPath . 'files.xml'); $xmlFile = $descriptions->createElement('file'); // <-- please check the following line $xmlFile->setAttribute('name', $_POST['folder'] . '/' . $originalFileName); $xmlFile->setAttribute('source', $sourceFileName); $xmlFile->setAttribute('size', $uploadedFile->getSourceSize()); $xmlFile->setAttribute('originalname', $originalFileName); $xmlFile->setAttribute('thumbnail', $thumbnailFileName); $xmlFile->setAttribute('description', $uploadedFile->getDescription()); $xmlFile->setAttribute('username', $username); $xmlFile->setAttribute('locationid', $locationid); $xmlFile->setAttribute('folder', $dirName); $descriptions->documentElement->appendChild($xmlFile); $descriptions->save($absGalleryPath . 'files.xml'); } $uh = new UploadHandler(); $uh->setFileUploadedCallback('onFileUploaded'); $uh->processRequest(); ?> Many thanks I have some FLV files above web root. I want to feed my flv player a php file and an ID. I need that php file to return an flv file basically. So if someone has firebug or something they wont see a video path, but instead see something like: fileserve.php?id=4679 I dont care if a logged in user go directly to that link and it prompts them with a download or whatever. I just want to avoid having a non logged in user do that. Hello there, I have a script which uses the LOAD DATA LOCAL INFILE command see below: <?php //connect to your database mysql_connect("localhost", "xxx", "xxx"); //(host, username, password) //specify database mysql_select_db("xxx") or die("Unable to select database"); //select which database we're using // Build SQL Query $query = "LOAD DATA INFILE '/public_html/admin/files/test-jp-stock.csv' INTO TABLE 'jpaero_stocksearch' FIELDS TERMINATED BY ',' LINES TERMINATED BY '\r\n' IGNORE 1 LINES"; if(mysql_query($query)){ echo ">> New Stock Data has now been uploaded. Database is now live and searchable.";} else{ echo "Upload failed. Please contact support.";} ?> Initially I uploaded the csv file through phpmyadmin and everything worked fine - so I then used the SQL generated inside my script, changing the location to where the file actually is - however now nothing happens at all. Any ideas on whats gone wrong, gratefully received! Thanks, What is the best way to load a .jsp file on an external sever? I wonder whether someone may be able to help me please. I've put together the following script which saves user defined images to server folders using the Aurigma Image Uploader software. Code: [Select] <?php require_once 'Includes/gallery_helper.php'; require_once 'ImageUploaderPHP/UploadHandler.class.php'; $galleryPath = 'UploadedFiles/'; function onFileUploaded($uploadedFile) { global $galleryPath; $packageFields = $uploadedFile->getPackage()->getPackageFields(); $username=$packageFields["username"]; $locationid=$packageFields["locationid"]; $usernamefolder = preg_replace('/[^a-z0-9_\-\.()\[\]{}]/i', '_', $_POST['username']); $locationfolder = preg_replace('/[^a-z0-9_\-\.()\[\]{}]/i', '_', $_POST['locationid']); $dirName = preg_replace('/[^a-z0-9_\-\.()\[\]{}]/i', '_', $_POST['folder']); $absGalleryPath = realpath($galleryPath) . DIRECTORY_SEPARATOR . $usernamefolder . DIRECTORY_SEPARATOR . $locationfolder . DIRECTORY_SEPARATOR; $absThumbnailsPath = $absGalleryPath . 'Thumbnails' . DIRECTORY_SEPARATOR; if (!is_dir($absGalleryPath)) mkdir($absGalleryPath, 0777, true); chmod($absGalleryPath, 0777); if (!is_dir($absGalleryPath . $dirName)) mkdir($absGalleryPath . $dirName, 0777, true); chmod($absGalleryPath . $dirName, 0777); if ($uploadedFile->getPackage()->getPackageIndex() == 0 && $uploadedFile->getIndex() == 0) initGallery($absGalleryPath, $absThumbnailsPath, FALSE); $originalFileName = $uploadedFile->getSourceName(); $files = $uploadedFile->getConvertedFiles(); $sourceFileName = getSafeFileName($absGalleryPath, $originalFileName); $sourceFile = $files[0]; if ($sourceFile) $sourceFile->moveTo($absGalleryPath . $sourceFileName); $thumbnailFileName = getSafeFileName($absThumbnailsPath, $originalFileName); $thumbnailFile = $files[1]; if ($thumbnailFile) $thumbnailFile->moveTo($absThumbnailsPath . $thumbnailFileName); $descriptions = new DOMDocument('1.0', 'utf-8'); $descriptions->load($absGalleryPath . 'files.xml'); $xmlFile = $descriptions->createElement('file'); // <-- please check the following line $xmlFile->setAttribute('name', $_POST['folder'] . '/' . $originalFileName); $xmlFile->setAttribute('source', $sourceFileName); $xmlFile->setAttribute('size', $uploadedFile->getSourceSize()); $xmlFile->setAttribute('originalname', $originalFileName); $xmlFile->setAttribute('thumbnail', $thumbnailFileName); $xmlFile->setAttribute('description', $uploadedFile->getDescription()); $xmlFile->setAttribute('username', $username); $xmlFile->setAttribute('locationid', $locationid); $xmlFile->setAttribute('folder', $dirName); $descriptions->documentElement->appendChild($xmlFile); $descriptions->save($absGalleryPath . 'files.xml'); } $uh = new UploadHandler(); $uh->setFileUploadedCallback('onFileUploaded'); $uh->processRequest(); ?> This code saves the files in the following structu UploadedFiles (Pre-existing folder) 'username' (Subfolder created dynamically on image upload if it doesn't already exist. This folder contains the 'location' folder) 'location' (Subfolder created dynamically on image upload if it doesn't already exist. This contains original image, 'files.xml' and 'Thumbnails' folder) 'Thumbnails' (Subfolder created dynamically on image upload if it doesn't already exist. This contains thumbnail of original image) I'm now trying to put together a script which creates an image gallery, with those images pertinent to the current user and location. The code below is the piece of my script which deals with the loading of the images. Code: [Select] <?php $galleryPath = 'UploadedFiles/'; $thumbnailsPath = $galleryPath . 'Thumbnails/'; $absGalleryPath = realpath($galleryPath) . DIRECTORY_SEPARATOR; $descriptions = new DOMDocument('1.0'); $descriptions->load($absGalleryPath . 'files.xml'); ?> The initial problem I had, was resolved from guidance I received on this site, and that was to find the correct 'realpath' of the 'Thumbnails' folder and 'files.xml' These are as follows: Quote /homepages/2/d333603417/htdocs/development/UploadedFiles/IRHM73/1 and Quote /homepages/2/d333603417/htdocs/development/UploadedFiles/IRHM73/1/Thumbnails with 'IRHM73' being the 'username' value and '1' the 'location' value. The problem I now have lies within this line of code: `$absGalleryPath = realpath($galleryPath) . DIRECTORY_SEPARATOR;` Because the 'username' and 'location' are dynamic and hence contain different values for each user and location, I've found it impossible to find a way of creating the correct file path to open the 'Thumbnails' folder and 'files.xml'. I had tried this: Code: [Select] <?php $galleryPath = 'UploadedFiles/'; $absGalleryPath = realpath($galleryPath) . DIRECTORY_SEPARATOR . $usernamefolder . DIRECTORY_SEPARATOR . $locationfolder . DIRECTORY_SEPARATOR; $absThumbnailsPath = $absGalleryPath . 'Thumbnails' . DIRECTORY_SEPARATOR; $descriptions = new DOMDocument('1.0'); $descriptions->load($absGalleryPath . 'files.xml'); ?> But I receive the following error: DOMDocument::load() domdocument.load: I/O warning : failed to load external entity /homepages/2/d333603417/htdocs/development/UploadedFiles/'files.xml'; in /homepages/2/d333603417/htdocs/development/gallery.php on line 13 and line 13 is this: Code: [Select] $descriptions->load($absGalleryPath . 'files.xml'); I really am stumped with what to do next to get this to work. I appreciate that this is a fairly lengthy post, but thought it would be better to post all the information. I just wondered whether someone could perhaps take a look at this and let me know where I'm going wrong and how I can get it to work. Many thanks and regards Hi guys, Should be a simple 1. If i have the following at the top of the page: $page_views = $row['page_views'] + 1; mysql_query("UPDATE table SET page_views='$page_views'"); and then the following at the bottom of the page: echo $row['page_views']; Should I see the page views as 1 the first time the page is visited, 2 the second time the page is visited, and so on......? At the moment im seeing 0 on the first page visit, 1 on the second page visit, 2 on the third..... I had this problem before on another page i was working, and i simply solved it by displaying the mysql query above the echo similar to the code above. However now it does not seem to be working. Am i missing something really simple? lol Thanks |