Reputation: 1
Suppose, I have a variable $var1 which contains the followings:
$var1="../sidebar_items/uploaded_files/notices/circular.pdf";
Now, I want to create another variable $var2 which will hold the following value:
$var2="../dev/sidebar_items/uploaded_files/notices/circular.pdf";
I want to create $var2 with the help of $var1 via string manipulation. Is it possible to do so? How will I achieve that?
Upvotes: 0
Views: 48
Reputation: 57131
I'd approach it by separating out the file name using basename()
and then having a variable which has the path to the dev directory. This allows you to change it to all sorts rather than limiting it to a minor change...
$var1="../sidebar_items/uploaded_files/notices/circular.pdf";
$devpath = "../dev/sidebar_items/uploaded_files/notices/";
echo $devpath.basename($var1);
gives...
../dev/sidebar_items/uploaded_files/notices/circular.pdf
Upvotes: 0
Reputation: 258
you could also use strtr() function of PHP
$var2 = strtr($var1, '../', '../dev/');
Upvotes: 0
Reputation: 4859
It looks like you're allowing users to upload files and saving the filenames. That's potentially very dangerous depending on how you're dealing with them; if you are taking their string value and doing file system operations against it, you could end up with a user uploading a file with a name like ../../../../../usr/bin/php
and risking allowing a delete operation against that file (if your permissions are set up really, really poorly) or, perhaps more realistically, using path manipulation to delete, modify, or overwrite any file owned by the web server user. index.php
would be an obvious target.
You should consider keeping both paths in separate constants rather than using string manipulation to turn one into the other at runtime. You should also consider renaming user-uploaded files, or at least being very careful about how you store them with regard to naming based on how you access them in your code.
Upvotes: 0
Reputation: 13635
Just use str_replace(). It returns the changed string but doesn't change the original variable so you can store the result in a new variable:
$var2 = str_replace('../', '../dev/', $var1);
Upvotes: 1