submit php variables with javascript (link?) - php

I'm creating a browser based game and at the moment I'm designing the script that updates the position of my character when he/she clicks on a different part of the map.
I am using a bit of ajax to do this which send a request to a php file called position_update.php. But for it to work I need to send two values along with it so it knows what the new position is, how do I do this? Below is my link that send the request to php file.
<a onClick="positionUpdate();"><img src="images/transparent.gif" border="0" /></a>
As a note, I'm using the php $_GET super global to retrieve the values when they're sent.
Thanks, Stanni

You need to hit the URL:
position_update.php?var1=val1&var2=val2
PHP will parse the get string into $_GET

BTW, you should ensure that degrades gracefully by having an equivalent href value that works for non-js users.

In case you need to encode the URL string, use the javascript function encodeURL():
sUrl = encodeURL("position_update.php?dir="+sDir+"&dist="+sDist);
And remember that in a client-server architecture, do not put too much implicit trust in the client. All of the application logic that handles game mechanics and rules enforcement should be contained in the server-side component.
A few years ago there was a really popular game called TetriNET (multiplayer online Tetris) that was designed without these security considerations. It took me about 3 days to crack the communication protocol and basically draw on other players' screens using server commands for creating/clearing blocks. It made cheating very easy using just a simple proxy.
So don't let the client 'tell' the server where the player is. Use the client only to display the interface, collect input, and display output. So have the client tell the server where the player 'wants' to move (direction, how far, etc.), and then have the server calculate the player's position based on what moves the player is legally allowed to make and his previous position.

Related

Many HTTP requests (API) Vs Everything in single php

I need some advice on website design.
Lets take example of twitter for my question. Lets say I am making twitter. Now on the home_page.php ,I need both, Data about tweets (Tweet id , who tweeted , tweet time etc. etc) and Data about the user( userId , username , user profile pic).
Now to display all this, I have two option in mind..
1) Making separate php files like tweets.php and userDetails.php. By using AJAX queries, I can get the data on the home_page.php.
2) Adding all the php code (connecting to db, fetching data ) in the home_page.php itself.
In option one, I need to make many HTTP requests, which (i think) will be load to the network. So it might slow down the website.
But option two, I will have a defined REST API. Which will be good of adding more features in the future.
Please give me some advice on picking the best. Also I am still a learner, so if there are more options of implementing this, please share.
In number 1 you're reliant on java-script which doesn't follow progressive enhancement or graceful degradation; if a user doesn't have JS they will see zero content which is obviously bad.
Split your code into manageable php files to make it easier to read and require them all in one main php file; this wont take any extra http requests because all the includes are done server side and 1 page is sent back.
You can add additional javascript to grab more "tweets" like twitter does, but dont make the main functionality rely on javascript.
Don't think of PHP applications as a collection of PHP files that map to different URLs. A single PHP file should handle all your requests and include functionality as needed.
In network programming, it's usually good to minimize the number of network requests, because each request introduces an overhead beyond the time it takes for the raw data to be transmitted (due to protocol-specific information being transmitted and the time it takes to establish a connection for example).
Don't rely on JavaScript. JavaScript can be used for usability enhancements, but must not be used to provide essential functionality of your application.
Adding to Kiee's answer:
It can also depend on the size of your content. If your tweets and user info is very large, the response the single PHP file will take considerable time to prepare and deliver. Then you should go for a "minimal viable response" (i.e. last 10 tweets + 10 most popular users, or similar).
But what you definitely will have to do: create an API to bring your page to life. No matter which approach you will use...

turn based game score recording

