PHP pass a string containing quotations via GET - php

I am trying to pass a string that already contains quotation marks from one php file to another via a hyperlink and the GET method.
I am retrieving thousands of lines which contain quotation marks in a while loop and saving the output to a variable as follows:
while ($trouble_row = mysql_fetch_array($trouble_result)) {
$ticketid = $trouble_row['ticketid'];
$ticketno = $trouble_row['ticket_no'];
$created = $trouble_row['createdtime'];
$modified = $trouble_row['modifiedtime'];
$title = $trouble_row['title'];
$solution = $trouble_row['solution'];
$hoursattended = $trouble_row['cf_629'];
$hoursbilled = $trouble_row['cf_628'];
$csv .= "$firstname $lastname,$ticketno,$created,$modified,$hoursattended,$hoursbilled,$title,$solution\n";
}
The variable $title sometimes contains an entry that looks like this:
The user "tom" is having problems.
The variable $csv is collecting all the results from each pass and creating a CSV formatted string that I then need to pass to a new php script, which I am trying to do using a hyperlink:
a href="export_csv.php?csv=$csv">Export to CSV</a>
Unfortunately the embedded quotation marks are recognized by the hyperlink and cut off the majority of the output. Any suggestions on how to collect the data differently, store it differently, or pass it differently would be greatly appreciated!

For parameters in links, you need to use urlencode():
echo 'Export to CSV';
note however that GET requests have length limits starting in the 1-2k area (depending on browser and server).
Alternative approaches:
Forms
One method that is immune to length limits is creating a <form> element for each link with method="post" and adding the values in <input type='hidden'> inputs. You would then style the submit button of the form like a link.
<form action="export_csv.php" method="post">
<input type="hidden" name="csv" value=".......">
<button type="submit">Click here </button> <!-- Use CSS to style -->
</form>
Sessions
Another very elegant way to pass the data would be
Generating a random key
Saving the CSV data in a $_SESSION variable with the random key
Passing the random (short) key in the URL instead of the full data
You'd just have to take care of deleting unused random keys (and their data) frequently.
These kinds of links couldn't be bookmarked, of course.

Use urlencode() before creating the hyperlink url, and use urldecode() to get the original string.

use urlencode() for embedding into a link, and html_special_chars() for embedding into form fields.

url_encode and url_decode.

Quickest and easiest solution given what you already have is probably to change this:
Export to CSV
To something like this:
Export to CSV

Related

post multiple links inside textbox to another page and insert into mysql separately

