addslashes

addslashes

by Gustav W Delius -
Number of replies: 2

I have noticed that I am not the only Moodle developer who gets confused by the addslashes/stripslashes issue. Even though this is not really a Moodle issue, let me summarize my understanding of the addslashes issue so that people can correct me:

1) any data that I want to write to a database must have single quotes ' , double quotes " and backslashes \ escaped with a backslash \. So for example O'Connor should be converted to O\'Connor before it is written to the database. This can be achieved with addslashes.

2) when the data is pulled from the database it comes out without the slashes. So it can't be written straight back. For example the function get_record produces an object that can not be immediately written back with update_record.

3) any data that is passed to a script via GET or POST already has slashes added. Thus such data should have these slashes removed before printing to the screen. The functions p() and s() do this automatically.

In view of point 2) above it would be convenient to have a function that adds slashes to all strings in an object. Does someone already have such a function?

Average of ratings: -
In reply to Gustav W Delius

Re: addslashes

by Martin Dougiamas -
Picture of Core developers Picture of Documentation writers Picture of Moodle HQ Picture of Particularly helpful Moodlers Picture of Plugin developers Picture of Testers
You got it. Basically, you don't need to worry about slashes most of the time, because it's data from the browser. You only need to addslashes() to raw data (from the database or files) - I can only think of a handful of places where I needed to do that. And yes, always use p() and s() when outputting data to the browser.

To convert all the strings in an object just treat it like an array:
foreach ($object as $key => $string) {
$object->$key = addslashes($string);
}
Man I love PHP.
In reply to Martin Dougiamas

Don't strip slashes too often

by Gustav W Delius -

Some places in Moodle strip slashes once too often. This happens when the p() or s() functions are used to output data that did not actually have slashes added. Examples are the mod.html files that provide the forms for adding and editing activity modules. This is the reason why it is not possible to get \' or \" or \\ in activity names or descriptions. They become ', " and \.