How Can I Prevent Apostrophes From Being Backslashed Out - PHP

They have: 5 posts

Joined: May 2009

I'm having a problem with a script I've found, chopped and adapted to doing as I need it to do. The script adds form submitted data into a text file but whenever text containing an apostrophe is submitted the apostrophe's backslashed out when it's added to my text file. How do I stop inputted data from being re-formatted to php standard?

The code, including form, is:

<?php

if(isset($_POST['SubmitTwo'])){

   
$adcode = $_POST['adcode'];
  
$errs = '';
  
   if(empty(
$adcode)){
     
$err .= '-Please enter your ad\'s code<br />';
   }

   if(
$errs!=''){
      echo
'<b style=\'color: red;\'>Ad Submission Failed</b><br />' . $errs;
   }
   else{
     
$file = 'ads.txt';
     
$code = $adcode . "\n";

     
// First check, let's make sure ads.txt exists and is writable.
     
if (is_writable($file)) {
     
        
// We're opening $file in append mode.
         // The file pointer is at the bottom of the file hence
         // that's where $code will go when we fwrite() it.
        
if (!$handles = fopen($file, 'a')) {
             echo
"Cannot open file ($file)";
             exit;
         }
     
        
// Write $code to our opened file.
        
if (fwrite($handles, $code) === FALSE) {
            echo
"Cannot write to file ($file)";
            exit;
         }
        
         echo
'<b style=\'color: green;\'>Submission successful</b><br /><br />It looks like this:<br /><br />' . $adcode . '<br /><br />It will now show in the footer on rotation.';
        
        
fclose($handles);

      }else {
         echo
'<b style=\'color: red;\'>Failure -' . $file . ' is not writable</b>' ;
      }
   }
}
?>


<div id="wrapper">

<br />
<br />

<div class="left">

<h3>Submit your link's html code</h3>
<br />

<form  action=""  method="post" name="addcodeform">

<table class="positionleft">

<tr>
<td>

   <label>Please enter the code here</label>
</td>
</tr>
<tr>
<td>
   <textarea cols="30" rows="8" name="adcode" class="text" id="adcode" onmouseover="ddrivetip('Enter the full code here', 200)" onmouseout='hideddrivetip()'  onblur="validate(this,'RequiredAlphabetic')" ></textarea>
</td>
</tr>

<tr>
<td>
<br />
<div class="submitbutton">
  <input type="submit" name="SubmitTwo" class="btn" value="Submit" />  <input type="reset" class="btn" value="Clear" />
</div>
</td>
</tr>
</table>

</form>

</div>

</div>

The code adds data entered into the form (for my case, a fully formatted html link) to a file named ads.txt which is then read by another script (not reproduced here) which randomly displays a series of links in my website's footer.

As a working alternative, I've adapted the script so that I can add the href and anchor text separately and have the html tags added by the script but I'd like to be able to just post fully formatted links without worrying about the link being altered and made unworkable.

The script itself isn't fully my own work; I'm 2-3 days new to php and I'm learning by finding, inspecting, chopping and adapting scripts as I go along (I've read a lot over the last few days!). Any ideas how I can stop the backslashes from being added?

Edited to replace all instances of "coma" with "apostrophe" - changed title and body text. Thank you Greg for pointing out my mistake.

greg's picture

He has: 1,581 posts

Joined: Nov 2005

I presume by "comas" you mean "apostrophes" '

You need to know why it's doing this to decide the best method to stop it, as well as where in your code to do it.

Does your server have magic_quotes_gpc turned on? It's NOT common for it to be ON these days, but worth checking...

<?php
// Returns the current configuration setting of magic_quotes_gpc
//Returns 0 if magic quotes gpc are OFF, 1 if ON
echo get_magic_quotes_gpc();
?>

If yes, the you could try the stripslashes() function.
EG

<?php
$code
= stripslashes($adcode)."\n";
?>

But you may need to do that when you output it rather than input/save.

Really though, you should have magic_quotes_gpc off. It's simply a nuisance these days and you shouldn't rely on it in code as it's off in recent PHP versions by default (depreciated in PHP 6, so wont even function), so most servers wont provide for it.

As for the links, there are various ways to handle this.
Either require a full input entirely to input/save, so you just output <a href="'.$link.'">"'.$lnk_text.'"</a>, or just input/save just the domain and tld so you output the rest in the HTML, <a href="http://www.'.$link.'">"'.$lnk_text.'"</a>

Either way requires some form of checking the string with PHP. Does it have "http://" does it have "www." etc. What you do and don't allow depends on how and where you construct the link.

On a slight side note. Why do you set $adcode to $_POST['adcode'], then set $code to $adcode?
You can just use the $_POST['adcode'] for the error checking as in this instance you do very little with it. I only tend to assign it to a var if I'm doing lots of checking with it and prefer a smaller var throughout the code.
Each to their own methods of course Wink

They have: 5 posts

Joined: May 2009

Thank you Greg, I did mean apostrophes and not comas (I knew at the time of writing I'd used the wrong word but didn't fully twig-on). I've checked with my host and magic_quotes_gpc is supposed to be turned off but I'm not sure it is so I'm dealing with that one now.

I'm new to php so most of what you wrote went straight over my head but working it out will keep me busy for the rest of today.

I've thought of using str_replace to remove the offending alterations. I'll wait until I know that magic_quotes_gpc is definitely off before I alter the script.

On a slight side note. Why do you set $adcode to $_POST['adcode'], then set $code to $adcode?

I adapted the script from another one. When adapting it, I thought about doing as you suggest but changed my mind; I'll change it today.

greg's picture

He has: 1,581 posts

Joined: Nov 2005

Midas wrote:
I've thought of using str_replace to remove the offending alterations.
As I said, you need to find out why the slashes are being escaped first to know what solution to use.

And always use the right tool for the job. With PHP, that can mean using a function or method that takes a lot more server resource.
At a guess, str_replace() probably uses more resource than stripslashes(), although I'm not sure about that without research or benchmarking..

Put the following in a file (preferably an empty test one and away from public)

<?php
echo get_magic_quotes_gpc();
?>

And tell us if it outputs a 0 or 1.

They have: 5 posts

Joined: May 2009

Greg, we've sussed it - magic_quotes_gpc wasn't turned off. I've added a line to my php.ini file to turn it off and the script now works as it should.

Your advice has been very helpful, thank you.

greg's picture

He has: 1,581 posts

Joined: Nov 2005

np Smiling

It would be better if it was turned off at server level, but as long as you're sorted that's the main thing.

They have: 5 posts

Joined: May 2009

According to my host, it's supposed to be turned off at server level. I'm aware they had a few problems with some servers when they switched magic_quotes off by default a few months ago (it didn't switch off for all of them) but they have said (in a forum thread I read today) they'll switch it off when notified that it's still "on" for a server (I tried to rephrase that several ways and it always came out a mouthful). I'll see what happens over the next few days.

Want to join the discussion? Create an account or log in if you already have one. Joining is fast, free and painless! We’ll even whisk you back here when you’ve finished.