-
Posts
293 -
Joined
-
Last visited
-
Days Won
5
Everything posted by jodunno
-
I have decided to update the sample page that i posted earlier. I shouldn't assume that you know what is missing. I've added the session start and even modified the output pages for a better experience. <?php declare (strict_types = 1); //session_start(); //if (empty($_SESSION['userID'])) { header("Location: /"); exit; } (string) $SID_page = 'getForm'; (string) $SID_pageTitle = 'Upload files'; switch ($_SERVER["REQUEST_METHOD"]) { case 'GET': /* use this area to set any variables required for the get page, et cetera */ break; case 'POST': (string) $SID_errors = ''; (array) $SID_filesArrayErrors = ['4'=>'Please choose a file for upload']; if (!empty($_FILES['Upload']['error'])) { if (array_key_exists($_FILES['Upload']['error'], $SID_filesArrayErrors)) { $SID_errors = $SID_filesArrayErrors[$_FILES['Upload']['error']]; break; } $SID_errors = 'Error uploading file. Please try again.'; break; } if (preg_match('/^[0-9A-Za-z-_.\s]{1,64}.jpg|jpeg|jpe|png|gif$/', $_FILES['Upload']['name']) === 0) { $SID_errors = 'Invalid file: Filenames must be Alphanumeric with the following acceptions: - _ . and word spaces. Filetypes must be jpg/jpeg, png or gif'; break; } if (function_exists(pathinfo($_FILES['Upload']['name'], PATHINFO_FILENAME))) { error_log("attention! filename contains a function name: " . pathinfo($_FILES['Upload']['name'], PATHINFO_FILENAME)); /* $SID_errors = 'hack attempt'; */ break; } /* catches built-in functions: phpinfo, phpinfo(), file_get_contents et cetera. use prefixes for all user defined code (here $SID_, stands for site id). */ $SID_dir = 'folder/'; $SID_timestamp = time(); $SID_filename = $SID_dir . $SID_timestamp.basename($_FILES['Upload']['name']); move_uploaded_file($_FILES['Upload']['tmp_name'], $SID_filename); $SID_page = 'postForm'; $SID_pageTitle = 'Files upload'; break; } ?> <!DOCTYPE html> <html> <head> <title><?php if (!empty($SID_pageTitle)) { echo $SID_pageTitle; } ?></title> </head> <body> <div data-role="page" id="page"> <div data-role="header"> <h1>Upload files</h1> <a href="logout.php" data-role="button" data-icon="home">Sign out</a> </div> <?php switch ($SID_page) { case 'getForm': ?> <div data-role="content"> <?php if (!empty($SID_errors)) { echo '<div><p>' . $SID_errors . '</p></div>'; } ?> <form method="post" enctype="multipart/form-data"> <input type="file" name="Upload" required> <input type="submit"> </form> </div> <?php break; case 'postForm': /* var_dump($_FILES); */ echo '<p>File was uploaded --> '. htmlspecialchars(urlencode($_FILES['Upload']['name']), ENT_QUOTES); echo '<br>'; echo '<p>Information about file from $FILE array</p>'; echo 'File Name: ' . htmlspecialchars(urlencode($_FILES['Upload']['name']), ENT_QUOTES) . '<br>'; echo 'File Type: ' . htmlspecialchars($_FILES['Upload']['type'], ENT_QUOTES) . '<br>'; echo 'File Size: ' . $_FILES['Upload']['size'] . 'kB<br>'; ?> <div data-role="content"> <p>Would you like to upload another file?</p> <form method="post" enctype="multipart/form-data"> <input type="file" name="Upload" required> <input type="submit"> </form> </div> <?php break; } ?> </div> </body> </html>
-
I try to help out whenever i am able to do so. Regular php specialists answer alot of questions here so i try to give back to the community. I am not a programmer but i'm learning programming slowly. I know what it is like to be a beginner and the stress of trying to get code to work. I apologize for the regex error. I sometimes copy and paste my regex expressions and tweak them to a new design. I forgot to remove the brackets. Try this code instead: if (preg_match('/^[0-9A-Za-z-_.\s]{1,64}.jpg|jpeg|jpe|png|gif$/', $_FILES['Upload']['name']) === 0) { $SID_errors = 'Invalid file: Filenames must be Alphanumeric with the following acceptions: - _ . and word spaces. Filetypes must be jpg/jpeg, png or gif'; break; } Requinix is a regex specialist here. If you have further troubles with regex, then post a thread in the regex subforum. I'm sure that you notice some missing code, like session start. I assume that you know to add it in order to read from the session. Also, i have erroneously applied htmlspecialchars to the file size, which should be integer instead. Furthermore, you shouldn't alert an internet user about the function exists, just log it and either disallow the name or change it in the code while storing the original name for download purposes. You have mentioned that the site is to be local and not online, so i suppose you could just skip this code anyway. I hope that you have a good day and please inform me of any other problems with my sample file. I may have overlooked some things.
-
so i had some free time to code a better example page for you while preserving some of your original content. I strongly disagree that you need to submit the form to the same page [rolling my eyes] but do whatever feels best for you. <?php declare (strict_types = 1); // if (empty($_SESSION['userID']) { header("Location: /"); exit; } (string) $SID_page = 'getForm'; (string) $SID_pageTitle = 'Upload files'; switch ($_SERVER["REQUEST_METHOD"]) { case 'POST': (string) $SID_errors = ''; (array) $SID_filesArrayErrors = ['4'=>'Please choose a file for upload']; if (!empty($_FILES['Upload']['error'])) { if (array_key_exists($_FILES['Upload']['error'], $SID_filesArrayErrors)) { $SID_errors = $SID_filesArrayErrors[$_FILES['Upload']['error']]; break; } $SID_errors = 'fileArray'; break; } if (preg_match('/^[0-9A-Za-z-_.\s]{1,64}.[jpg|jpeg|jpe|png|gif]+$/', $_FILES['Upload']['name']) === 0) { $SID_errors = 'Invalid filename (Filenames must be Alphanumeric with the following acceptions: - _ . and word spaces)'; break; } if (function_exists(pathinfo($_FILES['Upload']['name'], PATHINFO_FILENAME))) { /* log this error */ $SID_errors = 'hack attempt'; break; } /* catches built-in functions: phpinfo, phpinfo(), file_get_contents et cetera. use prefixes for all user defined code (here $SID_, stands for site id) */ $SID_dir = 'folder/'; $SID_timestamp = time(); $SID_filename = $SID_dir . $SID_timestamp.basename($_FILES['Upload']['name']); move_uploaded_file($_FILES['Upload']['tmp_name'], $SID_filename); $SID_page = 'postForm'; $SID_pageTitle = 'Files upload'; break; } ?> <html> <head> <title><?php if (!empty($SID_pageTitle)) { echo $SID_pageTitle; } ?></title> </head> <body> <?php switch ($SID_page) { case 'getForm': ?> <div data-role="page" id="page"> <div data-role="header"> <h1>Upload files</h1> <a href="logout.php" data-role="button" data-icon="home">Sign out</a> </div> <div data-role="content"> <?php if (!empty($SID_errors)) { echo '<div><p>' . $SID_errors . '</p></div>'; } ?> <form method="post" enctype="multipart/form-data"> <input type="file" name="Upload"> <input type="submit"> </form> </div> </div> <?php break; case 'postForm': /* var_dump($_FILES); */ echo '<p>File was uploaded --> '. htmlspecialchars(urlencode($_FILES['Upload']['name']), ENT_QUOTES); echo '<br>'; echo '<p>Information about file from $FILE array</p>'; echo 'File Name: ' . htmlspecialchars(urlencode($_FILES['Upload']['name']), ENT_QUOTES) . '<br>'; echo 'File Type: ' . htmlspecialchars($_FILES['Upload']['type'], ENT_QUOTES) . '<br>'; echo 'File Size: ' . htmlspecialchars($_FILES['Upload']['size'], ENT_QUOTES) . 'kB<br>'; /* one could add the form here too for more uploads but a user limit should be placed in a database then loaded into the session at login or retrieved from the db on pageload */ break; } ?> </body> </html> good luck to you. You may want to ask requinix about my regex code. I am not a programmer either, so perhaps my regex could be better. Have a nice day.
-
Hello again, i have copied the two files named upload_home.php and fileUpload.php to my xampp installation. I altered the code a bit with request method and tried he form. The path set in the dir variable was incorrect. I used a folder named uploads and placed a folder in the uploads folder named folder and the code works for me. upload.php <html> <head> <title>Upload files</title> </head> <body> <div data-role="page" id="page"> <div data-role="header"> <h1>Upload files</h1> <a href="logout.php" data-role="button" data-icon="home">Sign out</a> </div> <div data-role="content"> <form action="/upload/fileUpload.php" method="post" enctype="multipart/form-data"> <input type="file" name="Upload"> <input type="submit"> </form> </div> </div> </body></html> fileUpload.php <html> <head> <title>Fileupload</title> </head> <body> <?php if ($_SERVER['REQUEST_METHOD'] === 'POST') { $dir = "folder/"; $timestamp = time(); $filename = $dir.$timestamp.basename($_FILES['Upload']['name']); var_dump($_FILES); echo '<br><br>'; if (move_uploaded_file($_FILES['Upload']['tmp_name'], $filename)){ echo '<p>File was uploaded --> '.$_FILES['Upload']['name']); } else { echo 'Upload failed'.$_FILES['Upload']['name']); } echo '<p>Information about file from $FILE array</p>'; echo 'File Name: '.$_FILES['Upload']['name'].'<br>'; echo 'File Type: '.$_FILES['Upload']['type'].'<br>'; echo 'File Size: '.$_FILES['Upload']['size'].'kB<br>'; } ?> </body></html> so it seems as though your path to folder is incorrect. You should enable php errors because it will show you a 'cannot move to folder' message.
-
you forgot to close the if condition in the login upload php file: <?php session_start(); if (isset($_SESSION['id']) && isset($_SESSION['user_name'])) { somewhere over the rainbow: <?php } ?> i recommend switching the request method and checking $_POST with empty over isset (simply typing a zero passes isset) also change your logic from if...elseif..else to if alone switch ($_SERVER['REQUEST_METHOD']) { case 'GET': //get lost code or friendly page break; case 'POST': if (empty($_POST['username'])) { /*set error and leave or just leave + exit; etc.*/ } if (empty($_POST['password'])) { /*set error and leave or just leave + exit; etc.*/ } /*rest of your code*/ break; } i recommend hashing passwords and using hash_equals to verify passwords i recommend storing the sha1 value of usernames and comparing hashes versus plaintext i also recommend using pdo for database interaction good luck...
-
try the magical span 'shroom. It works for me in edge/chrome and ff: <style> .ripple { background: -webkit-linear-gradient(0deg,#7521ff 20%,#33b6f1 50%,#b8ff21 80%); -webkit-background-clip: text; background-clip: text; -webkit-text-fill-color: transparent; } .see { width: 400px; font-family: coolvetica; font-size: 6em; line-height: 0.8em; box-sizing: content-box; } </style> <div class="see"><span class="ripple">Big time hosting<wbr> Low cost design</span></div> <br> <div> <div class="see"><span class="ripple">Big time hosting</span></div> <div class="see"><span class="ripple">Low cost design</span></div> </div> and you should still be able to adjust the line height *warning: calculated line-height adjustments may also need to be added to parent elements in certain cases
-
please learn html5 and css3. Such advice leads to lazy front-end coding. And div elements default to left alignment, which means that one has not read the dtd and browser defaults. One can align divs anyway that one desires using css3. I am not going to design a site for someone. I have no free time to spare. However, here is a quick example of aligning the divs the way that you want them using html5 and css3. Also responsive using @media. <html> <head> <title></title> <style> div { display: block; position: relative; margin: 0px; padding: 0px; border: none; outline: none; opacity: 1; box-sizing: content-box; } div.columnContainer { background: #dcdcdc; min-width: 308px; max-width: 100%; box-sizing: content-box; } div.leftColumn { display: inline-block; width: 30%; background: #a0a0a0; vertical-align: top; } div.leftColumnRow { max-width: 100%; margin: 2px; padding: 6px; background: #f0f0f0; text-align: center; } div.rightColumn { display: inline-block; width: 69%; background: #a0a0a0; vertical-align: top; } div.rightColumnRow { max-width: 100%; margin: 2px; padding: 6px; background: #101010; } img.rightColumnImage1 { display: block; width: 200px; height: 50px; } @media (max-width: 600px) { div.leftColumn, div.rightColumn { display: block; min-width: 99%; } div.leftColumnRow, div.rightColumnRow { display: block; min-width: 92%; } } </style> </head> <body> <div class="columnContainer"> <div class="leftColumn"><!-- browsers default is left align and div is a block element, so no need to float or use a grid or flex --> <div class="leftColumnRow">Hello</div> <div class="leftColumnRow">Hello again</div> </div> <div class="rightColumn"> <div class="rightColumnRow"><img class="rightColumnImage1" src="no_float_grid_flex_equals_good_html5_programming.png"></img></div> </div> </div> </body> </html>
-
xampp php session files and firefox browser
jodunno replied to jodunno's topic in PHP Installation and Configuration
Hi everyone, bananaman: you really do not know how to set a session variable and unset it? you need to see that code? O.O good thing that i have solved the problem. session_start either continues a session or starts a new one. I learned PHP at home and using forums for help when needed. I was always told to use session_start() on every page that uses 'the' session. It seems as though this is not correct or a certain usage exists that is not described in the PHP manual. I decided to name my session cookies in the php.ini file, then add an if statement in the getImage.php file. so if mycookie isset then session_start(), else show image error. Meantime, i maintain multiple versions of browsers for html and css testing. The start a new session only happens in older versions of firefox (50, 51, 60). The curent 108 does not make a new session file. Anyway, my understanding of sessions is the problem here and that is a big problem since the official manual does not address proper session handling and usage in depth. I have to learn how to handle sessions properly before continuing to develop websites. Thank you for taking time to read this post. I hope that everyone has a lovely New Year's eve. Please be safe and do not drink alcohol and drive. I hate alcohol so it is not a problem for me but i am concerned about all of you. John -
Hi everyone, I am having a problem with a xampp php installation regarding session file generation using firefox browser. problem: i create a session variable which acts as a token on the server side. The token is used to display an image, then the token (session array key) is deleted. Thus, i am able to prevent access to protected images. Everything is working, in Edge and Chrome. Whenever i use firefox browser to test the site on xampp, i notice a session file creation in the tmp file. I go to Tools > Page Info > Media tab. My images do not appear in the media tab (which is good because they are protected.) However, every time that i click on one of the media links in the tab, a new session file is created in the tmp directory of my xampp installation (size 0bytes). It seems like PHP or xampp is not managing sessions correctly. A new session is started for each image requested from the firefox pageinfo media tab. Should i report this to xampp or is there another reason why this is happening? should i manually set session handlers? has anyone else noticed this problem? Thank you, John
-
That is excellent advice, requinix. Thank you for taking time to help a non-programmer. I always appreciate this forum and its members despite my agression at times. LOL. what i can say, i'm a bit of a weight lifting pesky wasp. I have made a text file with your advice and i will read more about this subject. I always make an effort to better myself so i promise that your advice is well taken. I am going to shutdown my xampp for the day and relax a bit. I am still trying to feel normal after covid and the flu. I started playing Grim Tales games (not spamming here but how else do i describe the games?) I can just sit back and click my way through a game. I hope that everyone has a great day and i cannot stress enough the importance of well being. Take care of yourselves. John
-
Hi requinix and anyone else reading this post, The code that uses this expression is as follows working directories: C:\xampp C:\xampp\htdocs\qs.php <?php declare (strict_types = 1); //example request: http://localhost/qs.php?legal_copyright function checkGetRequest(string $queryString = '') { if (preg_match("/^[A-Za-z]{3,16}+_[A-Za-z]{3,48}$/", $queryString) === 0) { return false; } (array) $queryString = explode('_', $queryString); (string) $path = dirname(__FILE__) . '/../system/paging/'; if (!file_exists($path) || !file_exists($path . $queryString[0] . '/definition.php')) { return false; } require_once $path . $queryString[0] . '/definition.php'; if (!function_exists('definition')) { return false; } unset($path); if (definition($queryString[1]) !== true) { return false; } return (array) $queryString; } if (!empty($_SERVER['QUERY_STRING']) && is_string($_SERVER['QUERY_STRING']) && function_exists('checkGetRequest')) { (array) $showPage = checkGetRequest(trim(htmlspecialchars($_SERVER['QUERY_STRING']))); if ($showPage !== false && is_array($showPage)) { print_r($showPage); exit; } unset($showPage); } echo 'index page'; exit; ?> C:\xampp\system\paging\ (outside root) C:\xampp\system\paging\legal\definition.php (array of acceptable page requests) <?php declare (strict_types = 1); function definition(string $validity = '') { $pages = (array) ['agb','copyright','datenschutz','impressum','kontakt','uberuns']; if (in_array($validity, $pages, true)) { unset($pages); return true; } unset($pages); return false; } ?> category exists to allow hundreds of possibilities. a switch with more than 10 cases is ridiculous, so i 'switched' to a category and page system. I am aware of everyone's attitude about exit and error handling and cleanup work but i am not open to changing the code. I always clean up after myself in reality and i do the same in my code (unset). I like it that way. I also like to handle foreseen errors (a file doesn't exist or a call to an array loads a string instead. I try to handle known possible erros, which makes me happy. So besides my coding methods, if you spot anything that could be done better, then offer an opinion. Happy Holidays everyone and please stay healthy and warm. We are living in difficult times. John
-
oh wow! I missed that entirely. I honestly did not realize that i had that flag. I copied a similar expression from my form validation and changed the core of the expression. I'm not trying to make an excuse for overlooking this stupidity but my brain is a little foggy lately. I had covid immediately followed by the flu a few weeks ago. I was not well and i am still trying to feel normal. I cannot believe how many times that i have looked at this code and did not notice the i Honestly, Thank You for cleaning this up for me. Meantime, i will post my experimental code so that you can see how it is used. I need to copy the code from my non-internet connected work laptop, then i will post it. I have tried the restrictions in everyway that i can imagine and the regex is working as expected. So once again, Thank you, requinix. I appreciate and value your expertise.
-
Hi requinix, I was hoping that you would offer an opinion, since you are an actual regex specialist. I actually learned the basics of regex from your posts at this forum. I don't want to say that i credit you entirely because i am prone to erroneous regex logic at times and you are not responsible for the bad regex solutions of mine. Anyway, the links are a beautiful addition to your reply. Thank you for posting 🙂 well, our viewpoint is obviously different. I only use index.php and accept requests for content that fits my definition of acceptable content requests. Thus, the location/resource/route is the same. Only the content changes. So i don't consider it to be routing traffic, rather fetching different content for display in the same location. Routers typically involve mvc or classes, functions and frameworks. You know, call a class, which calls a class, which loads a function, which loads another function to echo a message instead of using the built-in echo function. LOL. Please let's not start a router definition, i should be using mvc argument. I actually like and respect you, requinix. I hope that you can reciprocate that sentiment 🙂 either way, if you must see my usage, then i don't mind posting my code but it would not be open to discussion 🙂 Happy Holidays and please stay healthy and warm, John
-
Dear members, I'm building a get request file handler (sometimes erroneously referred to as a router) and i need to restrict the query string to a particular format using regex. goal: restrict a GET query string format to: category_page (id est, http://localhost/file.php?category_page) so Alphabetic letters of length 3 to 16 characters followed by an underscore followed by alphabetic letters of length 3 to 48 characters my current regex is contained within a "checkGetRequest()": if (preg_match("/^[A-Za-z]{3,16}+_[A-Za-z]{3,48}$/i", $queryString === 0) { return false; } is this regex correct? or perhaps someone can stop laughing and correct me? the regex seems to be working but i'm not a regex guru. Happy Holidays, John
-
okay, i see. you are the big php gorilla in the room and you want to pound your chest when someone is out of place challenging you. i didn't expect this behaviour from you. You are always right. You are omniscient and i should bow down to you. Fine, i kow tow your excellency. You are so much smarter than me. I'm have no iq. I no nothing about programming. Only Barand knows. I will add to my notes: modulus is defined in php with an illogical % symbol (per centum, 100). modulus only exists because of php. So when you see a ≡ b (mod n) it was invented by php developers. gotcha. I will be sure to find my place in stuporville. I know nothing so i should not contribute to this forum. I should only ask questions from the Wizard of Oz but never look behind the curtain. I will stay away from this forum and let you pound your chest.
-
"The modulo operator was invented for situations like this" it was invented? it was invented to handle division? it was invented to handle division by 5? I'm pretty sure that remainders are as old as division. The term is simply a word to refer to them and the concept is a way to work with them.
-
hmm. I didn't think about modulus so it is a better example of reducing the code but your definition of it is not correct. Modulus is simply remainder and calculating using remainder (hence, ==0 means no remainder.) I learned that years ago when i encountered modulus in a Microsoft QBasic Gorilla game. I never heard of it before since my Math teachers only used the word remainder. Then again, I never had a proper algebra or calculus education. I had to teach myself (using teach yourself books). Good contribution, Barand.
-
I have tried scaling before and it failed because browsers seem to keep the space of the original size. Thus multiple scaled items will not adjust to the new size in proportion with the page. I cannot remember exact details but it was horrible. I don't think any changes have been made to the rendering engines, so the problem should still remain.
-
Hi Lumana, You could reduce the comparison branching to a single comparison with a count . <?php $Count = 5; for ($j = 1; $j < 101; $j++) { if ($j == $Count) { echo $j . ' Boogie Woogies' . '<br>'; $Count += 5; continue; } echo $j . '<br>'; } ?>
-
yes it is 12. i made an erroneous mental calculation and i saw it after i posted.. i didn't want to log back in to correct it. ixiiv is still nonstandard and i intend to filter it out. I'm working on the code...
-
update: so i used my decimal to roman numeral code inside of a loop in my roman to decimal code. All of the numbers passed, which means my code is not filtering standard roman numerals. Super! i changed an entry in the loop to a numeral that should be considered non standard and my code stopped the loop and displayed the invalid message. so the code is working. Then i used the decimal to roman code to produce an array of all of the standard roman numerals, then i used the var_export to create a copy of this good numerals array. I made a copy of the array produced in the roman to decimal converter that passed through the filtering process. I made a new php file named compare.php. I pasted both arrays into compare.php, then i created a loop that compares the values. If any value is different, then show the different value via echo. Continue the loop until it is finished. The result is a blank page, which confirms that good numerals are not filtered. Yippee! However, i did notice that a nonstandard numeral still passes through my filter: xxxliiv. Now i permit nonstandard subtraction of numerals up to five, so iiv is okay. xxxl has not been handled. I have no filter for higher numeral subtractions. I think that i could make a rule that two non-standard subtractions should not occur in the same processed number. I am not yet sure if that idea works or not. But i can say that artificial intelligence could help me here. Imagine including my decimal to roman code inside of the same file as the roman to decimal code. I could calculate a good numeral based upon the total of the submitted numeral. Then compare the code and if the submitted code is different, then i will know that you are adding or subtracting to reach the nonstandard form of the decimal. Then i could check, i guess, powers of ten? 54 should have a fifty or L. Otherwise, you did something to reach 50 which is non standard. Thus, ixiiv should fail because the total is 14 which is between 10 and 20, yet the equation does not have a X (10). You did something strange to reach the number. If i can add such code to my current code, then i should have a splendid converter.
-
interesting. I can't believe that my code is even remotely similar to yours. I am not a very good programmer so it is nice to know that i did something correctly. I suppose that i am a bit too hard on myself. Really though, i am still trying to comprehend how i wrote code that is similar to your code. You are a pro and i am just a programmatic idiot trying to make a website. I guess i am slowly learning how to think programmatically. So progress is good 😀 but i don't let it go to my head. I got lucky this time and did something right. I am going to get some coffee and get to work on my roman to decimal converter.
-
Hi Barand, I created a script for decimal to roman last week. I am certain that my approach is different than yours but i get the job done. I added a loop so that my code prints numerals 1-3999. Decimal to Roman is easy if we only convert to standard Roman numerals. Converting from unknown possibly nonstandard possibly invalid roman numerals to decimal is a bit more difficult. I suppose that one could make a 3999 roman numeral valued array and call it a day but i like to try to solve the problems programmatically. If failure happens and i can't find a way to filter correctly then the 3999 value array is my only hope. Here is my Decimal to Roman converter using basic arithmetic of places. Everyone, take your places! 😃 <?php //John's PHP Decimal number to Roman Numeral converter v1 $Ones = array('I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX'); $Tens = array('X', 'XX', 'XXX', 'XL', 'L', 'LX', 'LXX', 'LXXX', 'XC'); $Hundreds = array('C', 'CC', 'CCC', 'CD', 'D', 'DC', 'DCC', 'DCCC', 'CM'); $Thousands = array('M', 'MM', 'MMM'); for ($j = 1; $j < 4000; $j++) { $PlaceCount = strval(strlen($j)); $Places = str_split($j); $RomanNumeral = null; switch ($PlaceCount) { case '1': $RomanNumeral = $Ones[$j - 1]; break; case '2': $RomanNumeral .= $Tens[$Places[0] - 1]; if (!empty($Places[1])) { $RomanNumeral .= $Ones[$Places[1] - 1]; } break; case '3': $RomanNumeral .= $Hundreds[$Places[0] - 1]; if (!empty($Places[1])) { $RomanNumeral .= $Tens[$Places[1] - 1]; } if (!empty($Places[2])) { $RomanNumeral .= $Ones[$Places[2] - 1]; } break; case '4': $RomanNumeral .= $Thousands[$Places[0] - 1]; if (!empty($Places[1])) { $RomanNumeral .= $Hundreds[$Places[1] - 1]; } if (!empty($Places[2])) { $RomanNumeral .= $Tens[$Places[2] - 1]; } if (!empty($Places[3])) { $RomanNumeral .= $Ones[$Places[3] - 1]; } break; } echo $RomanNumeral . '<br>'; } ?>
-
Hi Barand, Thank you for the lovely gift 🙂 I will finish testing today. I have a physical therapy session in the afternoon. Hopefully, i can put it all together after my appointment. I think that the program is working as expected but time will tell. Best wishes, John
-
Hi gw1500se, i don't know how to define the scholarly subtraction but it certainly isn't invalid. Some mathematicians (which noone has ever heard of) suddenly hold themselves higher than, say Carl von Linne, and deem MDVC as an invalid numeral. However, some of the world's smartest people have published books with these 'invalid' numerals. I want to convert these numerals that you may see in old books and not show a message that it is invalid. I have only seen numbers I-5 used in irregular subtraction dates: mdvc, mdic etc. I've not seen MDVIIC or MDVIXC. I want to limit irregular subtractions to five while ignoring any other subtractions until later in the code. I like the limit and i want the limit. I have the limit. Filter number 2 handles these lower numbers used in irregular subtractions: //2. subtraction less than 5 should be valid in this converter $validSubtraction = array('IV', 'III', 'II', 'I', 'V'); foreach ($validSubtraction as $m) { foreach ($FollowedBy as $n) { $pos = stripos($RomanNumeralInput, $m . $n); if ($pos !== false) { // if ($m === $n) { $invalid = 1; $invalidRule = 20; break(2); } if ($pos > 0 && $RomanNumeralInput[$pos-1] === 'I') { $invalid = 1; $invalidRule = 21; break(2); } if ($pos > 0 && $RomanDecimal[$RomanNumeralInput[$pos-1]] < $RomanDecimal[$n]) { $invalid = 1; $invalidRule = 22; break(2); } $subtraction = 1; $subtractionCount = strlen($m . $n); $subtractionIsolated = $m . $n; $calculateSubtraction = $RomanDecimal[$n] - $RomanDecimal[$m]; if ($pos + $subtractionCount < strlen($RomanNumeralInput)) { if ($calculateSubtraction > $RomanDecimal[$RomanNumeralInput[$pos + $subtractionCount]]) { $invalid = 1; $invalidRule = 23; break(2); } } $RomanNumeralInput = str_replace($m.$n, '', $RomanNumeralInput); break(2); } } } if ($invalid) { echo ' is a nonstandard Roman Numeral (Rule number: ' . $invalidRule . ')'; exit; } This code works. Later, i handle all other subtractions like everyone else. loop through the array holding the submitted numeral. Then simply use an if statement. If current numeral less than next numeral, then subtractive. I have tried my code on numbers 1-100, 200, 300, 400, 500, 1000, 3999, MDVC etc. I have no problems yet. MDCM is handled normally in my code. I will finish the code tomorrow, then loop through 1-3999 and see how it goes. Then i will try various irregular combinations and see how the code holds up. I'll post reults. Maybe someone can help clean up and tighten my code. Best wishes, John