Jump to content

Goldeneye

Members
  • Posts

    315
  • Joined

  • Last visited

    Never

Everything posted by Goldeneye

  1. The weirdest thing is happening. I'm using this function someone else made getCaretPosition which retrieves the position of the cursor in a textarea. I only use this function for IE. The problem is that the getCaretPosition function seems to return the length of the textarea-value. So if you have the text "abcd" in the textarea (with the cursor between the 'b' and 'c') and press the link, the result will be "ab%%%%%%cd" with the cursor set after the first 4 characters (in this case "ab%%"). The way I have the javascript set up right now, the cursor should not move. Am I missing something? <html> <head> <script type="text/javascript"> function insert_formatText(pre, suf, fid, eid){ if(document.selection){ //Internet Explorer var str = document.selection.createRange().text; document.forms[fid].elements[eid].focus(); var sel = document.selection.createRange(); var caretPos = getCaretPosition(document.forms[fid].elements[eid]); sel.text = pre + str + suf; setCaretPosition(document.forms[fid].elements[eid], caretPos); return; } else if ((typeof document.forms[fid].elements[eid].selectionStart) != 'undefined'){ //Firefox var txtarea = document.forms[fid].elements[eid]; var selLength = txtarea.textLength; var selStart = txtarea.selectionStart; var selEnd = txtarea.selectionEnd; var oldScrollTop = txtarea.scrollTop; var s1 = (txtarea.value).substring(0, selStart); var s2 = (txtarea.value).substring(selStart, selEnd) var s3 = (txtarea.value).substring(selEnd, selLength); txtarea.value = s1 + pre + s2 + suf + s3; //set the cursor in-between the pre and suf parameters var pos = (s1.length + pre.length); txtarea.focus(); txtarea.setSelectionRange(pos, pos); txtarea.scrollTop = oldScrollTop; return; } else document.forms[fid].elements[eid].value += pre + suf; } function setCaretPosition(ctrl, pos){ if(ctrl.setSelectionRange){ ctrl.focus(); ctrl.setSelectionRange(pos,pos); } else if (ctrl.createTextRange) { var range = ctrl.createTextRange(); range.collapse(true); range.moveEnd('character', pos); range.moveStart('character', pos); range.select(); } } function getCaretPosition(ctrl){ var CaretPos = 0; if(document.selection){ // IE Support ctrl.focus (); var Sel = document.selection.createRange (); Sel.moveStart ('character', -ctrl.value.length); CaretPos = Sel.text.length; } else if (ctrl.selectionStart || ctrl.selectionStart == '0') // Firefox support CaretPos = ctrl.selectionStart; return (CaretPos); } </script> </head> <body> <form id="entryform"> <a href="javascript:void(0);" onclick="insert_formatText('%%%', '%%%', 'entryform', 'text');">Bold</a><br /> <textarea id="text"></textarea> </form> </body> </html>
  2. The Math part makes sense to me. But accomplishing it, I can't get my head around. You mean by concatenation? The only reason it doesn't make complete sense is because I am unfamiliar with the pack and unpack functions. Would this be considered as using a bitmask? Or is a bitmask something completely different?
  3. How would I accomplish that? :-\ Well, it's not that I'm explicitly storing checkboxes this way. This is what I implemented for my user-permission system and categorization system.
  4. <?php $abbr_state = mysql_real_escape_string($_POST['abbr_state']); $query=mysql_query("SELECT full_state FROM zip_codes WHERE abbr_state = '".$abbr_state."'") or die("Could not get data from db: ".mysql_error()); $full_state=$result['full_state']; ?> Try that
  5. 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: 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>';
  6. A fairly simple way would be to use the $_SESSION array. This would ensure that each user would not see a page generated by another user which is useful if have a User-account system. $_SESSION['cache'] = array( 'PAGE_NAME' => array( 'html' => 'HTML_HERE', 'time' => 'UNIX_TIMESTAMP' ) ); 'PAGE_NAME' is just the name of the page the cache is for. So say you had three pages (index.php, about.php, contact.php); each page would have its own element in the $_SESSION['cache'] array: $_SESSION['cache']['index.php']; $_SESSION['cache']['about.php'] $_SESSION['cache']['contact.php'] $_SESSION['cache']['PAGE_NAME']['time'] would contain the timestamp (from time()) of when the page is generated. This way, you can check on each page load if the cached content is more than X seconds, minutes, or hours old and if it is, then regenerate the HTML.
  7. Aggregation is a new one to me. I only knew about composition and inheritance but I also knew using $GLOBALS is a poor programming practice as it can easily lead to overwritten data. I read up about using a Registry (a registry pattern) to store Objects in but that seems counter-productive and abusive to the Registry Pattern.
  8. I do know how to do this but I am curious about whether or not there is a "preferred" way to do this. I know there are a couple ways to use a class (I'll call Alpha_Class) within another class (I'll class Beta_Class) Let's say we have this simple class (Beta_Class): class beta { function foo(){ } } If I wanted to use the Alpha Class within the Beta Class, I could any number of things. For example: class beta { function foo(){ $this->alpha = new alpha; //$this->alpha->bar(); } } Or you could simply use the $GLOBALS array to store instantiated objects in: $GLOBALS['alpha'] = new alpha; class beta { function foo(){ //GLOBALS['alpha']->bar(); } } You could even declare Alpha_Class as a static class and thus would not need to be instantiated: static class alpha { static function bar(){} } class beta { function foo(){ //alpha::bar(); } } Those are the only ways I can think of right now. Are there any other ways to accomplish this? I was wondering which way is the best in terms of readability and maintainability.
  9. Trying to set up my wild-card domain so that it will dynamically redirect to a folder. EX) http://x.foo.bar/ redirects to http://foo.bar/x/ Is there anyway to do this with Wild-Card Domains? Or... is it even possible? I tried this but this (but to no avail): <VirtualHost *:80> ServerName foo.bar ServerAlias foo.bar DocumentRoot /home/foo/bar/foo.bar_public ErrorLog /home/foo/bar/foo.bar_private/error_log CustomLog /home/foo/bar/foo.bar_private/access_log combined RedirectMatch * http://foo.bar/$1 </VirtualHost>
  10. session_is_registered is not a native PHP-function; that's most likely where the problem lies. Also, if myusername is supposed to be a variable, make sure you prepend a dollar-sign to it so it becomes: $myusername
  11. Trying to improve my script-architecture, I got curious about other ways to pass application-data around aside from using the$GLOBALS array. The only other way I really found was to use an object called a "Registry". I just ended up being confused regarding when which method is better than the other, let alone how to even use a registry-object in my scripts. So my questions are: - When is it better to use a registry object in place of global data? - how would you use a registry? - how would a registry object get passed around, through other objects and functions? Heres the registry I found... class registry { var $_cache_stack = array(); function __construct(){ $this->_cache_stack = array(array()); } function set($key, &$item){ $this->_cache_stack[0][$key] = &$item; } function &get($key){ return $this->_cache_stack[0][$key]; } function isEntry($key){ return ($this->getEntry($key) !== null); } function &instance(){ static $registry = false; if (!$registry) $registry = new Registry(); return $registry; } function save(){ array_unshift($this->_cache_stack, array()); if (!count($this->_cache_stack)) exit('Registry lost!'); } function restore(){ array_shift($this->_cache_stack); } }
  12. $prod $_GET['id']; should be... $prod = $_GET['id'];
  13. You can't parse [X]HTML with regex. Because HTML can't be parsed by regex. Regex is not a tool that can be used to correctly parse HTML. As I have answered in HTML-and-regex questions here so many times before, the use of regex will not allow you to consume HTML. Regular expressions are a tool that is insufficiently sophisticated to understand the constructs employed by HTML. HTML is not a regular language and hence cannot be parsed by regular expressions. Regex queries are not equipped to break down HTML into its meaningful parts. so many times but it is not getting to me. Even enhanced irregular regular expressions as used by Perl are not up to the task of parsing HTML. You will never make me crack. HTML is a language of sufficient complexity that it cannot be parsed by regular expressions. Even Jon Skeet cannot parse HTML using regular expressions. Every time you attempt to parse HTML with regular expressions, the unholy child weeps the blood of virgins, and Russian hackers pwn your webapp. Parsing HTML with regex summons tainted souls into the realm of the living. HTML and regex go together like love, marriage, and ritual infanticide. The <center> cannot hold it is too late. The force of regex and HTML together in the same conceptual space will destroy your mind like so much watery putty. If you parse HTML with regex you are giving in to Them and their blasphemous ways which doom us all to inhuman toil for the One whose Name cannot be expressed in the Basic Multilingual Plane, he comes. HTML-plus-regexp will liquify the n​erves of the sentient whilst you observe, your psyche withering in the onslaught of horror. Rege̿̔̉x-based HTML parsers are the cancer that is killing StackOverflow it is too late it is too late we cannot be saved the trangession of a chi͡ld ensures regex will consume all living tissue (except for HTML which it cannot, as previously prophesied) dear lord help us how can anyone survive this scourge using regex to parse HTML has doomed humanity to an eternity of dread torture and security holes using regex as a tool to process HTML establishes a breach between this world and the dread realm of c͒ͪo͛ͫrrupt entities (like SGML entities, but more corrupt) a mere glimpse of the world of reg​ex parsers for HTML will ins​tantly transport a programmer's consciousness into a world of ceaseless screaming, he comes, the pestilent slithy regex-infection wil​l devour your HT​ML parser, application and existence for all time like Visual Basic only worse he comes he comes do not fi​ght he com̡e̶s, ̕h̵i​s un̨ho͞ly radiańcé destro҉ying all enli̍̈́̂̈́ghtenment, HTML tags lea͠ki̧n͘g fr̶ǫm ̡yo​͟ur eye͢s̸ ̛l̕ik͏e liq​uid pain, the song of re̸gular exp​ression parsing will exti​nguish the voices of mor​tal man from the sp​here I can see it can you see ̲͚̖͔̙î̩́t̲͎̩̱͔́̋̀ it is beautiful t​he final snuffing of the lie​s of Man ALL IS LOŚ͖̩͇̗̪̏̈́T ALL I​S LOST the pon̷y he comes he c̶̮omes he comes the ich​or permeates all MY FACE MY FACE ᵒh god no NO NOO̼O​O NΘ stop the an​*̶͑̾̾​̅ͫ͏̙̤g͇̫͛͆̾ͫ̑͆l͖͉̗̩̳̟̍ͫͥͨe̠̅s ͎a̧͈͖r̽̾̈́͒͑e n​ot rè̑ͧ̌aͨl̘̝̙̃ͤ͂̾̆ ZA̡͊͠͝LGΌ ISͮ̂҉̯͈͕̹̘̱ TO͇̹̺ͅƝ̴ȳ̳ TH̘Ë͖́̉ ͠P̯͍̭O̚​N̐Y̡ H̸̡̪̯ͨ͊̽̅̾̎Ȩ̬̩̾͛ͪ̈́̀́͘ ̶̧̨̱̹̭̯ͧ̾ͬC̷̙̲̝͖ͭ̏ͥͮ͟Oͮ͏̮̪̝͍M̲̖͊̒ͪͩͬ̚̚͜Ȇ̴̟̟͙̞ͩ͌͝S̨̥̫͎̭ͯ̿̔̀ͅ [as cited from http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454]
  14. Well, you seem to be missing a set of braces around your "if()..." statement, you're also missing quotes around Admin (in your if statement). You should use the isset function to check if a variable isset. Finally, your code structure can be consolidated/augmented. Try this: session_start(); if (isset($_SESSION['username'])){ if ($_SESSION['username'] != 'Admin') echo "Welcome, ".$_SESSION['username']. "!<br /><a href='settings.php'>Settings</a><br /><a href='logout.php'>Logout</a>"; else echo "Welcome, ".$_SESSION['username']. "!<br /><a href='logout.php'>Logout</a><br /><a href='admin/index.php'>Admin Area</a>"; } else die("You must be logged in!");
  15. What exactly do you want this regular expression to do? You want it to match alphabetic-characters at the beginning of a string? If so, it appears to be working fine for me: <?php $input='hjkhk$#@$@'; preg_match_all("/^[A-Za-z]{1,20}/",$input,$match); print_r($match); ?> produces: Array ( [0] => Array ( [0] => hjkhk ) )
  16. Well, without registration, you really only have a person's Internet Protocol Address to rely on. And that is not a very reliable way to identify a user especially since a lot of your guests might have Dynamic IP addresses meaning their IP Address will change regularly. One thing you could do is if users wish to come back to your site, give them an option to "download" or "save" a unique-Identification number which you assign to them as a file and then have them upload that file (per session) as they return to the site. It's might not be what you had in mind but it also isn't registration or forcing users to provide their e-mail address.
  17. Okay, I have figured out what I was doing wrong, and as embarrassing as this is... I should've been using (\S*?) instead of (.*?). I was simply replacing the wrong character with the \S. This hit me when I realized that periods (.) tell the regex to match any character except for a linebreak. My regular expression does appear to be working now. So, if you want a sub-class to match anything up to a linebreak, tab, space, or return; use: (\S*?). It should be noted that \S symbolizes non-whitespace characters
  18. What would I use to explicitly match strings that do not span multiple lines? I thought, (.\S?) (instead of the less partial (.*?)) would do accomplish what I want, but it doesn`t. I`ve also searched around (this forum included) but haven`t found anything relevant which leads me to believe that I might be over-thinking this.
  19. I just noticed, PEAR/Mail_IMAP and it`s v2 child both require the PHP IMAP Extension as a dependancy. This means, I can`t use it because the PHP IMAP extension is not installed; doesn't it? Edit: It doesn`t appear to be working for me, anyway. I have setup my server-settings exactly as they should be but I still get, `Error: Unable to build a connection.`
  20. Please excuse my ignorance: Being a PEAR virgin, I really have no idea how to install this. I`ve looked at tutorials found through a Goolge Search, but I am finding them too ambiguous or simply not working for me. I tried ''pear install Mail_IMAP-1.1.0RC2'' in a PuTTY session but that didn`t work. How do I manually install it?
  21. Well, I`m trying to create a script or class to interface PHP and MySQL with an IMAP server. I would use the PHP IMAP-Extension but because it isn`t a standard extension, it`s not complied on the Webserver I`m currently using. What I currently have is... $username = 'foo'; $password = 'bar'; $handle = fsockopen('localhost', 143, $errint, $errstr, 15); $query = 'LOGIN {' . strlen($username) . "}\r\n$username". ' {' . strlen($password) . "}\r\n$password"; fputs($handle, $query); $query = 'SELECT INBOX'; fputs($handle, $query); $query = 'FETCH 8 BODY[]'; fputs($handle, $query); echo fgets($handle); I thought the code would work but all that is echo`d is * OK Dovecot ready. So, how do I go about connecting to (and reading from) an IMAP Server using sockets?
  22. Thank you, PFMaBiSmAd! That worked exactly as it should have. I must admit I am amazed at how it only took about 1 second to fully insert all 2666392 rows. It is exponentially faster than PHP. :-)
  23. My objective consists of converting a flat-file into a MySQL-file. My problem occurs while trying to read all the contents of a file via the fgets function. I get the usual: "Fatal error: Out of memory (allocated 387973120) (tried to allocate 129212411 bytes)." I tried setting the "memory_limit" and "max_execution_time" limit to limitless which it still gave me the error which leaves me to believe that the problem I'm encountering is hardware related. Is there anyway to break this file up into sections (using PHP) or ever sort of... "paginating" it? I could split the file manually but with ~2 600 000 lines, that'll take an extremely long time. <?php ini_set('memory_limit', -1); set_time_limit(0); $handle = fopen('imports/flatfile.txt', 'r'); echo 'INSERT INTO `districtbase` (`districtkey`, `name`, `countrykey`, `regionkey`) VALUES '; while($line = fgets($handle, filesize('imports/flatfile.txt'))){ $cells = explode(',', $line); echo '("'.$cells[1].'", "'.$cells[2].'", "'.$cells[0].'", "'.$cells[3].'"),<br/>'; } ?> SAMPLE-DATA: CountrSHy,CityKey,CityName,Region,Latitude,Longitude ad,aixas,Aixàs,06,,42.4833333,1.4666667
  24. Give your getName() function a parameter like so: <?php function getName($name){ //do stuff here } ?> That's how you would pass an outside variable into a function. (There are other ways, as well). And that way, you can do this: <?php $person_name = 'Mike'; $obj->getName($person_name); ?>
  25. That is a good point. With my system, you'd want to implement a last-active field as well. Which would defeat the purpose of the `active` field I talked about.
×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.