Jump to content

Archived

This topic is now archived and is closed to further replies.

Jnitrofish

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

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

Share this post


Link to post
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.

Share this post


Link to post
Share on other sites
[code]<?php
$string = 'abc/def';
if(substr($string,-1)!='/'){
$string .= '/';
}
echo $string;
?>[/code]

Share this post


Link to post
Share on other sites

×

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.