Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 11 of 11
  1. #1
    New Coder
    Join Date
    Mar 2012
    Posts
    91
    Thanks
    2
    Thanked 0 Times in 0 Posts

    strip characters from a php write text file

    Hi All,

    I seem to have lost the plot here. The code below came out of a different post where I was asking about remote password protection for the code, that is all fine and below is just an example to show a code for the question.

    The code writes whatever is sent from a form to a text file. In different cases I want to strip all characters except numbers and sometimes strip only specific characters.

    Do I need to use a RegExp or a Replace and where should it be positioned in the code below.


    Code:
    <?php
    # initialise variables
    $Something = "";
    $data = array();
    $changed = false;
    $myTextFile = "somefilenamehere.txt";
    if (file_exists($myTextFile))
    $data = parse_ini_file($myTextFile, true);
    if (isset($_POST['userdata']) && $_POST['password'] == "xxxxx")
    {
    $data[$_POST['']]['Something'] = $_POST['Something'];
    $changed = true;
    }
    if ($changed) {
    $fp = fopen($myTextFile, 'w');
    ksort($data);
    foreach ($data as $key=>$dataArray){foreach ($dataArray as $k => $v){fwrite($fp, "$v");}}
    fclose($fp);
    header("Location: done.php");
    Exit();
    }
    ?>


    Martin.
    Last edited by SpidersWebHelp; 08-04-2013 at 09:30 AM.

  • #2
    God Emperor Fou-Lu's Avatar
    Join Date
    Sep 2002
    Location
    Saskatoon, Saskatchewan
    Posts
    16,987
    Thanks
    4
    Thanked 2,660 Times in 2,629 Posts
    If you have any type of change that is dynamic or variable, than the use of pcre is probably warranted. That way you can swap at runtime to do what it needs to do.
    PHP Code:
    header('HTTP/1.1 420 Enhance Your Calm'); 

  • #3
    New Coder
    Join Date
    Mar 2012
    Posts
    91
    Thanks
    2
    Thanked 0 Times in 0 Posts
    Hi,

    Suggestion is fine, but example is better.

    I am asking because I simply cannot grasp how to apply a strip or in the case of code below say match the numbers 0 to 9 to allow the file to be written.


    Code:
    <?php
    
    number = /^[0-9]+$/; 
    
    define("isokay", match(number));
    
    # initialise variables
    $Total = "";
    $data = array();
    $changed = false;
    $myTextFile = "fileshowingnumber.txt";
    if (file_exists($myTextFile))
    $data = parse_ini_file($myTextFile, true);
    if (isset($_POST['userdata']) && $_POST['pass1'] == "xxxx")
    {
    if ($_POST['Total'] == isokay)
    {
    $data[$_POST['']]['Total'] = $_POST['Total'];
    $changed = true;
    }
    }
    if ($changed) {
    $fp = fopen($myTextFile, 'w');
    ksort($data);
    foreach ($data as $key=>$dataArray){foreach ($dataArray as $k => $v){fwrite($fp, "$v");}}
    fclose($fp);
    header("Location: done.php");
    Exit();
    }
    ?>


    Martin.
    Last edited by SpidersWebHelp; 08-05-2013 at 12:09 PM.

  • #4
    God Emperor Fou-Lu's Avatar
    Join Date
    Sep 2002
    Location
    Saskatoon, Saskatchewan
    Posts
    16,987
    Thanks
    4
    Thanked 2,660 Times in 2,629 Posts
    Are you stripping, or are you matching? They're completely different things.
    If you are matching, that is saying "does this string match this pattern?" and the pcre will tell you yes or no. If you're stripping, it will say "take this string, and return it to me with only this pattern in it". So you have to decide what it is you're planning to do first.
    I don't know if you are matching before or after, so I'll just say before. That would be here in this foreach:
    PHP Code:
    foreach ($data as $key=>$dataArray)
    {
        foreach (
    $dataArray as $k => $v)
        {
            if (
    preg_match('/^[0-9]+$'$v)) // value check I guess?
            
    {
                
    fwrite($fp"$v");
            }
        }

    PHP Code:
    header('HTTP/1.1 420 Enhance Your Calm'); 

  • #5
    New Coder
    Join Date
    Mar 2012
    Posts
    91
    Thanks
    2
    Thanked 0 Times in 0 Posts
    Hi,

    I am big enough to be called any level of stupid you wish, because I must be.

    I asked about strip or match as I am happy to try and adapt anything that works in the first place.

    Previous to my post I had tried the preg_match and other ideas posted on the net in all sorts of locations in the code to see if I could make it work, nothing ever did.


    I have placed the change suggested into the original code to replace the indicated part. Assuming I did that correctly it fails to work in so much as it will not write the input fields number quantity to the final somefilenamehere.txt text file.

    The example code 1. below will write the number entered in the forms input field 'Something' to the text file somefilenamehere.txt.

    The revised code 2. will not write anything entered into the forms input field. However, if the final somefilenamehere.txt actually had content previously, it does vanish giving the suggestion the revised code makes a completely new file but fails to enter the sent value from the form.

    I am lost, any suggestions welcome.


    1. Original code writes to the text file.
    Code:
    <?php
    # initialise variables
    $Something = "";
    $data = array();
    $changed = false;
    $myTextFile = "somefilenamehere.txt";
    if (file_exists($myTextFile))
    $data = parse_ini_file($myTextFile, true);
    if (isset($_POST['userdata']) && $_POST['password'] == "xxxxx")
    {
    $data[$_POST['']]['Something'] = $_POST['Something'];
    $changed = true;
    }
    if ($changed) {
    $fp = fopen($myTextFile, 'w');
    ksort($data);
    foreach ($data as $key=>$dataArray){foreach ($dataArray as $k => $v){fwrite($fp, "$v");}}
    fclose($fp);
    header("Location: done.php");
    Exit();
    }
    ?>


    2. This is the revised version, if I did it correctly.
    Code:
    <?php
    # initialise variables
    $Something = "";
    $data = array();
    $changed = false;
    $myTextFile = "somefilenamehere.txt";
    if (file_exists($myTextFile))
    $data = parse_ini_file($myTextFile, true);
    if (isset($_POST['userdata']) && $_POST['password'] == "xxxxx")
    {
    $data[$_POST['']]['Something'] = $_POST['Something'];
    $changed = true;
    }
    if ($changed) {
    $fp = fopen($myTextFile, 'w');
    ksort($data);
    
    // replaced all this......... foreach ($data as $key=>$dataArray){foreach ($dataArray as $k => $v){fwrite($fp, "$v");}}
    
    foreach ($data as $key=>$dataArray)
    {
        foreach ($dataArray as $k => $v)
        {
            if (preg_match('/^[0-9]+$', $v)) // value check I guess?
            {
                fwrite($fp, "$v");
            }
        }
    } 
    
    fclose($fp);
    header("Location: done.php");
    Exit();
    }
    ?>

    Martin.

  • #6
    New Coder
    Join Date
    Mar 2012
    Posts
    91
    Thanks
    2
    Thanked 0 Times in 0 Posts
    Hi again,

    I may want to retract at least one level of stupid because I think I have realised what may be wrong.

    The replacement code part.... preg_match('/^[0-9]+$', $v))
    is missing a forward slash after the +$


    Martin.

  • #7
    New Coder
    Join Date
    Mar 2012
    Posts
    91
    Thanks
    2
    Thanked 0 Times in 0 Posts
    Hi Fou-Lu,

    Keeping with the same example code you helped with which used the if statement for a match to control the write to text file action, can you tell me how you would do a replace action should I want to stop a script being written by replacing slashes, tag chevrons < > or a word like script, with a blank space.

    Can I for instance use the replace below.
    $data = preg_replace('/^[\/< >]+$/', '', $data);
    and introduce into the example code where shown to kill off a script or replace anything I happened to want to replace before the text file was written.

    Code:
    <?php
    # initialise variables
    $Something = "";
    $data = array();
    $changed = false;
    $myTextFile = "somefilenamehere.txt";
    if (file_exists($myTextFile))
    $data = parse_ini_file($myTextFile, true);
    if (isset($_POST['userdata']) && $_POST['password'] == "xxxxx")
    {
    $data[$_POST['']]['Something'] = $_POST['Something'];
    
    
    // can I add a replace here for instance
    $data = preg_replace('/^[\/< >]+$/', '', $data);
    
    
    $changed = true;
    }
    if ($changed) {
    $fp = fopen($myTextFile, 'w');
    ksort($data);
    
    foreach ($data as $key=>$dataArray)
    {
        foreach ($dataArray as $k => $v)
        {
            if (preg_match('/^[0-9]+$/', $v)) // value check I guess?
            {
                fwrite($fp, "$v");
            }
        }
    } 
    
    fclose($fp);
    header("Location: done.php");
    Exit();
    }
    ?>

    Martin.
    Last edited by SpidersWebHelp; 08-20-2013 at 12:38 AM.

  • #8
    New Coder
    Join Date
    Mar 2012
    Posts
    91
    Thanks
    2
    Thanked 0 Times in 0 Posts
    Hi again,

    Following on from my previous question I have tried various methods to strip the tags from any script code if it were entered into a form so that no active code could be executed. Below is one way I tried $v = trim(strip_tags($v)); and it seems to work, however is it correct to do it that way before the file is written.

    The example shown is a form with say four input fields called 'Something', I am assuming the strip would apply to each as it is processed before writing to the text file.

    Code:
    <?php
    # initialise variables
    $Something1 = "";
    $Something2 = "";
    $Something3 = "";
    $Something4 = "";
    $data = array();
    $changed = false;
    $myTextFile = "somefilenamehere.txt";
    if (file_exists($myTextFile))
    $data = parse_ini_file($myTextFile, true);
    if (isset($_POST['userdata']) && $_POST['password'] == "xxxxx")
    {
    $data[$_POST['']]['Something1'] = $_POST['Something1'];
    $data[$_POST['']]['Something2'] = $_POST['Something2'];
    $data[$_POST['']]['Something3'] = $_POST['Something3'];
    $data[$_POST['']]['Something4'] = $_POST['Something4'];
    $changed = true;
    }
    if ($changed) {
    $fp = fopen($myTextFile, 'a');
    ksort($data);
    foreach ($data as $key=>$dataArray){foreach ($dataArray as $k => $v){
    
    
    // I added this to strip tags from any code
    $v = trim(strip_tags($v)); 
    
    
    fwrite($fp, "$v");}}
    fclose($fp);
    header("Location: done.php");
    Exit();
    }
    ?>


    Martin.
    Last edited by SpidersWebHelp; 08-20-2013 at 12:19 PM.

  • #9
    God Emperor Fou-Lu's Avatar
    Join Date
    Sep 2002
    Location
    Saskatoon, Saskatchewan
    Posts
    16,987
    Thanks
    4
    Thanked 2,660 Times in 2,629 Posts
    strip_tag's purpose is to remove the html, except for whatever you specify to retain. If you are intending to remove just the HTML, than yes that would be fine. I cannot tell you if its preferable to remove it before or after, as that would be defined by the purpose of the data. If I were writing templates, than I would not do anything to remove the tags. If I were handling a user provided post, I would convert the characters using htmlspecialchars or htmlentities since there would never be a reason to retain it in its original parsable form. So if you intend to never store them within the file, than removing prior to insertion makes sense.

    I would probably write a function for it instead so I could easily add and remove behaviour as well as choose to use in a array_walk_recursive if I wanted to do that instead.

    I'm trying to figure out why you are using $_POST[''] in here. '' is never a valid post name, but it is a valid associative name (its also valid within $_POST, but w3 specifies that a name cannot be empty, so it can only end up there if manually associated as the browser would consider it to be non-successful).
    PHP Code:
    header('HTTP/1.1 420 Enhance Your Calm'); 

  • #10
    New Coder
    Join Date
    Mar 2012
    Posts
    91
    Thanks
    2
    Thanked 0 Times in 0 Posts
    Hi Fou-Lu,

    Thanks for the comments.

    What I am doing is taking information from a form which is actually e-mailed somewhere and saving whatever was entered into the input fields to a .txt file on host so it can be read if necessary to see what was really entered into the input fields of the form.

    As a text file of course I realise the content would show a text and not active script codes, but I just wanted to make sure there is absolutely no way that the seen text in the file could ever be rendered by whatever method to become active code. There is no problem seeing what function may have been added and if all shown it could be reconstructed to see what someone was up to.

    My thought was to kill off any way actual code could even be written to the file to start with and hence the trim of tags. I also have a $v = preg_replace("/\(/", "", $v); which can be used to indicate a character or symbol I want to knock out, which for the example could kill an alert by removing the bracket.


    On your question.... I'm trying to figure out why you are using $_POST[''] in here.......
    I never wrote the original code which makes up part of my example just chopped up different ones and joined up to get the result I wanted based on various examples of php forms on web pages shown on help pages around the net. The $_POST[''] was in one such code which did something from a form, I cannot even remember if the '' actually had something in there and I removed it or it was already written as seen. However, the overall code always worked fine to do what I wanted and my belief is if it works don't touch it, so I never tried to remove until you mentioned it.

    Below is the code revised to remove the $_POST[''], is that how you meant I should revise the code to not have the.... $_POST[''].

    Code:
    <?php
    # initialise variables
    $Something1 = "";
    $Something2 = "";
    $Something3 = "";
    $Something4 = "";
    $data = array();
    $changed = false;
    $myTextFile = "somefilenamehere.txt";
    if (file_exists($myTextFile))
    $data = parse_ini_file($myTextFile, true);
    if (isset($_POST['userdata']) && $_POST['password'] == "xxxxx")
    {
    $data[]['Something1'] = $_POST['Something1'];
    $data[]['Something2'] = $_POST['Something2'];
    $data[]['Something3'] = $_POST['Something3'];
    $data[]['Something4'] = $_POST['Something4'];
    $changed = true;
    }
    if ($changed) {
    $fp = fopen($myTextFile, 'a');
    ksort($data);
    foreach ($data as $key=>$dataArray){foreach ($dataArray as $k => $v){
    
    
    // I added this to strip tags from any code before text file is written
    $v = trim(strip_tags($v)); 
    
    // used to chop out any character or symbol before text file is written
    $v = preg_replace("/\(/", "", $v); 
    $v = preg_replace("/\)/", "", $v);
    
    
    fwrite($fp, "$v");}}
    fclose($fp);
    header("Location: done.php");
    Exit();
    }
    ?>

    Martin.

  • #11
    God Emperor Fou-Lu's Avatar
    Join Date
    Sep 2002
    Location
    Saskatoon, Saskatchewan
    Posts
    16,987
    Thanks
    4
    Thanked 2,660 Times in 2,629 Posts
    A file extension does not control what a file is, nor how it is run especially in linux. If you accept text and run it through directly and that text includes a shebang line, it is technically possible to execute the type given if the webserver is set up to do so.
    If access through a webserver is a problem, than simply place the file in a location above the httpd directory root.
    Simple characters do not need the use of preg_replace, use str_replace for those instead. PCRE is used for complex patterns, such as removing () from around text, but only if the text is at least 5 chars in length and contains only characters for example.

    $_POST[''] and [] won't result in the same thing. It's close but not the same. The error of the $_POST[''] will be that there is no valid offset for '' within the post. It will then retrieve the nothing and assign it to the variable. The associative context will be that of the string, so you'd end up with a single item when you use the string since its valid in the $data array. [] on the other hand is numerical, so you'd have 4 items within the array.
    The iteration gets around that though. Instead of iterating once four times, you will iterate four times once. Since the initial item's key has no value in the code, it does not matter that you have changed the structure.
    PHP Code:
    header('HTTP/1.1 420 Enhance Your Calm'); 


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •