I am checking if the particular parameter is passed and if a folder exists for that parameter. ex
if ((! isset($_GET["name"])) or (! is_dir($_GET["name"]))) {
print "----------------USER NOT FOUND-----------------" ;
}
and in my URL if have name=Erik and if that folder does not exist in that name, I want to print the Error message.
Also I would like to check if the parameter'name' is passed into URL using isset.
Somehow the above does not work and I am unable to figure out why.
Any input will help.
Thanks
or has a different use. It's for whenever something you are trying to do does not work, then it executes the other bit. Typical deprecated example would be when you try to do some database interaction, you'd write back then $STH = mysql_query('SELECT * FROM users') or die();. For your case, you should use the || operator instead, as explained in the documentation
Besides, you are not checking if someone submitted something. This will never print anything if a form is submitted with nothing in it. Both errors fixed, your code should look something like this:
if (empty($_GET["name"]) || !is_dir($_GET["name"])) {
print "----------------USER NOT FOUND-----------------" ;
}
Because, if someone submits the form, the url will be example.com/index.php?name=, which makes $_GET['name'] to be set while it's empty. I assume you want to say User not found in that situation.
Related
I have a personal search site project I'm building, at the moment the only data that is being displayed on the website is data that is retrieved using SELECT queries and the GET method using the super global $_GET['example']. Now I don't know if I'm doing this wrong but some parts of my page are only displayed if certain GET variables in the URL are set or not empty. Below shows how my URL looks
EXAMPLE: index.php?search_category=guitar&main_category=9&postcode_val1=NP22&distance_default=100&submit=search
I have a lot of these if(isset($_GET['search_category']) type conditions in my website which are replied upon and show particular parts of content depending whether or not these are either true or false.
I have been on a lot of other websites that have similar URL's, I have tried to alter and manipulate these and the content does not break, alter or change in any way yet when i try this with my url it breaks my page and only certain parts of content gets displayed by being based on what is set. Is there some other layer of protection I should add, would using something like a rewrite rule help? The code below shows how I have wrote a drop down box based on what has been set In the URL but if a user edits the URL this is easily broken.
if(isset($_GET['search_category']) && isset($_GET['main_category']) &&
isset($_GET['postcode_val1']) && isset($_GET['distance_default']))
{
$stmt = $getFromUi->dispCategories();
echo "<option value='0'>All</option>";
echo "<option value='#'>-------------</option>";
while($row = $stmt->fetch(PDO::FETCH_OBJ))
{
$selected = '';
if(!empty($_GET['main_category']) && $_GET['main_category'] == $row->cat_id)
{
$selected = ' selected="selected"';
}
echo '<option value="'.htmlentities($row->cat_id).'"'.$selected.'>'.htmlentities($row->cat_title).'</option>';
}
}
It will break because the strict nature of logic you use on your code. The && mark with isset mean any parameter you define not set will not evaluate to true. If the parameter is quite flexible why not ||.
If you need it to still evaluate all parameter try to do limit first if condition to main determiner. like $_GET['search_category'] and use the remaining $_GET['other_parameter'] as needed inside the block code of main if.
You would need to use a post method, so that this goes through as a request instead. In my experiance, get will only fetch the url you open - not actually pass anything through unless its in the URL.
Not sure if that made any sense, but check post out.
https://www.w3schools.com/tags/ref_httpmethods.asp is a good place to start to see the difference of get vs post.
I am trying to register a button click on my website using PHP.The click downloads a file to client's machine. Database connection was tested before and it works fine. I just need to register that click into DB. Here is my code, could you guide me through?
echo '<div id="fdbox1"><h2>Details</h2><p> Download full details in PDF format ('.$file_size.')</p></div>';
if(isset($_GET['dl']))
{
$server = "xx.xxx.xx.xxx";
$dbusername = "xxxx";
$dbpassword = "xxxx";
$database = "xxxx";
$dbcon = new mysqli($server,$dbusername,$dbpassword, $database);
$userid = $_SESSION['suserid'];
$date_downloaded = date('Y-m-d H:i:s');
$sql = "INSERT INTO external_activity (
userid,
saleid,
activity,
date_register,
) VALUES (
'".$userid."',
'".$ref_no."',
'".'Downloaded file'."',
'".$date_downloaded."'
)";
$dbcon->query($sql);
$dbcon->close();
}
If using jquery is an option, you could create a "register_click.php", paste the if(isset($_GET['dl'])) stuff inside and call it via ajax using an onclick listener that you will have to create and bind to the anchor.
You could do it with POST data instead of GET.
$i = 0;
if $_POST['submit'] {
$i++;
$number_of_times_clicked = $number_of_times_clicked_stored_into_database + $i;
}
After that restore the new value back into the database. If you really want the onclick you need javascript. PHP is unable to check when a button is clicked, since the code only works once when the page is loaded.
This is too long for a comment.
The & in your code might give you some problems, I said "might". If so, then consider changing those to & (ampersands).
Should it be the case, then you could change:
echo '<div id="fdbox1"><h2>Details</h2><p> Download full details in PDF format ('.$file_size.')</p></div>';
to:
echo '<div id="fdbox1"><h2>Details</h2><p> Download full details in PDF format ('.$file_size.')</p></div>';
Then you will need to check and see if each GET array is is set/not empty with isset() and !empty().
References:
http://php.net/manual/en/function.isset.php
http://php.net/manual/en/function.empty.php
I only see if(isset($_GET['dl'])) as a single array, so it's unsure as to how you're wanting to fetch the other GET arrays in your URL and if you did set those.
Your present code (if it's the full code), will throw a few notices about certain variables not being defined.
For example, the if(isset($_GET['dl'])) and using the other GET arrays, would look like this:
if( isset($_GET['f']) && !empty($_GET['l']) && !empty($_GET['dl']) ){
// do something inside here
}
You also need to make sure that the session was indeed started with session_start(); and to be included inside all files using sessions.
Reference:
http://php.net/manual/en/function.session-start.php
This is usually the first line under the opening PHP tag.
<?php
session_start();
// rest of your code
The $userid = $_SESSION['suserid']; needs to have a value/equal something, so that is unknown as to whether or not there is indeed a value for it.
Error reporting will be of help here for you, as will checking for errors against your query.
References:
http://php.net/manual/en/function.error-reporting.php
http://php.net/manual/en/mysqli.error.php
You also have a trailing comma in date_register, < and that needs to be removed, as I already stated in comments.
That alone would have thrown a syntax error.
The use of '".'Downloaded file'."' is unclear. If you just want to insert the Downloaded file as a string, then you can just place it inside single quotes 'Downloaded file' and do:
$sql = "INSERT INTO external_activity (
userid,
saleid,
activity,
date_register
) VALUES (
'".$userid."',
'".$ref_no."',
'Downloaded file',
'".$date_downloaded."'
)";
Make sure that the date_register column type is DATE and not VARCHAR or other format. Although VARCHAR would not throw an error, it's best to use MySQL's built-in dating functions; that column's type is unknown.
Now, make sure that the userid column is not an AUTO_INCREMENT'ed column, otherwise your code will fail.
If the ultimate goal here is to "UPDATE" that userid column, then use just that, UPDATE:
http://dev.mysql.com/doc/refman/5.7/en/update.html
You also need to make sure that all columns' types are correct and have a length long enough to accomodate the incoming data and that there are no characters that MySQL will complain about, such as apostrophes.
Escaping those with a prepared statement will ensure that it doesn't throw/cause a syntax error and is something you should be using in order to help prevent against an SQL injection and you are open to one right now.
References:
https://en.wikipedia.org/wiki/Prepared_statement
https://en.wikipedia.org/wiki/SQL_injection
This is the best way that I can offer for the question, given the information left in the question.
Again; check for errors. That is one of the most important things that needs to be done during the development of your code.
For example:
If anyone fails at the login function (for example: enters wrong password) on my webpage, i want to show an error-message at the webpage. My idea was like that:
if(doLogin()) {
//....
}else {
$GLOBAL['errorLogin'] = "Wrong Userdata";
}
and then echo the global-variable in the .html.
But i searched also for this topic and found only this method, but everyone had used the $_SESSION variable for this instead of $GLOBAL.
Is my variant with the $GLOBAL varible wrong or bad practise?
And why use $_SESSION for a error-message, if i only echo the message one time and don't need it in the next request?
I think you mean $GLOBALS (notice the s) which is a suber global variable and therefore can be accessed from anywhere in the PHP script (also from within functions or methods).
There is nothing wrong about that.
I don't think that you should use the $_SESSION variable for that, because the user needs to see the error message only one time. In your case, and in most cases, that's why it might make no sense to store it in a session.
Personally, I just would use a custom errorMessage-Array, like that:
//store all Error Messages in one array.
$errorMessages = array();
if(doLogin()) {
//....
}else {
$errorMessages["Login"] = "Wrong Userdata";
}
//...
foreach($errorMessages as $key=>$message){
echo $key.": ".$message."<br>";
}
i am new to PHP so don't know how this would turn out. Lets say i have a add friend page. And in the database lets say i have a table called "friends" and the following rows: my_id and friend_id and id_request.
And now i have a php page that will look something like: addfriend.php?id=friendid
And then i use the id from that link to insert in to the database my id and that friendid.
The question is what will happen if someone enters "kdjfkldjlfk" in the link in the address bar?
you need to prevent those cases and validate
ex:
test that the $_GET['id'] isset and that the friendid is real , you could query the database to see that the id exists ...
If you mean "What will happen if someone visits the URI for an id that does not exist?", then it depends on what your PHP says should happen.
If your PHP doesn't check how many results it got from its SQL query, then it is quite possible that the page will spit out a 500 Internal Server Error.
If you've designed it properly, then it would return a document that explains that you cannot add a user that does not exist as a friend.
Actually, if you've designed it properly then the data should be sent via POST not GET since adding a friend is not an idempotent event. (See the HTTP specification — GET should be free of side effects)
You need to validate your user input. First, cast the $_GET value to an int type, and if it's equal to 0, tell them they've mistyped it.
$var = (int)$_GET['id'];
if($var == 0)
{
// Error
}
else
{
// The rest of your code
}
It turns out that PHP has some pretty cool filter functionality built-in. You should learn them and use them:
if (filter_var($_GET['id'], FILTER_VALIDATE_INT) === false) {
// error
}
if (filter_var($_GET['email'], FILTER_VALIDATE_EMAIL) === false) {
// error
}
if (filter_var($_GET['ip_address'], FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) === false) {
// error
}
http://us.php.net/manual/en/function.filter-var.php
I have a call to a PHP script from my home page which I do like this:
echo 'Delete';
So it is pretty standard.
Then in my PHP I have this code:
<?php
// delete_problem
include '../connect.php'; // Here I have db connection settings
error_log ( ".......in delete problem");
$problem_id = mysql_real_escape_string($_GET["problem_id"]);
?>
And the last line where I try to get the problem_id is throwing the undefined index error. Any idea why?
Thanks!
Have you got an actual connection inside connect.php? Or does it just store variables and the like?
mysql_real_escape_string may be causing a problem as if a connection is not available it will fail.
Beyond that, try echoing out the contents of the GET variable. You can also check whether it exists by using (isset($_GET["problem_id"])).
For values coming from the user, always make sure they are present and possibly validate their format.
Use:
if (isset($_GET['problem_id']) && trim($_GET['problem_id']) != '') {
$problem_id = $_GET['problem_id'];
// make sure it is a number
} else {
echo "No problem id given!";
}
That warning appears because the $_GET array doesn't contain a value problem_id, most likely because it was not passed with the URL.
Bleh, all you people with the mysql_real_escape string...
Always check if a variable is set before you try and assign the value of it to another variable.
Also use (int) to cast!!
if (isset($_GET["problem_id"])){
$problem_id = (int) $_GET["problem_id"];
}