I am using the following statement to check for post data and set a variable if it comes through via the URL:
if($_SERVER['REQUEST_METHOD']=='POST')
{
$sort = $_GET['sort'];
} else {
$sort = "mgap_ska_id";
}
I need the variable to be assigned a value via POST, but only if the value is passed through the URL. If the URL doesn't contain the variable, the value needs to the a string I can pass to a query. Is it better to use if/then or is some other method better?
Thanks
You have two conditions:
If it's a post request
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
}
Use the get variable if present
$sort = isset($_GET['sort']) ? $_GET['sort'] : 'mgap_ska_id';
Just put them together:
$sort = 'default'; // If it's a get request
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$sort = isset($_GET['sort']) ? $_GET['sort'] : 'mgap_ska_id';
}
just check
if(isset($_GET['sort']){
$sort = $_GET['sort'];
}
else{
$sort = "mgap_ska_id";
}
but don't forget to check for valid data. Never trust a users input.
also you may try following will work with POST and GET Methods
if(isset($_REQUEST['sort']){
$sort = $_REQUEST['sort'];
}
else{
$sort = "mgap_ska_id";
}
For your reference
You should use $_GET when someone is requesting data from your
application.
And you should use $_POST when someone is pushing (inserting or
updating ; or deleting) data to your application.
Either way, there will not be much of a difference about performances : the difference will be negligible, compared to what the rest of your script will do.
Make sure you have a form input field named "sort":
$sort = '';
if($_SERVER['REQUEST_METHOD']=='POST'){
// Sent by POST
$sort = $_POST['sort'];
} else if ($_SERVER['REQUEST_METHOD']=='GET'){
// Sent by GET
$sort = $_GET['sort'];
} else {
// Neither - set a default.
$sort = "mgap_ska_id
}
echo $sort;
Related
I am receiving post values. I want a suggestion for logic to handle empty or not set post values.
Is there such a way if one of them receives empty post, the $Data array should not receive anymore values and make it empty. In other words, i am trying to immitate the try and catch feature. If on any POST is empty, ignore reading the rest of POST and make that array as empty
Is my second draft considred valid?
First draft
if(!empty(isset($_POST["SHOWSCHEDULE_SHOWTYPE"]))){
$DATA["SHOWSCHEDULE_SHOWTYPE"] = $_POST["SHOWSCHEDULE_SHOWTYPE"];
}
if(!empty(isset($_POST["SHOWSCHEDULE_SHOWTITLE"]))){
$DATA["SHOWSCHEDULE_SHOWTITLE"] = $_POST["SHOWSCHEDULE_SHOWTITLE"];
}
if(empty($DATA)){
//do something
}else{
//do something else
}
Second draft
try{
if(!empty(isset($_POST["SHOWSCHEDULE_SHOWTITLE"]))){
$DATA["SHOWTITLE"] = $_POST["SHOWSCHEDULE_SHOWTITLE"];
}else{
throw new Exception('POST SHOWSCHEDULE_SHOWTITLE');
}
if(!empty(isset($_POST["SHOWSCHEDULE_SHOWTYPE"]))){
$DATA["SHOWTYPE"] = $_POST["SHOWSCHEDULE_SHOWTYPE"];
}else{
throw new Exception('POST SHOWSCHEDULE_SHOWTYPE');
}
} catch (Exception $e) {
echo 'ERROR: ', $e->getMessage(), "\n";
unset($DATA);
}
You can use one if statement with all required POST parameters.
if(!empty($_POST['var1']) && !empty($_POST['var2']) && !empty($_POST['var3']) && !empty($_POST['var4'])):
/*and then assign all the POST values to a $DATA array as you want.*/
$DATA['var1'] = $_POST['var1'];
$DATA['var2'] = $_POST['var2'];/* and so on..*/
endif;
I personally prefer to white list values that I loop through and assign.
<?php
$valid_keys = ['SHOWSCHEDULE_SHOWTYPE', 'SHOWSCHEDULE_SHOWTITLE'];
$at_least_one_empty = false;
foreach($valid_keys as $data_key)
{
$data[$data_key] = isset($_POST[$data_key])
? trim($_POST[$data_key]) // Remove accidental user whitespace.
: ''; // If unsubmitted - set to empty string.
if($data[$data_key] === '')
$at_least_one_empty = true;
}
if($at_least_one_empty) {
unset($data);
} else {
process($data);
}
Note with the sample code above an unsubmitted value will be assigned the empty string. This might not be the behaviour you want.
However if you just want to assign and check you received all inputs this might do (no filtering or validation):
<?php
$valid_keys = ['SHOWSCHEDULE_SHOWTYPE', 'SHOWSCHEDULE_SHOWTITLE'];
foreach($valid_keys as $data_key)
$data[$data_key] = $_POST[$data_key] ?? null;
$not_all_received = in_array(null, $data, true);
I want to make action if the current url only equals to this: https://www.example.co.il/index.php?id=1000&2222
$url = 'https://www.example.co.il/index.php?id=1000';
if(strpos($url,'&2222'))
{
// Do something
echo "2222";
}
else
{
// Do Nothing
}
To exactly do what you are asked, try this
//actual link (http or https)
$actualUrl = (isset($_SERVER['HTTPS']) ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$url = 'https://www.example.co.il/index.php?id=1000';
if($actualUrl === $url) {
//do something
}
But if you just want to retrieve the id :
$id = $_GET('id');
//return 1000 in your case
You're able to read the parameters in the URL using the $_GET object. It lists the keys and values in the querystring, i.e. in your example,
https://www.example.co.il/index.php?id=1000
if you use:
print $_GET['id'];
you'll see 100.
so you could simply check for the existence of the key 2222:
if (isset($_GET['2222'])) { /** do something **/ }
bear in mind, this is only the case if you're actually reading a URL the script is running on.
your method of searching for a string within the URL is appropriate if you simply want to match a value in a string, whether its a URL or not.
USE THIS
// Assign your parameters here for restricted access
$valid_url = new stdClass();
$valid_url->scheme = 'https';
$valid_url->host = 'www.example.co.il';
$valid_url->ids = array(1000,2222);
$url = 'https://www.example.co.il/index.php?id=1000&2222';
$urlinfo = parse_url($url); // pass url here
$ids = [];
parse_str(str_replace('&', '&id1=', $urlinfo['query']), $ids);
if($urlinfo['scheme'] == $valid_url->scheme && $urlinfo['host'] == $valid_url->host && count(array_intersect($valid_url->ids, $ids)) == count($valid_url->ids)){
echo 'valid';
// Do something
}else{
echo 'in valid';
// error page
}
How I can create multiple get/post request in page URL?
Like this:
http://www.example.com/?goto=profile&id=11326
I already tried with this:
$doVariableprofile = isset($_GET['goto']) ? $_GET['goto'] : null;
if($doVariableprofile == 'profile') {
if(empty($_SESSION['logged'])) require_once('register.php');
}
how i can add more request?
now i have http://www.example.com/?goto=profile
i trying do this http://www.example.com/?goto=profile&id=1
$testt1 = isset($_GET['goto']) ? $_GET['goto']:null;
if($_GET['goto'] == 'profile?id=".$_GET['id']"'){
require_once('profile.php');
}
Doesn't work page when I add to profile?id="$_GET['id']"')
$goto = isset($_GET['goto']) ? $_GET['goto']:null;
$id = isset($_GET['id']) ? $_GET['id']:0;
if($goto == 'profile' && $id != 0){
require_once('profile.php');
}
you need to assign these values to variables, if you directly write $_GET['id'] in
'if condition' and those values are not available then you may get
"Notice: Undefined index: " error.
I believe this could be done like this
$url = "profile?id=".$_GET['id'];
if($_GET['goto'] == $url){
require_once('profile.php');
}
another thing I understood this could be done like this
if(isset($_GET['goto']) && $_GET['goto']=="profile"){
if(isset($_GET['id'] || $_GET['id']==''){
header("Location: profile.php");
}
}
I've been trying to work my way to it simply must check it with all inputs in the present that I might have 100 lines so got it done less to just check it all together for an error or what?
What I think about that: instead of taking 14 lines of code that make it less but may be the same,
if($_POST["email"] == "")
{
$error = 1;
}
if($_POST["pass1"] == "")
{
$error = 1;
}
if($_POST["pass2"] == "")
{
$error = 1;
}
if($_POST["fornavn"] == "")
{
$error = 1;
}
if($_POST["efternavn"] == "")
{
$error = 1;
}
if($_FILES["file"] == "")
{
$error = 1;
}
Just create an array of field names and loop over them...
foreach(array('email','pass1','pass2',...) as $field) {
if(empty($_POST[$field])) {
$error = 1;
}
}
$_FILES you will have to handle separately. You can create another loop if you want. The structure of $_FILES is different though; I think you should be checking the "error" field. Check the docs.
Another way to approach this, considering the fact that you don't seem to be performing different tests for each field, or responding with specific error messages, is to use array_diff_key:
$names = array('email', 'pass1', 'pass2', 'fornavn', 'efternavn', 'file');
$names = array_keys($names); // convert $names to keys
$posts = array_filter($_POST); // filter out any falsy values
$fails = array_diff_key($names, $posts); // check for the differences
$error = $fail ? 1 : 0;
If you then wish to respond with specific messages depending on what is missing, you already have a list of the problem parameters in $fails. If you wish to extend the above to take into account specific value checks, you could write your own array filter callback function and pass it's name as the second parameter to array_filter... however this wont allow you to choose a different filter response based on array key, only on array value. All because rather annoyingly array_filter doesn't receive a key value when filtering an array.
I am getting tired trying to see what is wrong. I have two php. From the first I am sending a variable 'select1' (basically the id) to the second and than I want to update that record uploading a pdf file.
$id = "-1";
if (isset($_GET['select1'])) {
$id = mysql_real_escape_string($_GET['select1']);
}
if(isset($_POST['Submit'])) {
$my_upload->the_temp_file = $_FILES['upload']['tmp_name'];
$my_upload->the_file = $_FILES['upload']['name'];
$my_upload->http_error = $_FILES['upload']['error'];
if ($my_upload->upload()) { // new name is an additional filename information, use this to rename the uploaded file
mysql_query(sprintf("UPDATE sarcini1 SET file_name = '%s' WHERE id_sarcina = '%s'", $my_upload->file_copy, $id));
}
}
If I put a line with a valid id, like:
$id = 14;
it is working. What I am doing wrong? Thank you!
If you need to accept both post & get, then you should try something like the code below to retrieve the variable.
$var = 'select1';
if( isset( $_POST[$var] ) ) {
$id = $_POST[$var];
} else if( isset( $_GET[$var] ) ) {
$id = $_GET[$var];
} else {
$id = -1;
}
You are using both GET and POST at the same time. As far as I can see, this condition is not returning True
if (isset($_GET['select1']))
Edit: If you don't find any answer in above; maybe some more information/code can help getting to a solution.