I'm developing a very, very basic turn-based game using php and jquery and I'm looking at two different ways of keeping track of the current user's score:
1) global javascript variables - for example var currentScore at the beginning of the js. The game action and turns are all controlled via ajax so I don't have to worry about a page refreshing losing the variable data.
2) mysql - create a row with currentScore, user, etc and access it / update it every turn.
I'm trying to balance a) load speed and b) making the score tamper-proof. I'm thinking that local javascript would be fast and less load time but mysql records would be more tamper-proof. Does anyone have any advice as to which is faster and which is more tamper-proof, or perhaps have another way of accomplishing this that I didn't list above?
Run your game in PHP, not in JS.
What I mean to say is instead of allowing the player's computer to control the action, and send the results back to the server...
that allows for people to hijack and send messages to your PHP like auto-firing pistols...
...or headshot scripts ...or speed-hacking.
...or even worse -- sending in messages like: "I just scored 500 points on my turn", and having your PHP script go: "Okay!".
So instead, the core of the game engine should run in PHP, the client should just say: "My character wants to move X squares.", and then the server can say: "No, you're a cheating tool, you can only move 3 squares.", and then the client will have to adhere to those rules.
In this regard, PHP will be 100% in control of the score-keeping.
any data that is not stored on the server will be tamperable. any data sent to the server can be doctored. not only should the server store all of the game data, but it should be validating all incoming data from the client. for instance, do the rules actually allow this player to use the move they are telling me they are using? Otherwise, it will be fairly easy to cheat. Then again, your project may not require that amount of scrutiny.
both,
never trust javascript in games. There will always be a clever player which will mess with it.
Use javascript for the gui part and controlling the game, but always check ALL results in PHP, especially player specific values. Check for the right player!! Else some losers will mess with your game.
Don't worry about speed, just script your game (of course with speed and data in mind) and investigate when you hit performance problems. One issue is important from beginning: think about your database tables and queries. That will become most likely your performnce bottleneck,more then bad php scripting.

Client-side page rendering, good or bad (PHP + Javascript\AJAX)