I have a html form in php file in which there is a textbox in which a user can post multiple links . suppose
www.4shared.com/video/UryixZ7l/Puppy_loves_ringtones.htm
www.4shared.com/video/UryixZ7l/Puppy_loves_ringtones.htm
www.4shared.com/video/UryixZ7l/Puppy_loves_ringtones.htm
www.4shared.com/video/UryixZ7l/Puppy_loves_ringtones.htm
There are four links here . If i submit the form and the data is send to target page then it counts the whole textbox suppose named "links" as a string and send all of its data into database which it should . But i wanted to send these links and the data along with them such as uid , name to be submitted 4 times into database ie as many times as many links are there instead on 1 entry with all four links and the name and id in one row . How can i make this possible ?
I edited this entire post after I got more information by the author
Assuming you are using a textarea where the user can enter his information you could process that in PHP:
<form action="mytarget.php" method="post">
<textarea name="urls"></textarea>
</form>
Assuming the user should enter one URL per line, on PHP:
$data = explode("\n", $_POST['urls']);
if(count($data) > 0) {
foreach($data as $url) {
echo $url . "<br />";
}
}
Maybe this are the droids you are looking for. :P
Sorry I've been trying to figure how a technique with just the textarea:
This does use jQuery, I'm not sure if that is something you want to do or not. You can easily convert it to javascript if you like.
<script>
$(document).ready(function() {
$('textarea').on('focusout', function() {
var text = $('textarea').val();
var delimiter = ",";
$('textarea').val(text + delimiter);
});
});
</script>
What that does is appends a comma to the end of each url when the user focuses out of the textarea (pick whichever event you want, i don't expect you to use focusout), so that when your form is submitted, you can then explode the textareas text and get the urls and store them in separate variables.
The regular expression will expect the url to always end in .htm, so if you are wanting other url endings then add to the regex.
This will add a delimiter after every focusout event, even if its just plain text (i.e. not a valid url). But you can check against this once you've exploded (the text I mean :D), and it can be a good way to sanitize your data to make sure you're getting valid urls.
Hope this helps in some way
PS, the delimiter can be anything, i.e. a new line would be best \n, just remember to use the same delimiter in explode() i.e. explode("\n", $_POST[urls]);

how to chop up returned string from file_get_contents() into variable

i have a wordpress plugin that sends a request using file_get_contents() to a url and in-turn receive an image and four variables which ofcoz are already processed so they are just four words. How to i break down this string (using php) so i can take turn the four words into variable again as soon as they are returned, and use them on that page, (page C. )
here is a diagram of what i want to do
http://itmastersworld.com/my_problem.jpg
I have tried placing a form to be part of the string returned but apparently there is no way of manupilating the data inside the form
<form><input id="test" name="avariable" type="hidden" value="<?php echo $xxxx; ?>" /></form>
it works but i cant find a way to use the value="" without submiting the form from the server(using stuff like
$yes = $_REQUEST['avariable']
,) the form is introduced in part B that is, and appears in part c.
Help ???? I basically need my php variable created in part B.!!
Since you already have control on the page B, you can send them with some delimiter and split them? For example lets say the output is
word1,,,word2,,,word3,,,word4
Your code can be
<?php
$vars = explode(",,,", file_get_contents('your_url');
// echo $vars[1];
// echo $vars[2];
// echo $vars[3];
// echo $vars[4];
?>

HTML checkbox form and HTTP URL

So, I have this HTML form:
<form id="search_form" class="form_wrapp"
accept-charset="utf-8" method="get" action="http://testing.com/results">
<input class="inputbox" type="text" name="search_query">
<input class="ic_search" type="submit" value="">
<input type="checkbox" value="checkbox1" name="search_filter[]">
<label for="Checkbox1">Checkbox1</label>
<input type="checkbox" value="checkbox2" name="search_filter[]">
<label for="Checkbox2">Checkbox2</label>
</form>
and it redirects to this URL upon submit with the 2 checkboxes checked
results?search_query=dreams&search_filter[]=checkbox1&search_filter[]=checkbox2
It works like this (inside codeigniter I get the data with $this->input->get('search_filter')), but my question is: I am doing something wrong inside the form, or this is how it's supposed to work?
And I mean about: &search_filter[]=checkbox1&search_filter[]=checkbox2. Shouldn't it be something like: &search_filter[]=checkbox1,checkbox2 ? And if not, how can I make it work like that?
If you want it in the comma format you can do the following:
$filters = (array) $this->input->get('search_filter');
$filters = implode(',',$filters);
If you want to alter the format in which the form is submitted, assuming jquery for js:
$('#search_form').submit(function() {
var $hidden = $('<input type="hidden" name="search_filter" />').appendTo($(this)),
$filters = $('input[name^=search_filter]'),
value = '';
//loop through the filters check if there checked and add them to the value
$hidden.val(value);
$filters.remove();
});
Of course if the user doesn't have js enabled it will submit natively
Am I doing something wrong inside the form, or this is how it's supposed to work?
That's how it's supposed to work. At least if you need to read query string with PHP, those brackets need to be there to read the whole query string without each search_filter value being overwritten by the next one.
And if not, how can I make it work like that?
If you have to, you can use a POST request instead, process the submission, and redirect to the URL of your choice with whatever query string you want.
From your comment:
I wanted to make the url like this &search_filter[]=checkbox1,checkbox2 just to make it a bit more "beautiful"
Don't worry about that, seriously. The only time this matters is when you're doing extreme SEO and you don't want two URLs that point to the same place. It's common practice in those cases to remove all unused keys and alphabetize them so that all URLs with query strings are consistent, but mangling them into something custom still isn't a part of that.
Besides that, don't fight against the behavior - work with it - it's not "broken" and making it "beautiful" won't matter to anyone, plus you'll have to guess/remember which pages process query strings the correct way, and which ones use your "custom" method.
I am doing something wrong inside the form, or this is how it's supposed to work?
That is how it is supposed to work
Shouldn't it be something like: &search_filter[]=checkbox1,checkbox2 ?
Then you couldn't tell the difference between two items and one item that had a comma in it.
And if not, how can I make it work like that?
Obtrusive JavaScript. Don't do that. Forms work well the way they work.
That's perfectly normal. form data is always sent in key=value pairs, with one single value. Submitting key=value,value is not part of the HTTP spec, and would have the values treated as a single monolithic string, not two separate comma-separated values.
You can certainly use some JS to rebuild your form on the fly to use the value,value format, but then you'll have to mod your server-side scripts to accept that new format as well. PHP won't auto-split the values before you, because it's not a standard representation.
&search_filter[]=checkbox1,checkbox2
Why you need this?
Use this like:
<?php
$searchFilter = $this->input->get('search_filter');
foreach($searchFilter as $filter)
// some actions with filters.
You search_filter[] is simple array with values from checkbox inputs.

Post text from a text area

I have a form where a user types paragraphs into a text area and then it takes them to another page after they submit. How can I pass whatever they typed to the page after they submit? The text area might have linebreaks and if I use a query string to pass the data, it gives me an error. This is my current code to pass the field:
<?php
if(isset($_POST['form']))
{
$title = $_POST['title'];
$body = $_POST['body'];
header("SubmitForm.php?title=$title&body=$body");
?>
<html>
...html form...
It doesn't work when the text area has line breaks in it.
I would suggest installing a wysiwyg editor to make this easier for you, but i assume that would add some time for the learning curve.
The simplest tips I can give you is to set a CSS attribute for your textarea: white-space:pre so that when it gets submitted, all line breaks get sent as well.
On your server side, you would need to use the nl2br() function, so that when it gets saved on your DB or wherever you store them, all line breaks are converted to HTML breaks.
For your additional reference, I had a similar question like this last year.
You really shouldn't be putting anything that long in a query string in the first place. Look into using sessions to store data across pages instead.
(This is assuming I understood the question right)
urlencode the data in order to pass it via query string.

Store JSON in a hidden input element?

I need to be able to generate an effectively unlimited number of datasets, so what I want to do is something like this;
<input type="hidden" name="items[]" value="{id:1,name:'some-name'}" />
I tried JSON.stringify to convert my array in javascript and store it in the current hidden input element, but it wraps all the keys and values in double quotes, which obviously conflicts with HTML wrapping the entire value in double quotes. Somehow I need to escape the quotes, but I need this to work two ways...basically these elements are generated with PHP and placed in the page in order, then I can add or delete items on the user end and submit the page, which should have PHP iterating through these hidden elements and updating the records.
Anyone have any suggestions on an escaping method of some sort?
You can use escaping function presented here: http://phpjs.org/functions/htmlspecialchars:426
It should escape chars in json and make your string safe to use as value of html attribute.
If you want to do the escaping on PHP then you should use function htmlspecialchars() that is built in PHP.
What you want to do is grasp some of html5 data-* attrubites so you can dod
<div id="post-container" data-meta="{id:22,name:'Robert Pitt'}">
..
</div>
Then you can use htmlentites() to make the string safe and use javascript, you can get the data with javascript like so:
function ElementJson(id,attrib)
{
var post_c = document.getElementById(id);
for( var x = 0; x < post_c.attributes.length; x++)
{
if( post_c.attributes[x].nodeName.toLowerCase() == 'data-' + attrib.toLowerCase())
{
return post_c.attributes[x].nodeValue;
}
}
return false;
}
json = ElementJson('post-container','meta');
Via jQuery for instance you can do
json = $('#post-container[data-meta]').attr('data-meta');
A lot of large sites use it especially Facebook
base64_encode the data or run it through htmlentities() to turn the quotes in to entities :)
To be honest, if you are setting the value in javascript in the page then I am a little surprised that you ran into problems but here are a couple of suggestions: -
Of course the proper thing to do is HTML encode the data in the html attributes - but this requires calling htmlentities or similar so instead, why not URL encode the data using the "built in" javascript encode and decode and methods. URL encoding should escape double quotes to '%22'.
Or if you are already using jQuery, use the val() method to set (and get?) the value - I am sure that would deal with these issues for you (although I have not gone and actually checked this).

Categories