I have a stored url in a MySQL database. (http://example.com/page.php?ex='$_GET[ex]') When I retrieve it to create a dynamic link it gives me http://example.com/page.php?ex=%27.$_GET[ex].%27 and of course won't work.
I can't seem to be able to get (sorry had to use it!) the $_GET variable.
To be exact the cell contains...
Submit Risk Assessment<button>Create / Edit</button>
It seems that the string have been encoded by urlencode
You should decode the url encoded string
$a = urldecode('http://example.com/page.php?ex=%27.$_GET[ex].%27');
echo $a;
// print the url
Not really answering the question, but my solution was to create a separate field in the database for the url only. I then used deceze's suggestion of sprintf and it works perfectly.
if(!empty($row[buttonlink])){
$ex = $_GET[ex];
$rawlink = $row[buttonlink];
$format = '<button>Create / Edit</button>';
$buttonlink = sprintf($format, $rawlink, $ex);
}
Only had a small number of buttons to do and they could all be labelled 'Create / Edit'. I could add another field to have the label called into the sprintf too.
Related
I need to parse user submitted urls before echoing their submitted urls on my page. need to parse the urls as I won't know what urls they will be submitting nor the structures of their urls.
On each submitted url, I need to add the key part of each query string on the $key array and the value part of each query string on the $value array. How to do this ?
Example, a user submits this url:
http://example.com/autos/cars/list.php?country=usa&min_price=5000
FIRST STEP
In this example, I need the $key array to be populated with:
country,
min_price
And, I need the $value array to be populated with:
usa,
5000
Then I need to echo each array's values.
How to do this ?
SECOND STEP
I need to auto add the appropriate encoding functions in the submitted url. So now I won't be echoing like this:
echo 'http://example.com/autos/cars/list.php?country=usa&min_price=5000';
But after parsing the url and after adding the appropriate encoding php functions in the correct spots of the url, I will be echoing like this:
echo rawurlencode('http://example.com/autos/cars/list.php') .'?country=' .urlencode('usa') .'&min_price=' .intval(5000);
Can you see, I auto added rawurlencode on the file path and urlencode on the query string's values and can you see I added intval where the query string's value was an INT ?
Well, I did all this additions manually here ofcourse to show you what I want php to do on auto. I really need to get php to auto analyze the url and auto add the rawurlencode(), urlencode() and intval() where appropriate. Add the 3 functions on the correct spots on the url.
How to do this ?
Once these two steps are achieved, then I can say a custom php function has been built that analyzes submitted urls and auto encodes the urls with the appropriate encoding functions (rawurlencode, urlencode, intval) on the correct spots on the url.
My Failed Attempt:
print_r(parse_url($url)); echo '<br>';
$keys = array(print_r(parse_url($url))); echo '<br>';
foreach($keys as $key=>$value)
{
$key = array();
$value = array();
echo $key['0']; echo '<br>';
echo $value['0']; echo '<br>';
}
Don't know how to proceed from this point onwards.
Using window.location.hash (used to pass in ID for page) returns something like the following:
Also, for people asking why I used window.location.hash instead of window.location.href is because window.location.href started looping infinitely for some reason, and .hash does not. I don't think this should be a big deal, but let me know if it is and if I need to change it.
http://website.com/NewPage.php#?name=1418019307305
[The string of numbers is actually epoch system time]
When using PHP to try to retrieve this variable It is not picking up any text in the file It's supposed to write to.
<?php
$myfile = fopen("File1.txt","w");
echo $_GET['name'];
fwrite($myfile, $_GET['name']);
fclose($myfile);
?>
Try to print $_SERVER variable and it will give you the array and in the desired key you can get the values. It can help you to find that variable in the string.
If you want to get the value after the hash mark or anchor, that isn't possible with "standard" HTTP as this value is never sent to the server. However, you could parse a URL into bits, including the fragment part, using parse_url().
This should do the trick:
<?php
$name_query = parse_url("http://website.com/NewPage.php#?name=1418019307305");
$get_name = substr($name_query['query'], strpos($name_query['query'], "=") + 1);
echo $get_name;
?>
Working example: http://codepad.org/8sHYUuCS
Then you can use $get_name to store "name" value in a text file.
The hash tag is a fragment that never gets processed by the server, but rather the user-agent, i.e. the browser, so JavaScript may certainly access it. (See https://www.rfc-editor.org/rfc/rfc3986#section-3.5). PHP does allow you to manipulate a url that contains a hash tag with parse_url(). Here's another way to get the info:
<?php
$parts = parse_url("http://website.com/NewPage.php#?name=1418019307305");
list(,$value) = explode("=",$parts['fragment']);
echo $value; // 1418019307305
The placement of the hash tag in this case wipes out the query string so $_SERVER['QUERY_STRING'] will display an empty string. If one were to rewrite the url following best practice, the query string would precede the hash tag and any info following that mark. In which case the script for parsing such a url could be a variation of the preceding, as follows:
<?php
$bestPracticeURL = "http://website.com/NewPage.php?name=1418019307305#more_data";
$parts = parse_url( $bestPracticeURL );
list(,$value) = explode("=", $parts['query']);
$hashData = $parts['fragment'];
echo "Value: $value, plus extra: $hashData";
// Value: 1418019307305, plus extra: more_data
Note how in this case parse_url was able to capture the query string as well as the hash tag data. Of course, if the query string had more than one key and value, then you might need to explode on the '&' into an array and then explode each array element to extract the value.
I have a URL that contains a department name that will pull records from the database.
The URL looks like this: submissions.php?department=Settings,%20Security%20&%20Payments which is the equivalent of Settings, Security & Payments
My query needs to pull records from the table where the department is equal to Settings, Security & Payments.
How can convert that GET variable back to what I would expect it to be?
I tried html_entity_decode but it ignores the & and only gave me everything prior to that.
Whats the best way to do that?
Side note, if it was my data I would make it simple and pull it by ID but we dont have a table that has ID's for the departments.
Try urldecode()
You can see the manual here. http://uk3.php.net/urldecode
<?php
$string = "submissions.php?department=Settings,%20Security%20&%20Payments";
$decoded = urldecode($string);
echo "Original string: $string\n";
echo "Decoded string: $decoded\n";
?>
http://codepad.org/Bq1Gt30s
Use urldecode($your_URLstring)
I am using PHP to save the values of a form as JSON into a cookie like so:
// set cookie with search values so we can use jQuery to repopulate the form
setcookie('jobSearchValues', json_encode($form_state['values']), 0, '/');
This works great and then on the JavaScript side I can use this to get at the values:
var jobSearchValues = JSON.parse($.cookie("jobSearchValues"));
$("#keywords").val(jobSearchValues.keywords);
Again this works great, but the problem is that when a value for one of the fields in the form has a space in it, the space gets replaced with a "+". So when the form gets repopulated the text field displays like this for example "hi+mom". Is there a better way to go about this? By the way, $form_state['values'] is a PHP array. There are 4 fields in the form that I am setting as JSON into the cookie.
Use setrawcookie( '<name>', rawurlencode( json_encode( $value ) ), ... ) and then manually url-decode & json-parse on the client side (with JSON.parse(decodeURIComponent(cookie)))
This is weird. json_encode is not supposed to replace spaces with +..
setcookie is probably urlencoding it.
You will have to urldecode it in javascript before using it.
Try this:
(taken from phpjs)
function urldecode(str) {
return decodeURIComponent((str+'').replace(/\+/g, '%20'));
}
and then
var jobSearchValues = JSON.parse($.cookie("jobSearchValues"));
$("#keywords").val(urldecode(jobSearchValues.keywords));
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