How Use get method to do different functions PHP .? - javascript

I wrote a simple php file to open different websites using different URLs.
PHP code is here.(it's file name is user.php)
<?php
$id = $_GET["name"] ;
if ($id=joe) {
header('Location: http://1.com');
}
if ($id=marry) {
header('Location: http://2.com');
}
if ($id=katty) {
header('Location: http://3.com');
}
?>
I used those 3 methods to call php file.
1.http://xxxxxx.com/user.php?name=joe
2.http://xxxxxx.com/user.php?name=marry
3.http://xxxxxx.com/user.php?name=katty
But php file opens only http://3.com at every time.How to fix this.?
how to open different websites for each names.?

Your comparison is wrong. joe, marry and katty are string type
<?php
$id = $_GET["name"] ;
if ($id=='joe') { //<--- here
header('Location: http://1.com');
}
if ($id=='marry') { //<--- here
header('Location: http://2.com');
}
if ($id=='katty') { //<--- here
header('Location: http://3.com');
}
?>
Here is PHP comparison operator description.
http://php.net/manual/en/language.operators.comparison.php

First off, using the == vs = is what's wrong with what you have, however whenever you are doing a script take care to not be redundant. You may also want to think about making a default setting should no conditions be met:
<?php
# Have your values stored in a list, makes if/else unnecessary
$array = array(
'joe'=>1,
'marry'=>2,
'katty'=>3,
'default'=>1
);
# Make sure to check that something is set first
$id = (!empty($_GET['name']))? trim($_GET['name']) : 'default';
# Set the domain
$redirect = (isset($array[$id]))? $array[$id] : $array['default'];
# Rediret
header("Location: http://{$redirect}.com");
# Stop the execution
exit;

So it looks like your question has been answered above but it's probably not that clear for you, if you're just beginning (using arrays, short php if statements etc).
I'm assuming that you're just learning PHP considering what you're trying to achieve, so here is a simplified answer that is easier to understand than what some other people have posted here:
<?php
// Check that you actually have a 'name' being submitted that you can assign
if (!empty($_GET['name'])) {
$id = $_GET['name'];
}
// If there isn't a 'name' being submitted, handle that
else {
// return an error or don't redirect at all
header('Location: ' . $_SERVER['HTTP_REFERER']);
}
// Else your code will keep running if an $id is set
if ($id == 'joe') {
header('Location: http://1.com');
}
if ($id=marry) {
header('Location: http://2.com');
}
if ($id=katty) {
header('Location: http://3.com');
}
?>
Hope this helps you better understand what's happening.

You should use == for conditional statements not =
if you use = , you say :
$id='joe';
$id='marry';
$id='katty';
if($id='katty') return 1 boolean

Related

How do I insert # character in echo statement for JavaScript?

When I include the # glyph in my statement, to return to an anchor on the page, the PHP code fails.
I've tried everything I can think of to resolve this issue, escaping PHP characters, writing JavaScript functions and the list goes on.
if (isset($_POST['name'])) {
$_POST = array();
echo "<script>window.location.href='Contact_Us.php#myForm'</script>";
} else {
unset($_POST);
}
There are no error messages.
The page appears to refresh and the code to unset the POST variables fails.
If you really want to do things that way simply drop out of PHP instead of trying to echo things.
if (isset($_POST['name'])) {
$_POST = array();
?>
<script>window.location.href='Contact_Us.php#myForm'</script>
<?php
} else {
unset($_POST);
}

How to send user to a certain website when a specific access code is submitted

I have been looking for multiple ways to redirect users to a html page when a certain access code if submitted in a form. I have the form up and is working properly, but I can't get it to redirect to the right page, I have seen 1 other post like this, but with specific user login.
<?php
$_GET["code"] = $accessCode;
if ($accessCode === "code123") {
header("Location: http://www.example.com/code_123.html");
} else if ($_GET["code"] === "test") {
header("Location: http://www.example.com/code_test.html");
} else {
header("Location: http://www.example.com/unknown_code.html");
}
?>
I even tried using the redirect option (cPanel)
Whenever I use the code code123 or test, they redirect me to unknown_code.html
I tried using both if ($accessCode === "code123") and ($_GET["code"] === "test")
You have it backwards.
When you are making an HTTP "GET" Request, PHP will store the "query string parameters" in the global $_GET array.
For example, http://www.yoururl.com?code=code123&mobile=1
In this context, the query string starts with "?" and is delimited by "&", leaving you with key value pairs of:
code = code123
mobile = 1
PHP converts that and stores it in the global $_GET array as such:
$_GET['code'] = "code123"
$_GET['mobile'] = 1
The same thing would happen if you were to do an HTTP POST request, where instead of the query string, the HTTP POST Request "Body" contains the query string, or in some cases, JSON, or XML, etc.
PHP would parse that and you would get as so:
$_POST['code'] = "code123"
$_POST['mobile'] = 1
So for your context, you actually have it backwards.
You want to "assign" $accessCode with the value stored in the $_GET array at index "code"
<?php
$accessCode = $_GET['code'];
if ($accessCode == 'code123') {
header('Location: http://yaddayadda', 301); /* you can change 301 to whatever redirect code that is most appropriate. this is good for information search engines on the appropriate behavior. do a google search for http redirect codes to understand. 301 is permanent redirect. 302 is temporary. etc.*/
exit;
} elseif ($accessCode == 'code234') {
header('Location: http://');
exit;
}
else {
echo 'No valid access code.';
exit;
}
You need to assign the value of $_GET['code'] to $accessCode.
<?php
$accessCode = $_GET['code'];
switch ($accessCode) {
case 'code123':
header("Location: http://www.example.com/code_123.html");
exit;
case 'test':
header("Location: http://www.example.com/code_test.html");
exit;
default:
header("Location: http://www.example.com/unknown_code.html");
exit;
}
?>
Also, when you are comparing a single variable to several values, use a switch statement.
It's a good idea to follow a redirect header with exit - you're done at that point.

How to allow PHP file to be only accessible through call reference /view.php?url=123

I want to block direct access to my php file and make it work only through a call reference like: mysite.com/view.php?url=123
And when it is called direct: mysite.com/view.php
Returns: Invalid ID!
My script:
if(isset($_GET['url']) && isset($sources[$_GET['url']])){
$link = $sources[$_GET['url']]; }
After your update in question, you just need to add ELSE condition, if condition false than execute else part, something like:
if(isset($_GET['url']) && isset($sources[$_GET['url']])){
$link = $sources[$_GET['url']];
}
else{
echo "Invalid ID"; // error message
}
But, in your IF condition, you have a problem, suppose if any one try to access this URL:
mysite.com/view.php?url=asdfasdf
Maybe, you code break, in this case, you can also use intval() function, if value of url always integer.
<?php
$url = $_GET['url'];
if(!$url) {
die('Invalid ID!');
}

JS and PHP variable don't show good

If this was in asks, sorry for that, but I want to speed help, thanks!
Do you have suggestions for result this ? Because when I do this it show last $name, it doesn't work.
JavaScript:
var name = 'Test';
if(name === 'Test'){
<?php $name = "Test"; ?>
} else {
<?php $name = "Error"; ?>
}
I have click function and when I click I check ID of object, but after this I want check this id is good e.g. (if(id === 'content')) and show good alert, when i checked it.
This is your server-side code, which will execute exactly once when the page is requested:
$name = "Test";
$name = "Error";
After this code executes, $name will be "Error". Every time.
This is your client-side code, which will execute exactly once when the page renders in the browser:
var name = 'Test';
if(name === 'Test'){
} else {
}
After this code executes, name will be 'Test'. Every time.
You're trying to mix server-side code and client-side code. They don't mix like that. They execute on two completely different platforms at two completely different times in two completely different contexts. Whatever you're trying to do (which we don't know), this isn't how you do it.
The way you wrote it isn't going to work. First of all PHP is executed before the JavaScript is parsed. In your code you set a variable inside PHP, so nothing actually happens. If you want something written on the page use echo or print.
What I think you want is to send a variable to PHP. For this you need a form or an Ajax-call.
If you want it the other way around, set a JavaScript variable based upon a PHP value you need to use JSON notification.
The only way I could even think of doing this would be:
<script>
var name = 'Test';
if(name === 'Test'){
</script>
<?php $name = "Test"; ?>
<script>
} else {
</script>
<?php $name = "Error"; ?>
<script>
}
</script>

