I am working on my personal site, where I want to store my customers recent search result limited to that particular session.
I am using PHP platform and Javascripts.
Here is an example of what I am exactly looking at :
It stores your previously searched domain name for that particular session so that user can make decision by comparing those results.
Thanks.
EDIT- Well Thanks for all of your answers and suggestions.
But If you have noticed
above example
It looks like some kind of script loading a new content on the same page without refreshing it and keeping previous search content <div> as it is.
How to achieve this using javascripts or some sort of div layer ????
UPDATE START
This example uses page reload. If you want to do it without page reload, you can but you'll have to use AJAX to load new search results. But then, it's not a PHP question. I suggest looking at jquery library, as it makes it easy. Tutorials: http://docs.jquery.com/Tutorials and e.g. this one ( http://docs.jquery.com/Tutorials:Getting_Started_with_jQuery#Rate_me:_Using_Ajax ).
When loading data via AJAX, the page rendering result (in my example search.php) should return only HTML for results part, not whole HTML page. This is generally a first part of my tutorial (without session).
But I really think that AJAX in here is not really needed. Session is more reliable and allows access to your page from older / mobile browsers where not always JS works correctly.
UPDATE END
Ok then. Let's try the simple tutorial then. Sorry if too simple, but I don't know your exact level.
PHP has mechanism called sessions. In reality they are just bytes stored on server. Server knows which session is for each client by reading session cookie from client browser.
Not every page uses sessions (not every page needs it, and session uses server space, even if only temporarily), session is not enabled by default. To turn on session you use command
<?php session_start(); ?>
In most cases this is either run by PHP framework you use, or put near the top of your site. Session is definitely needed if you want to authenticate user somehow. Or in your case :)
To access session you can use superglobal $_SESSION variable (superglobal means that you can access it anywhere). It's an array, so session element will be e.g. $_SESSION['search'] etc.
As example, let's assume that your page looks like that
<html>
...
<form action="search.php" method="post">
Search: <input type="text" name="searchQuery" />
<input type="submit" value="Search" />
</form>
...
</html>
this very form will send user search to file named search.php. It can be the same file where the form resides - in simplest case when you put both your code and HTML in one file. Beginners often use this schema, although it's not advisable as result is a mess and hard to further change.
In search.php then, you'll use similar code:
<?php
if (!empty($_POST['searchQuery'])) //we have a new search
{
$result = do_search($_POST['searchQuery']);
}
?>
Then, somewhere below you'll display your search result ($result variable). do_search() function is your search mechanism, I guess you have it somewhere. You may have it not 'wrapped' in a function, then I advise to create it like that, it's much more useful.
function do_search($searchQuery)
{
...
return $result;
}
mind it, the above code doesn't use sessions yet. Let's add saving previous search results in session. The code may then look like that:
<?php
session_start(); //Starting session
//let's create session variable used to store results
if (!isset($_SESSION['searches']))
$_SESSION['searches'] = array();
if (!empty($_POST['searchQuery'])) //we have a new search
{
if (isset($_SESSION['searches'][$_POST['searchQuery']]) //User already searched on this value, delete previous result from sesion
{
unset($_SESSION['searches'][$_POST['searchQuery']]);
}
$result = do_search($_POST['searchQuery']);
//Let's add new search on the begining of session array to make iterations easier.
$result = array($_POST['searchQuery'] => $result); //convert result to same format as session table
$_SESSION['searches'] = array_merge($result, $_SESSION['searches']);
}
?>
In display you'll now not iterate on $result variable as before, but instead you will do something like
foreach ($_SESSION['searches'] as $query => $result)
{
...//display of single result
}
I haven't tested following code and it's not a full program. Parts to display result and to do actual search are not described but I guess you have them already prepared. Also, this is only one possible approach of countless possibilities. But I hope this helps :)
Possible modification - now I always perform search, even if user already searched on this term. You may want to receive the result from cache without second search. Then the code will look like
if (isset($_SESSION['searches'][$_POST['searchQuery']]) //User already searched on this value
{
$result = $_SESSION['searches'][$_POST['searchQuery']];
unset($_SESSION['searches'][$_POST['searchQuery']]);
}
else
{
$result = do_search($_POST['searchQuery']);
}
For more in-depth information about sessions and some other constructs used in my example I suggest PHP manual
http://pl.php.net/manual/en/book.session.php
and various tutorials over the network. Or you can add a comment here :)
Put this code near the beginning of your script(s):
if (!isset($_SESSION['previous_searches']) || !is_array($_SESSION['previous_searches'])) {
$_SESSION['previous_searches'] = array();
}
[edit]
This code snippet checks if if there is already an array with prevous searches and if not it will be created.
[/edit]
Then when the user hits the search page put this code in the receiving script of the search:
$_SESSION['previous_searches'][] = $_GET['what_ever_your_search_value_might_be'];
[edit]
This code snippet adds the current search value to the and of the array with previous search values
[/edit]
Now you have all previous search values in $_SESSION['previous_searches']
If your website is a web application where you never reload the page nor change the page, you can keep it JavaScript in a global store (declare at top level something like var StoredSearch = []; and use it). If not, then use $_SESSION to store this and AJAX to save/load searches from JavaScript to PHP.
Related
I am using wordpress for a web site. I am using snippets (my own custom php code) to fetch data from a database and echo that data onto my web site.
if($_GET['commentID'] && is_numeric($_GET['commentID'])){
$comment_id=$_GET['commentID'];
$sql="SELECT comments FROM database WHERE commentID=$comment_id";
$result=$database->get_results($sql);
echo "<dl><dt>Comments:</dt>";
foreach($result as $item):
echo "<dd>".$item->comment."</dd>";
endforeach;
echo "</dl>";
}
This specific page reads an ID from the URL and shows all comments related to that ID. In most cases, these comments are texts. But some comments should be able to point to other pages on my web site.
For example, I would like to be able to input into the comment-field in the database:
This is a magnificent comment. You should also check out this other section for more information
where getURLtoSectionPage() is a function I have declared in my functions.php to provide the static URLs to each section of my home page in order to prevent broken links if I change my URL pattern in the future.
I do not want to do this by using eval(), and I have not been able to accomplish this by using output buffers either. I would be grateful for any hints as to how I can get this working as safely and cleanly as possible. I do not wish to execute any custom php code, only make function calls to my already existing functions which validates input parameters.
Update:
Thanks for your replies. I have been thinking of this problem a lot, and spent the evening experimenting, and I have come up with the following solution.
My SQL "shortcode":
This is a magnificent comment. You should also check out this other section for more information
My php snippet in wordpress:
ob_start();
// All my code that echo content to my page comes here
// Retrieve ID from url
// Echo all page contents
// Finished generating page contents
$entire_page=ob_get_clean();
replaceInternalLinks($entire_page);
PHP function in my functions.php in wordpress
if(!function_exists("replaceInternalLinks")){
function replaceInternalLinks($reference){
mb_ereg_search_init($reference,"\[custom_func:([^\]]*):([^\]]*)\]");
if(mb_ereg_search()){
$matches = mb_ereg_search_getregs(); //get first result
do{
if($matches[1]=="getURLtoSectionPage" && is_numeric($matches[2])){
$reference=str_replace($matches[0],getURLtoSectionPage($matches[2]),$reference);
}else{
echo "Help! An unvalid function has been inserted into my tables. Have I been hacked?";
}
$matches = mb_ereg_search_regs();//get next result
}while($matches);
}
echo $reference;
}
}
This way I can decide which functions it is possible to call via the shortcode format and can validate that only integer references can be used.
I am safe now?
Don't store the code in the database, store the ID, then process it when you need to. BTW, I'm assuming you really need it to be dynamic, and you can't just store the final URL.
So, I'd change your example comment-field text to something like:
This is a magnificent comment. You should also check out this other section for more information
Then, when you need to display that text, do something like a regular expression search-replace on 'href="#comment-([0-9]+)"', calling your getURLtoSectionPage() function at that point.
Does that make sense?
I do not want to do this by using eval(), and I have not been able to accomplish this by using output buffers either. I would be grateful for any hints as to how I can get this working as safely and cleanly as possible. I do not wish to execute any custom php code, only make function calls to my already existing functions which validates input parameters.
Eval is a terrible approach, as is allowing people to submit raw PHP at all. It's highly error-prone and the results of an error could be catastrophic (and that's without even considering the possibly that code designed by a malicious attacker gets submitted).
You need to use something custom. Possibly something inspired by BBCode.
So I have 2 different .ini files that stores different languages and I'm trying to choose which one I will read data from via a form.
Is there an easy way to do this, or should I use MySQL to switch between the files? With this I mean storing the filename and then changing the filename value in the database via the form.
Or as I'm trying to accomplish, store a $filename variable in PHP that holds either file 'a.ini' or file 'b.ini', depending on my choice.
It should also be possible to switch back and forth between the choices.
Right now I'm stuck and have no idea what to do.
I have this and I know I have to put it in a function, but from there I have no clue..
$ini_array = parse_ini_file("languages/EN.ini");
I'm trying to change the "EN" to a different value, but to no success so far.
My code right now, after som modifications: https://pastebin.com/a077jFE1
Right now I either have to refresh the page after submitting or submit again for the changes to take effect. Why is this occuring?
I would try something like this:
if (isset($_POST["your_form_field"])){
$ini_string = "languages/" . $_POST["your_form_field"] . "ini";
$ini_array = parse_ini_file($ini_string);
} else {
# Default
$ini_array = parse_ini_file("languages/EN.ini");
}
mmdts has a good answer too, store the posted value and use it on all your pages :)
Have you tried looking up storing data in a session?
A good guide on how to do this is available at:
How to set session in php according to the language selected?
You can follow the first answer to the letter in the php script present in the action of the form which allows the user to select the language.
And in all your other pages, you'd just check for
session_start(); // You have to call this at the start of each page to make sure that the $_SESSION variable works.
if ($_SESSION['lang'] == 'en')
$ini_array = parse_ini_file("languages/EN.ini");
etc.
And the full session documentation is available at http://php.net/manual/en/reserved.variables.session.php
So, I'm not sure if I can do this. If not, then any suggestions would be appreciated. Sorry in advance if the question is ridiculous...
I have an array that I created in php which is holding different user names populated off the database. When a user submits a form I want to use jQuery to check that the user name being submitted does not already exist in the array already created. I'm not quite sure how to do this. This is where I'm heading.
PHP section:
$existing_users = array();
$existing_users[] = $users; //this is reiterating in a while loop
HTML section:
<input type='text' name='user_name' id='user_name' />
jQuery section:
function checkAllFieldsForm() {
if (jQuery.inArray($('#user_name').val(),$existing_users) == -1) {
alert('no way this worked');
}
};
Not sure if maybe I should be using $.each instead or something else...
It seems like I would need to access the array $existing_users by an id but I haven't given it one. Do I need to give it a division id?
What you want to do is create this as a javascript array while still on the server side. I.e. have php output it as a javascript array (by looping over the array values and emitting them into a javascript array, or by outputting the array in JSON encoding). Then it will be available to javascript on the browser side, and all is well. PHP variables themselves are NOT available on the browser side, since PHP does not run there and was finished running before the server sent the web page.
Take a look at: Generating a JavaScript array from a PHP array.
You'll have to print the array into the javascript source, so the javascript can read it.
Should be like this:
var client_side_existing_users = <?php echo json_encode($existing_users); ?>;
if (jQuery.inArray($('#user_name').val(), client_side_existing_users) == -1) {
alert('no way this worked');
}
(I called it client_side_existing_users to make it very clear that the variable exists on the client side / in the browser, and has left the server-side world)
Keep in mind, the user will be able to see the contents of existing_users by looking at the page source. This could also make the page size massive if there are a ton of users. I would love to know why you're doing this, because there's probably a better way.
Is it a good practise, to use the php session object, to store several of my variables, can be arrays of request results.
I need this method, because I would like to do the request in a php file, store the result and immediately, (depending on result) redirect to a page,
It's probably not the best way, that's why I'm asking
thx for any advice,
edit: structure:
index.html
handler.php
view1.php
in index.html, I've got a
<form action="handler.php" ...
in handler.php, I construct a request and get a result,
if ($result->success)
header("location ./view1.php");
else
echo 'failed';
in view1.php, I would like to list the result array
Webshops do it - so why shouldn't you?
Some of the larger eCommerce frameworks store complicated data and objects in sessions and PHP handles this pretty well.
That's what sessions are for! So the general answer is "Yes: it's a good practice".
Here are some alternatives, however:
Consider using ajax calls to update parts of the loaded page without reloading it;
Cookies - not good for big amount of data, but generally can live longer than a session. Not useful in your particular case, however;
SQL servers are usually well-optimized, and when your query returns lots of rows and you cut those into sections with a LIMIT clause, or just repeat exactly the same request soon after the first time, the subsequent requests aren't of such a big load for the database server.
I just seen your update to the question.
AJAX can do the trick for you the best. I can imagine it all done within a single web page:
form data is submitted by an AJAX call to you handler.php, which..
returns either a JSON-packed array of results or a short string NOT FOUND, for example.
Then, the JS on your page either creates a new DOM element - a table, or a set of div's, with the returned results, or just creates a new div with some sad toon face and a "we didn't find anything' message.
// set session
session_start();
$_SESSION['my_session'] = array('var1' => 'value1', 'var2' => 'value2'); // your result list
session_write_close();
// get Session
echo ($_SESSION['my_sesson']['var1']);
if ($result->success)
header("location ./view1.php");
else
echo 'failed';
This is not good practice to use redirects to route requests. You can do it without additional request from the user.
Like this:
if ($result->success) {
include(dirname(__FILE__) .'/'. 'view1.php');
} else {
echo 'failed';
}
Thus, all variables from handler.php will be available in view1.php.
I render a page using YUI. and depending on the user I need to change how it is rendered. This change is not something that can be parametrized, it is drastic and different for each user.
Please tell me how can I generate Javascript dynamically?
I personally use a PHP file to pass a JavaScript object made up of some basic session and internal settings, nothing mission-critical as passing information to the client isn't overly secure, but I believe it might follow the same principles as what you are looking for.
Similarly, I use this to display certain elements once the client is logged in, although all the authorization is still done on the server-side. If my session handler gives the PHP file the ok, it outputs a JavaScript object using a PHP heredoc string, otherwise, it doesn't output anything. You can use attributes of this object to compare against, or you could output only the JavaScript for how a certain page should be rendered, based on settings in your PHP file.
HTML:
<script src="common/javascript/php_feeder.php" type="text/javascript"></script>
PHP:
//my session handler authorisation check has been removed
//although you could place your own up here.
//assuming session was authorised
//set content type header
header("content-type: application/x-javascript");
$js_object = <<<EOT
var my_object = {
my_attr: '{$my_attr}',
my_attr2: '{$my_arrt2}',
etc: '{$etc}'
}
EOT;
print($js_object);
You can probably create two separate Java script files, and include the required file, depending upon the user type.
Pseudocode
If user_type is One
<Script src='one.js' type='javascript'></script>
else
<Script src='other.js' type='javascript'></script>
End If
JavaScript has an eval function, so I think (I haven't tried it) that you can generate JavaScript by writing it into a string variable (and then calling eval on that string variable).
A little bit of elaboration here would most certainly help in getting you a more descript and helpful answer. That in mind, though, you could easily just use functions declared inside an if statement to provide distinctly varied experiences for different users.
A very basic example:
<script>
function do_something(userType)
{
if (userType == 'A')
{
// everything you need to do for userType A
}
if (userType == 'B')
{
// everything you need to do for userType B
}
}
</script>