I am designing the back-end for a web application. I am in a situation where I am unable to collaborate with the front end developer. I also do not like inline HTML\PHP and am not in a position to integrate a template. My solution is that I would keep the front end completely separate from the back-end. The front end would communicate with the back end via AJAX (or jQuery). For example the file upload system would work like this:
<?
//Do stuff
if(!isUserLoggedIn())
die("0-Must be logged in");
//Do more
if(!fileIsTooBigOrNotTheRightType()) {
die("0-Bad files");
}
//Do even more
if(!move_uploaded_file($src,$dst) {
die("0-directory error");
}
echo "1-Success";
?>
The front end developer will simply AJAX the file to upload.php and interpret the response and take the appropriate action on the front end (Show the form, red out some fields, display an error message, redirect to the login form, etc.)
To reduce the number of HTTP queries each page may contain a hidden field with JSON data containing the dynamic elements that will be in place. For example on a private messaging system's inbox page the JSON string may include things such as the number of new messages, who each message is from, and the subject. The front end developer will be able to parse that data and use it any way he likes and is free to create a user friendly interface independent of me.
It is 2012 and I don't think it is wrong to assume the client's have javascript with AJAX support.
TLDR: I am shifting the work of rendering the page (putting elements in their place) to client side javascript. From an efficiency standpoint is this good or bad? It seems like less work the server has to do.
Being both a front and back end developer, my general approach is server-side first, then client side. Make the application work completely and thoroughly without any JavaScript, then move on (or let the front end guy) to the client-side. This ensures that everyone can use your app, even those who don't use JavaScript, such as screen readers and search engines.
What you're referring to is called an API. You make the interface, and then have the frond end developer make API calls to you.
It's possible, though you should be very clear about the specifics of the API (what you can do, and what you can't).
Also make sure you're secure (so that not everyone can access your API).
Other than that, you can do it, sure, no problem.
My suggestion would be to provide a kind of API to the front-end. So, the front-end designer could develop all the HTML, and populate by making javascript calls to your back-end code.
I would then suggest you submit code back to the javascript in JSON format. Javascript handles JSON data structures very well, and the data could then be used to construct the HTML to be injected into the DOM.
I hope I am not too late for the question.
I have done a site based on HTML/Javascript(JQuery) - AJAX - PHP, there is no SEO issue to my site, for example, it's No 3 for Google keywords: free restaurant bookings. Plus, Google has suggested a few ways to work for Javascript, e.g. hidden text.
(My views on the question, please correct me if I am wrong)
Good:
1. More close to MVP model;
2. Clear structure: User interface on front end, PHP/MySQL on server end, AJAX exchange data in between;
3. Easy to change code as of MVP model;
4. Performance: 2 files should be loaded faster than a big file, front-end for data input and validation, server-end for data process
Bad:
1. Javascript maybe disabled (United States: 2.06%, United Kingdom: 1.29%, France: 1.46%, Spain: 1.28%, Brazil: 0.26%) (http://developer.yahoo.com/blogs/ydn/many-users-javascript-disabled-14121.html)
2. Extra coding: JSON/JSONP, AJAX, deal with arrays in PHP and Javascript.
Finally, I suppose that "my general approach is server-side first, then client side." suggested by Madara Uchiha could be more practice, for example, it's what wordpress is using.

sql database access through javascript game

I have made a basic javascript game of blackjack (21) were the page does not refresh/post. I am wanting it to change a entity in a database (money) with out a user being able to easily access the page/method of changing the database. I was thinking about ajax but even this way a user could finde the page and then access the db. Is there a better way of doing this??? Thanks.
See this question for reference:
Preventing cheating for on-line arcade high score board
Blackjack is a simple enough game however where you can simulate every single variable server side, there is no need for client side processing in your case. Move all your code to the server side, feed the result to the client, feed the clients actions back to the server and it will be for all intents and purposes cheat proof.
This way, the client cant send scores/card ID's etc, only their actions stick|split|draw etc.
Anything the client can do, the client can hack. Javascript is quite open and not secure.
You can type javascript:... in the address bar and execute code arbitrarily, including calling any function in your application.

show google map markers with php

Hi everyone!
Im working on a google map project where the user can type in a address and gets the result of nearby restaurants ploted on a google map.
So far no problems. I've created a ajax call where the backend outputs and xml and then with jquery I create the markers.
But now to my problem.
With this ajax solution anyone can easily with firebug or other webdeveloper tool access the xml result that contains all names, latitudes, longitudes of the restaurant I have.
I want to somehow protect the data that is showed.
How can I do this?
How can I plot google map markers with php without jquery? Can it be done?
thx in advance!
Google Maps Markers for an interactive map (using a the GMap2 object in the API) must be created on the client side (in Javascript) and are therefore vulnerable to reverse engineering the data.
If you want to generate the map data on the server, then you are limited to static functionality on the client. You can use the Google Static Maps API to build a URL on the server, which includes the information about the markers you want to display and the region that the static map will show. This approach sacrifices some usability for the client (no dynamic zooming, panning, marker popups etc...) to protect your data.
N.B. A determined engineer will still be able to access your data (albeit with some difficulty) by:
Parsing your static maps URL to determine the map region
Analyzing the image data to find markers and determine their locations.
The only way to protect the data is to render the map before sending it to the browser. Doing that will take most or all the cool features of google maps away since you'd have to display just an image.
Any data that is accessable by google maps is accessable by someone with firebug.
Some things you can do to make life difficult for someone trying to grab your data:
In your server code, examine the headers to see if the request came from your client page. If the request came from anywhere else, return nothing.
Encode the data that you return from the server. Decode it as late as possible in your client code, so that you only have the plaintext for one restaurant in Javascript variables at any one time. That way someone with Firebug can only directly read one restaurant at a time.
Have your server only return a limited number of locations at once, even if somebody uses Firebug to change the request parameters so that it asks for restaurants within a huge radius. That way they can only grab the cyphertext for that many locations at once to paste into their own code in which they've placed a copy of your decoding function.
Instead of grabbing the cyphertext for even that limited number of locations in a single call, send multiple requests that each return a very small number of locations, with an extra parameter specifying which chunk of restaurants is requested.
Its not foolproof, but for someone to grab substantial quantities of your data will either take them a long time, or require fairly sophisticated attack techniques, such as spoofing the request headers.
Simple answer - you can't.
Long answer
You could draw an image overlay on server-side, kinda like Wikipedia overlay in Google maps, but I don't think it's worth the effort.
You could also store a key in php session and pass it to JavaScript on initial page load and then don't return the data if data isn't requested trough Ajax with the correct key (which is unique per browser session). This would just protect you from simple bots which don't support cookies. More mess then gain.
Also remember that if someone were to write competing site using your server as data-source then they would still have to tunnel Ajax requests trough their own server because you can't do cross-domain requests with JavaScript therefore you would see a lot requests from same IP (their web-server) in your web-logs and you could easily ban that IP. (Unless they download all at once and then serve from their own server).
And is it really necessary? It's not like restaurant locations are top secret.

Categories