I have PHP up to 5.4, Perl 5.8, C and Python available server-side.
So basically I have JavaScript client-side and I'm generating a string. I'd like to save this string server-side.
I know how to load a string from a file in the server with XMLHttpRequest. But I don't like the idea to use a file for just storing a string even if it's a big one.
So what I'm looking is an example from a string which goes from Javascript to PHP (or something available for me) and back from PHP to JavaScript.
If it does not involved MySQL it is better (I just want to save a string).
I have nothing about jQUERY but I'm not planning to look into it right now.
EDIT 1 : To precise what I need, the user will connect to the website play with the JS application and in the middle save some simple stuff (the string). I want that afterward when he'll come back (or another user) to the website he can get his stuff back.
EDIT 2 : since it cannot be done as nnnnnn says in the comment. I changed the question to :
I'd like to save a string during the use of a JS application and restore it for the next user.
EDIT 3 : I'm looking for a simple example for saving the string in a file, as no other solution is feasible.
If I understand correctly:
send needed to server and save it to some temporary place (file, db, whatever)
next load, ask via ajax if there is any change or data saved
if so, load them
if data are javascript sode, you can use eval() code
Another, quite dirty solution is use cookie data
You cannot expect that supported features in new browsers are supported in old ones as well - savind localy is not possible.
As per my understanding, you want to share data between user. So that, you are sending information to the server and server is responsible to give the same data later. And you dont want to use file as well as database. Session is not suitable to keep large data.
Then,
An alternate solution is store your data in Memcache server. This is more suitable in your case. But you have to remember one thing about Memcache, That is, Memcache is not persistent storage. But you can increase Memcache flushing interval as much as you want.
Note: Memcache is RAM consuming process.
Related
Alright, so I've looked at a ton of questions, but I only found 1 that resembled what I am trying to do. Here is the link to it: Passing POST data from one web page to another with PHP
I want to pass data from one PHP file(we'll call it editData.php) to another PHP file(we'll call it submitData.php). Neither file has any HTML elements (pure PHP code I mean). The first file(editData.php) receives $_POST data, edits it, and needs to send it to the second file. The second file(submitData.php) needs to be able to read in the data using $_POST. No sessions nor cookies can be used I'm afraid.
In the linked question above, the answer accepted was to create hidden fields inside a form and POST the data from there. This worked for the OP because he had user interaction on his "editData.php", so when the user wanted to go to "submitData.php", he would POST the data then.
I can't use this solution(at least, I don't think I can), because I am accessing (and sending $_POST data to) editData.php from a javascript AJAX call and there will be no user interaction on this page. I need the modified data to be POSTed by code, or some other way that does the transfer 'automatically'(or 'behinid-the-scenes' or whatever you want to call it). submitData.php will be called right after editData.php.
I don't know if I can rewrite submitData.php to accept GET data, so count that out as well (it's a matter of being able to access the file). I really don't want to echo stuff back to my original JavaScript function(and then AJAX again). I am encrypting info in editData.php, and (while it sounds silly to say it) I don't want to make it easy for someone to develop a cipher for my encryption. Returning values after being encrypted(viewable with Inspect Element) would make it too easy to decipher if you ask me.
I feel like this issue could come up a lot, so I'd expect that there is something obvious I'm missing. If so, please tell me.
tl;dr? How can I send data to a PHP file via the POST method while only using code in another PHP file?
Well you might consider just streamlining your approach and including the submitData logic at the end of the editData file. But assuming that this is not possible for some reason (files live on different systems, or whatver), your best bet might be to use cURL functionality to post the data to the second script.
If the files are on the same server though I would highly recommend not posting the data to the second script as this will basically just double the amount of requests your web server needs to handle related to this script.
Normally I try to format my question as a basic question and then explain my situation, but the solution I'm looking for might be the wrong one altogether, so here's the problem:
I'm building a catalog application for an auction website that has the ability to save individual lots. So far this has worked great by simply creating a cookie with a comma-separated list of IDs for those lots, via something like this:
$_COOKIE["MyLots_$AuctionId"] = implode(",",$arrayOfIds);
The problem I'm now hitting is that when I go to print the lots, I'm using wkhtmltopdf through the command-line to request the url of the printout I want, like this:
exec("wkhtmltopdf '$urlofmylots' filename.pdf");
The problem is that I can't pass a cookie to this call, because Apache sees an internal request, not the request of the user. I tried putting it in the get string, but once I have more than a pre-set limit for GET parameters, that value disappears from the $_GET array on the target url. I can't seem to find a way to send POST data between them. My next possible ideas are the following:
Maybe just pass the sessionID to the url, and see if there's a way that I can use PHP to dig through the cookies for that session and pull the right cookie, but that sounds like it'd be risky security-wise for a PHP server to allow (letting one session be aware of another). Example:
exec("wkhtmltopdf '$urlofmylots?sessionId=$sessionIdFromThisRequest' filename.pdf");
Possibly set a session variable and then pass that session Id, and see if I can use PHP to wade through that information instead (rather than using the cookie).
Would I be able to just create an array and somehow have that other script be aware of it, possibly by including it? That doesn't really solve the problem of wkhtmltopdf expecting a web-facing address as its first parameter.
(not really an idea, but some reasoning) In other instances of using this, I've just passed an ID to the script that generates the markup for wkhtmltopdf to parse, and the script uses that ID to get data from the database. I don't want to store this data in a file or the database for the simple purpose of transferring data from the caller to the callee in this case. Cookies and sessions seem cleaner since apache/php handle memory allocation for these sessions.
The ultimate problem here is that I'm trying to get my second script (referenced here by $urlofmylots) to be aware of data available to the calling script but it's being executed as if it were an external web request, not two php scripts being called from the web root.
Can anyone offer some insight here?
You might consider rendering whatever the output of $urlofmylots?lots=$lots_to_print would be to a temporary file and running wkhtmltopdf against that file.
I've never really cached data before, but I feel as though it will greatly improve my site.
Basically, I pull JSON data from an external API that helps the basic functionality of my website. This info doesn't really change that often yet my users pull the info from the API thousands of times a day. If it updated once a day, that would be fine. I want to run a cron job daily that will pull the info and update the cache.
I already tried a few different things, both pulled using PHP:
1) Store data in an SQL table
I had it working, but there's no reason why I should ping the database each time when I can just store it in basic HTML/JSON.
2) .JSON file (using fwrite)
I had it stored, but the only way this worked is if the .getJSON() callback function is prepended to the JSON data and then the data is surrounded by parentheses (making it jsonp, I believe).
Does anyone have any advice or any directions to lead me in? As I said, I've never really done anything like this so I don't even know if I'm remotely headed in the right direction.
Edit:
Okay so I talked to my hosting and since I'm on a shared hosting (dreamhost) I can't install memcached, which sucks. The only info they could give me was that if it is on http://pecl.php.net/ then I can most likely use it. They said APC is available. I'm not sure if this fits my problem. I'd like to be able to access the cache directly in jQuery. Thanks
You can use memcached. Memcached is an in-memory key-value store for small chunks of arbitrary data (strings, objects) from results of database calls, API calls, or page rendering. Very easy to implement and has a low system footprint.
Since you can't use memcached, go back to your database option and store it in a table using the MEMORY engine.
try memcached. You can easily generate a string key and store whatever blob of json you want with it. works like a dictionary, except persists in memory.
There's an option to give it an expiration time (otherwise it just stays cached forever). So when the user requests the data, just check if it's stored in memcached. If it is, great, return it. If it's not, do whatever you do to build it, then put it in memcached with a 24 hour expiration.
If your data varies per user:
I've done this by storing an object in the $_SESSION array.
I attach a quick bit of logic that determines if the data expiry period is up. If so, it draws new data, serves and caches. If not, it draws from $_SESSION and serves it up.
Try Redis.
And to store data easily without unexpected errors on set/get - encode it using base64.
this to store:
file_put_contents($path, $json_text);
and this to restore:
$json_text = file_get_contents($path);
echo $json_text;
echo can be used to pass the json exactly as it comes from the http request. if you need to parse it into a variable (in javascript) you can use array = JSON.parse('<?php echo $json_text; ?>');. if you need to parse in php, use $array = json_decode($json_text);.
OK Ive written this neat javascript 'thing' using jquery and ajax. Its all based on the idea that a div has an attribute that lets you write inside the div. (contenteditable=true). I thought it would be cool to make a chatroom type thing out of it, and holy cow its doing some cool stuff(*), but I have an issue.
Using ajax I post to a php page that takes the posted data (x,y, text, id) and stuffs it into a JSON-like object. Without writing to a database (overkill I think), how can I make this data persist? See the problem? : The variables in a php page are essentially vapor after the page has ran, so my javascript ajax call to retrieveNewJSON() would find nothing.
*using jquery effects and setting colors I have variably placed text that scrolls and evaporates, matrix style, for example. Also, a cursor is placed in the div where the user clicks.
You have to store the data somewhere. If you don't want to use a full blown database you can store them in flat files (ie: txt) and use PHP's file functions to handle the files.
Of course this is not very scalable, and I'd strongly recommend using a database if you are going to be using this a lot.
You could use cookies (client-side) or session variables (server-side), or you could write to a file for longer-term storage.
You could use a the $_SESSION variable to persist data.
// Call at start of PHP script
session_start()
//....
// Store object
$_SESSION['obj'] = json_encode(obj);
in your pull script:
// Call at start of PHP script
session_start()
// Retrieve object
echo $_SESSION['obj'];
Note that when using sessions you have to make sure that you call session_start() at the top of every php script that uses the session.
I would not recommend trying to store this in a file unless you are supporting a very low number of users and have taken proper data sanitation steps to physically write files to the server. If you need this to persist past the length of a session you should be using a database.
It is worth noting that you can't update a users session without some other form of centralized storage. Unless you have some sort of long-polling / comet type setup you will have to have some sort of central storage place. Something I would take a look at would be memcache.
If you want to avoid using a database engine (which would have a lot of overhead for a multiple-read, multiple-write app like a chat room anyway), you might look at a simple object store like memcache, couch, or mongo. Files are also a valid option, provided you store them outside of the Web root with proper permissions. Bottom line is, you'll have to use some sort of storage engine on the back end in order to make the data shareable across multiple user sessions.
If this is simply a tech demo or a proof of concept, I wouldn't worry too much about overhead right away.
I'm just playing around with some PHP and was wondering what happens when an object from a class is created within another PHP script?
I assume once its created and been processed their is no way of then going back and 'playing' around with it from another script?
The idea is i'm trying to create a kind of deck of cards using a card class, each card has specific data that is added to each individual object to make it unique, suit, value etc. Once its created i need to be able to go back to specific cards to use them. In java i'd have an arraylist of card objects, i'm not sure how to approach the same area in PHP.
Thanks.
There is no problem passing objects around inside a php script, your problem is that php is that the webserver calling the script is essentially "stateless". i.e. every time someone posts the url from a browser a complete fresh copy of the php program is fired up.
To save data between times there are several options:-
One is to use $_SESSION variables which are associated with a user session but $_SESSION itself is an array so it gets really clumsy holding complex structures here, also , it sounds like you want to share the deck between users.
You could serialise your object and store it in a file -- which is OK as long as its not updated very often -- but if its updated by every user they will start overwriting each others changes.
Much better is to store the deck in a database (SQLITE is usually built into php) so that several users can share and update in a controlled manner.
Another good option would be to use one of the popular data caches such as "memcached" which will cache the data between calls to the script.
To reuse an object between page calls seems to be your issue. Maybe you can serialize the object and store it in database and pick it up back?? Check php.net/serialize Let know how it goes.
What you could do to keep the objects available to you is to serialize the objects and store them in a database table. If you link a game ID or something similar to the cards then you can retrieve them later using this game ID.
I don't know if the cardgame you are writing is realtime, using a database might be too much overhead. Another possibility is to use an existing caching solution, like for example Memcache.
So you want to create a serverside coded cardsgame? Good luck!
It is possible to do this, tho I think a script like a javascript you are talking about is much more suitable.
You could make a function that initialises a deck of cards and work with indexes etc. Save your things in cookies / sessions and work with postbacks. It's gonna be a hell of a job tho in my opinion compared to jscript.
Tho when you think about it, you could use ajax to make this game feel better for the user :).
Php scripts are not like Java server apps.
Where your Java server will run for a long time, your php script will just be a one time thing.
Instead of this kind of process : user make a request to Java-run server, server receive the request in one of it's infinite loops, server process it, server send the response, server wait for new request; you have this kind of thing : a webserver (Apache, Nginx, whatever other webserver) receive the user's request, understand it needs to be interpreted by php, starts a php child, this child do what's in the script, send its answer, dies, the server wait for new requests.
So, when a php script ends, nothing (in good case) is left from it.
But, a php script can use persistent storage on the server so another request can read from it. That's why you have files, databases and even shared memories functions.
If the games state is for one user only, you can use sessions (usually files) to store your deck object. If it's meant to be used by multiple players, you should store it after serialization in a database.