Jnitrofish Posted July 8, 2006 Share Posted July 8, 2006 This is pretty simple I'm guessing, its normally the simple ones that confuse me. :PI am trying to get code that will add something to to the end of a line (like a forward slash) if it does not find that something there already.In my case what I am doing is having a user submit form data to a PHP script. There are 2 important fields in this form; 1. a URL/directory field, 2. a file field. Now in the script there are a few cases where the 2 field's post data is being used together and I found that if the user forgets to add a forward slash to the end of the directory name (or to the beginning of the file name, and they are not suppost to do that anyway) that my fwrite() edits the wrong file/creates a new one.[code]$URL = $_POST['URL'];$FileName = $_POST['FileName'];$Content = "Blah";if (is_dir($URL)) {fwrite(fopen($URL.$FileName, "a"), $Content);fclose(fopen($URL.$FileName, "a"));chmod($URL.$FileName, 0755);} else {mkdir($URL, 0755);fwrite(fopen($URL.$FileName, "a"), $Content);fclose(fopen($URL.$FileName, "a"));chmod($URL.$FileName, 0755);}[/code]What happens with out a slash included on the end of the post data from the field 'URL'? mkdir ends up creating a new directory named "/testdir" and then fwrite creates a new file named "/testdirtestfile.php" and not a file in the directory "/testdir" named "testfile.php".So, I cant figure out how to make sure that the user added a slash to the end of the name they put in the URL field, and at least echo up a error if they forgot the slash, if not add the slash for them.If I could get some opinions on this, that would be great.Thanks as always,-Jnitro Quote Link to comment https://forums.phpfreaks.com/topic/13998-adding-something-to-the-end-of-a-line-if-it-is-not-there-to-begin-with/ Share on other sites More sharing options...
Kurt Posted July 8, 2006 Share Posted July 8, 2006 Im not good with regular expressions (thats one method of doing this) but you could tr this:[code]if(!strstr($string,'/')){die('Please enter a /');}[/code]That's not that secure for various reasons so I suggest using regular expressions. Quote Link to comment https://forums.phpfreaks.com/topic/13998-adding-something-to-the-end-of-a-line-if-it-is-not-there-to-begin-with/#findComment-54664 Share on other sites More sharing options...
Barand Posted July 8, 2006 Share Posted July 8, 2006 [code]<?php$string = 'abc/def';if(substr($string,-1)!='/'){ $string .= '/';}echo $string;?>[/code] Quote Link to comment https://forums.phpfreaks.com/topic/13998-adding-something-to-the-end-of-a-line-if-it-is-not-there-to-begin-with/#findComment-54720 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.