Jump to content

Adding something to the end of a line if it is not there to begin with.


Jnitrofish

Recommended Posts

This is pretty simple I'm guessing, its normally the simple ones that confuse me.  :P

I 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
Link to comment
Share on other sites

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.
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.