Javascript variable passed to PHP session in Wordpress

I am not sure if this is the best way to do it, but I have a button that when pressed it call a onClick JS function and it passed two parameters. I want to save those two parameters on a php session, then load another page and use those values.
So, I know that if I use something like this on PAGE !:
<?php
session_start();
$message1 = "A message";
$message2 = "Another message";
$_SESSION['routineName'] = $message1;
$_SESSION['dayName'] = $message2;
?>
I can go to PAGE 2, and by using $_SESSION['routineName'] I can use that info.
So, on PAGE 1 I have that code inside the function that is called with my onClick:
function trackIt(routine, dayName)
{
<?php
session_start();
$message1 = "A message";
$message2 = "Another message";
$_SESSION['routineName'] = $message1;
$_SESSION['dayName'] = $message2;
?>
}
I tried things like:
function trackIt(routine, dayName)
{
<?php
session_start();
$_SESSION['routineName'] = ?> routine; <?php
$_SESSION['dayName'] = $message2;
?>
}
and others, but nothing works.
And this is how I am calling the onClick (trackIt) function:
echo('<td colspan="3" style="background-color:#005673; text-align:right; padding: 4px 0px;">
<button class="btnTrack" onClick="trackIt(\'' . $name . '\' , \'' . $nameday1 . '\')" >Track It!</button></td>');
What I want to do is to save both, routine and dayName, into the session.
Is it possible to save JS variables/parameters into PHP Session?
PS: I am using Wordpress.
Thanks!
The PHP code you put in your files is not executed at Javascript run time, it is executed even before the page gets sent to the client. So you can't access $_SESSION from anywhere within your content, you need to do that from Wordpress's code. Usually this is done via a plugin.
You need to pass your Javascript variables to a server side PHP. As #Grasshopper said, the best (or at least most maintainable way) is through AJAX:
// This is your JAVASCRIPT trackit function
function trackIt(routine, day) {
$.post(
'/wp-setvar.php',
{
routine : routine,
day : day
}, // You can add as many variables as you want (well, within reason)
function success(data) {
// Here we should receive, given the code below, an object
// such that data.result is a string saying "OK".
// Just in case you need to get back something from the server PHP.
// Otherwise just leave this function out.
}
);
};
On the server, you need to create a specific file to accept the incoming variables (it would be best if you did this from a plugin, in order not to add files outside the installation: such practices are frowned upon by security scanners such as WordFence). This here below is a butcher's solution.
<?php /** This is wp-setvar.php */
/** Set up WordPress environment, just in case */
require_once( dirname( __FILE__ ) . '/wp-load.php' );
session_id() || session_start();
nocache_headers();
// DO NOT, FOR ANY REASON, ACCESS DIRECTLY $_SESSION
// ONLY USE A VARIABLE WITHIN $_SESSION (here, "ajjx")
// OTHERWISE THIS MAY ALLOW ANYONE TO TAKE CONTROL OF YOUR INSTALLATION.
$_SESSION['ajjx'] = $_POST;
Header('Content-Type: application/json;charset=utf8');
die(json_encode(array(
'result' => 'OK', // This in case you want to return something to the caller
)));
Now whenever you need the session-saved variable, e.g. "routine", you put
<?php
...
$value = '';
if (array_key_exists('ajjx', $_SESSION)) {
if (array_key_exists('routine', $_SESSION['ajjx']) {
$value = $_SESSION['ajjx']['routine'];
}
}
Or you can define a function in your plugin,
function ajjx($varname, $default = '') {
if (array_key_exists('ajjx', $_SESSION)) {
if (array_key_exists($varname, $_SESSION['ajjx']) {
return $_SESSION['ajjx'][$varname];
}
}
return $default;
}
Then you just:
<?php print ajjx('routine', 'none!'); ?><!-- will print routine, or "none!" -->
or
<?php print ajjx('routine'); ?><!-- will print nothing if routine isn't defined -->
An even more butcherful solution is to add the function definition above within wp-config.php itself. Then it will be available everywhere in Wordpress. Provided you have access to wp-config.php. Also, backup wp-config first and use a full FTP client to do it; do not use a Wordpress plugin to edit it, since if wp-config crashes, the plugin may crash too... and you'll find yourself in a my-can-opener-is-locked-within-a-can situation.
If you don't feel comfortable with some of the above, it's best if you do nothing. Or practice first on an expendable Wordpress installation that you can reinstall easily.

Categories