Php UPDATE row function - php

I am trying to allow users to upload a profile image for my site. The file upload part works fine (although there is nothing deterring them form uploading a non-image file). However I can't get it to update the "profile" row in the mysql database. I think it has something to do with the $_SESSION['user_id'] but I'm not sure. Any ideas why it wont update the row?
<?php
if(isset($_POST['submit'])){
$temp = explode(".",$_FILES["file"]["name"]);
$newfilename = ('ProfileImage') . rand(1,99999) . '.' .end($temp);
move_uploaded_file($_FILES['file']['tmp_name'],"images/profile/" . $newfilename);
$con = mysqli_connect("localhost","root","","testsite");
$q = mysqli_query($con,"UPDATE user SET profile = '".$newfilename."' WHERE username = '".$_SESSION['user_id']."'");
}
?>
<form action="" method="post" enctype="multipart/form-data" name="">
<input type="file" name="file" required>
<input type="submit" name="submit" value="Update Image">
</form>
Just in case you need to see this, this is the "functions.php" page where $_SESSION['user_id'] is defined:
<?php
#session_start();
function loggedin(){
if(isset($_SESSION['user_id']) && !empty($_SESSION['user_id'])){
return true;
} else {
return false;
}
}
function getuser($id, $field){
$query = mysql_query("SELECT $field FROM user WHERE UserID='$id'");
$run = mysql_fetch_array($query);
return $run[$field];
}
?>

I am assuming your error is here:
$q = mysqli_query($con,"UPDATE user SET profile = '".$newfilename."' WHERE username = '".$_SESSION['user_id']."'");
And that it should be like this:
$q = mysqli_query($con,"UPDATE user SET profile = '".$newfilename."' WHERE UserID = '".$_SESSION['user_id']."'");
Looks like you switched out UserId with username.
When it comes to the page where you supposedly is setting $_SESSION['user_id'], the code you displayed here does no such thing.
It defines two functions, but does not call them, and does not assign a value to user_id.
So first, update the query as shown above, then do a var_dump of $_SESSION, to see if you have stored anything in it. If not you need to go back a few steps, and make sure you actually set the session variables.

Related

Search-engine: Php get data from anchor-tag

I have this html search here:
<form action="index.php" method="POST">
<input id="search" type="text" placeholder="Search for Friends" name="search_name">
<input class="submit" type="submit" name="search-submit" value="Search">
</form>
And this php code for the search engine:
<?php
if (isset($_POST['search-submit'])) {
$search_name = $_POST['search_name'];
$aVar = mysqli_connect('localhost','root','','socialnetwork');
$result = mysqli_query($aVar, "SELECT username FROM users WHERE username LIKE '%$search_name%'");
$found = 1;
while ($row = mysqli_fetch_assoc($result)) {
$username = $row['username'];
#$output .= '<h2 class="friends-display">'.$username.'</h2><hr>';
}
}
?>
Now this code is working fine. It allows the user to search for other users.
The anchor tag "friends-display" shows the result of the code by using the variable $output. The $output is then echoed later in the aside.
My problem is the following: I want to make an if-statement so when the anchor tag "friends-display" is clicked by the user it should show the profile of the username the user has clicked on.
Example: you search for Mike and you find this username. Than you click on it and it should show the profile of Mike. How can I make this with an anchor tag?
I have tried if isset(), but it did not work for me.
Change the output variable like below
....
while ($row = mysqli_fetch_assoc($result)) {
$username = $row['username'];
#$output .= '<h2 class="friends-display">'.$username.'</h2><hr>';
}
....
Create a new file profile.php and add the following basic line.
<?php
If(isset($_GET['user']) && !empty($_GET['user'])){
$username = $_GET['user'];
// check for username found in database.
// if not found exit with error "user not found"
// else show user profile
}else{
Die("unothrized access");
}
I hope this will guide you to achieve your target..
Happy coding :)

Login returns password does not match in php

I hope you are doing great. I have within my project a login functionality. when I try to login. It gives me this strange error that I did not write within my login.php script. I wrote it somewhere else and did not make an import to it. I hope you guys can help me identify the problem.
Thanks in Advance. Cheers,
Some useful pieces of my code:
Login.php Script:
<?php
include_once 'Header.php';
?>
<style>
#container {
height: 92vh;
}
</style>
<div id="container">
<br>
<?php
$_SESSION['logged'] = null;
//in this page we do things slightly differently - the code for validation and displaying messages is done
//before we display the form
echo '<div id = "div_1"><h1>Login</h1>';
//display the form
echo '<div id="div_2"><div id="div_2">
<form action="Login.php" method="post">
<label>Email<br>
<span class="small">enter your Email</span>
</label>
<input type="text" name="Email" value=""/>
<label><br>Password<br>
<span class="small">enter your password</span>
</label>
<input type="password" name="Password" />
<button type="submit" name="submit" value="Login" />Log in</button>
<input type ="hidden" name="submitted" value="1">
</form>
</div>
</div>';
if (isset($_POST['submitted'])) {
//require_once is similar to 'include' but ensures the code is not copied multiple times
require_once('LoginFunctions.php');
$name3 = $_POST['Email'];
$pwd3 = $_POST['Password'];
echo $name3;
echo $pwd3;
//list() is a way of assigning multiple values at the same time
//checkLogin() function returns an array so list here assigns the values in the array to $check and $data
list($check, $data) = checkLogin($_POST['Email'], $_POST['Password']);
if ($check) {
setcookie('FName', $data['FName'], time() + 900); //cookie expires after 15 mins
setcookie('LName', $data['LName'], time() + 900);
//
//use session variables instead of cookies
//these variables should now be available to all pages in the application as long as the users session exists
$_SESSION['FName'] = $data['FName'];
$_SESSION['LName'] = $data['LName'];
$_SESSION['Email'] = $data['Email'];
//to enable $_SESSION array to be populated we always need to call start_session() - this is done in header.php
//print_r is will print out the contents of an array
print_r($_SESSION);
//
//Redirect to another page
$url = absolute_url('Index.php'); //function defined in Loginfunctions.php to give absolute path for required page
$_SESSION['logged'] = TRUE;
echo $_SESSION['logged'];
//this version of the header function is used to redirect to another page
echo "<script>setTimeout(\"location.href = '" . $url . "';\",10000);</script>"; //since we have entered correct login details we are now being directed to the home page
exit();
} else {
$errors = $data;
}
}
//create a sopace between the button and the error messages
//echo'<div class="spacer"></div>';
if (!empty($errors)) {
echo '<br/> <p class="error">The following errors occurred: <br />';
//foreach is a simplified version of the 'for' loop
foreach ($errors as $err) {
echo "$err <br />";
}
echo '</p>';
}
//this is the end of the <div> that contains the form
echo '</div>';
/* */
?>
</div>
<?php
include 'Footer.php';
?>
My loginFunctions.php class:
<?php
function absolute_url($page = 'Index.php')
{
//header('Location: http:\\localhost');
//exit(); //terminates the script
$url = 'http://' . $_SERVER['HTTP_HOST'] . dirname($_SERVER['PHP_SELF']);
$url = rtrim($url, '/\\');
$url .= '/' . $page;
return $url;
}
function checkLogin($Email = '', $password = '')
{
$errors = array();
if(empty($Email))
$errors[] = 'You must enter a Email';
if(empty($password))
$errors[] = 'You must enter a password';
if(empty($errors))
{
////set up database econnection
include 'DBConn.php';
$db = new DBConn();
$dbc = $db->getDBConnection();
$q = "select Email, FName, LName from Users_1 where Email = '$Email' and Password = '$password'";
$r = mysqli_query($dbc, $q);
if($r)
{
if(mysqli_affected_rows($dbc) != 0)
{
$row = mysqli_fetch_array($r, MYSQLI_ASSOC);
return array(true, $row);
}
else
{
$errors[] = 'Passwords do not match';
}
}
else{
echo '<p class="error"> Oh dear. There was a database error</p>';
echo '<p class = "error">' . mysqli_error($dbc) .'</p>';
}
}
return array(false, $errors);
}
?>
mysqli_affected_rows is used for returning rows affected by insert, update and delete operation. For select statement you must use mysqli_num_rows
if($r) {
if(mysqli_num_rows($r) != 0){
$row = mysqli_fetch_array($r, MYSQLI_ASSOC);
return array(true, $row);
}else {
$errors[] = 'Passwords do not match';
}
}
For better security: you can use password_hash() function to make your password stronger and later match the hash you saved in the field (Password- datatype would be varchar with a length of 255). You match this hash using password_verify() function which has two parameters: the string that user typed and the hash saved in the database.
For example:
echo password_hash("rasmuslerdorf", PASSWORD_DEFAULT)."\n";
will print:
$2y$10$.vGA1O9wmRjrwAVXD98HNOgsNpDczlqm3Jq7KnEd1rVAGv3Fykk1a
When a user login using rasmuslerdorf as password, you query the database and match the stored hash password $2y$10$.vGA1O9wmRjrwAVXD98HNOgsNpDczlqm3Jq7KnEd1rVAGv3Fykk1a with rasmuslerdorf using password_verify :
$q= mysqli_query($dbc, "SELECT Password FROM `Users_1`
WHERE `Email` = '$Email' and `Password` = '$password'");
$res = mysqli_fetch_assoc($q);
$hash = $res['Password'];
if (password_verify('rasmuslerdorf', $hash)) {
echo 'Password is valid!';
} else {
echo 'Invalid password.';
}
This is a fairly non-technical answer but it contains my advice based on my own experience.
When I was just learning html and had no real idea about php or javascript, I would spend hours trying to figure out how logins worked.
After a while I found out about php and javascript, and I had a friends php login script to go on.
I managed to get a database working, however the signup did not which is why I posted this question.
Eventually I got the login working, however my limited knowledge meant that I could have been storing peoples (and friends) private information such as passwords that they use elsewhere, on a website that could have had a major flaw.
Now don't get me wrong, I am not saying don't do this I am simply saying DO YOUR RESEARCH. Take time watching videos like this:
https://www.youtube.com/watch?v=8ZtInClXe1Q
How NOT to Store Passwords! - Computerphile
and then spend some more time doing database queries that don't involve passwords.
Once you have a good understanding of how to use queries and feel confident doing them, begin researching hashing methods in php.
Please take a look into:
Salting your passwords where you essentially add random
characters to the password that is being hashed so that you cant use
a hashing table to reverse a hashed password.
SQL Injection where people use the input (name field or any other field) on your form to change the syntax of your question, and essentially add code to your website. This is dangerous because then they can (depending on what permissions the user has) drop tables, drop databases, select *, and many other harmful things. This topic is also mentioned in the video mentioned before about "How NOT to Store Passwords!".
Do more research (don't only use that link it does not contain everything)...when you are storing peoples information you can never be too safe. Don't think of these tips as overkill, think of them as a responsibility to your users, that they can TRUST that nothing will happen to their password!
Good luck!

Upload process don't save the right name in database

I have a code in php with validation ok all working properly but my problem is that when I try to save in database I obtain something like this:
img_id img_small img_big
5 /tmp/phpdlYkiG /tmp/phph3dhka
I don't know why php save that name because the images have a diffent names like koala.jpg and horse.jpg
Here is my code in order to see if somebody have any suggestion...
<form enctype="multipart/form-data" action="upload_type_1.php" method="POST" >
<input type="file" name="img_small_1" id="img_small_1">
<input type="file" name="img_big_1" id="img_big_1">
<input type="submit" value="Upload" name="submit">
</form>
and this is my php code:
if ( (move_uploaded_file($_FILES["img_small_1"]["tmp_name"], $target)) && (move_uploaded_file($_FILES["img_big_1"]["tmp_name"], $target2)) ){
$img_title_1 = $_POST['img_title_1'];
$sql = "INSERT INTO press (img_title, img_small, img_big) VALUES ('$img_title_1', '$img_small_1', '$img_big_1')";
$retval = mysql_query( $sql, $conn );
if(!$retval) {
die('Could not enter data: ' . mysql_error());
}
mysql_close($conn);
echo "Your files has been uploaded";
} else {
echo "Sorry, there was an error uploading your files.";
exit;
}
This code work properly the only problem is that save into database that strange names and I need to use that names...
Thanks! - Waiting for help!
Your issue is probably not in the code that you are showing but in the code you are not showing, which is your variable declarations for $img_small_1 && $img_big_1. Taking a guess you have
$img_small_1 = $_FILES["img_small_1"]["tmp_name"];
$img_big_1 = $_FILES["img_big_1"]["tmp_name"];
but you want/need
$img_small_1 = $_FILES["img_small_1"]["name"];
$img_big_1 = $_FILES["img_big_1"]["name"];
$img_title_1 = $_POST['img_title_1'];
Should be:
$img_title_1 = $_FILES["img_small_1"]["name"]
A Simple Example of File Uploading
$uploadDir = "Your_upload_dir";
$img_small = $_FILES['img_small_1'];
$img_small_name = $img_small['name']; // get image name
$img_small_tmpName = $img_small['tmp_name'];
$img_small_fileSize = $img_small['size'];
$img_small_fileType = $img_small['type'];
if ($img_small['error'] == 0)
{
$img_small_filePath = $uploadDir . $img_small_name;
$result = move_uploaded_file($img_small_tmpName, img_small_filePath); //return true or false
}

PHP Form must be submitted twice to update checkbox

I'm still relatively new to PHP. I'm trying to build a privacy settings page for members to opt out of automatic emails for triggered events (i.e. private message notification). I want the checkbox set automatically based on the database setting. As of now, the form does update the database correctly, but the checkbox status does not show the correct setting unless the Submit button is pressed twice, or the page is reloaded. Setting would be '0' for unchecked, '1' for checked. I'd love to use Ajax or jQuery to handle this, but I don't know those at all.
privacysettings.php
<?php
$id = "";
$pm_mail_able = "";
$pm_email = "";
if (isset($_GET['id'])) {
$id = preg_replace('#[^0-9]#i', '', $_GET['id']); // filter everything but numbers
} else if (isset($_SESSION['idx'])) {
$id = $logOptions_id;
} else {
header("location: index.php");
exit();
}
//query to get checkbox status
$sql = mysql_query("SELECT * FROM members WHERE id='$id'");
while($row = mysql_fetch_array($sql)){
$pm_mail_able = $row['pm_mail_able'];
}
switch ($pm_mail_able) {
case 0:
$pm_setting = NULL;
break;
case 1:
$pm_setting = "checked=\"checked\"";
break;
}
if(isset($_GET['pm_email']) && !empty($_GET['pm_email'])) {
$updateqry = mysql_query("UPDATE members SET pm_mail_able='1' WHERE id='$id'");
} else {
$updateqry = mysql_query("UPDATE members SET pm_mail_able='0' WHERE id='$id'");
}
?>
<html>
Email Notifications<br />
<form name="testform" method="get" action="PvResult.php">
When a friend sends me a private message
<input type="checkbox" name="pm_email" value="on"<?php echo $pm_setting;?> />
<br /><br />
<input type="submit" value="Submit" />
</form>
</html>
PvResult.php
<?php
$url = 'http://www.mywebsite.com';
//If the form isn't submitted, redirect to the form
if(!isset($_GET['Submit']))
header('Location: '.$url.'/privacysettings.php');
//Redirect to the correct location based on form input
$pm_email = $_GET['pm_email'];
$url .= '/privacysettings.php?pm_email='.$pm_email;
header('Location: '.$url);
?>
Okay, hopefully this won't just answer your question, but give you a few best practices you might want to consider.
You can combine these two scripts into one relatively easily. Also, I'd highly suggest using a POST instead of GET; GET is very limited and is not intended to submit data like you're using it. If you're going to be changing data in a back-end store, using GET will bite you. Maybe not today, maybe not tomorrow, but it will, trust me.
You really should consider moving to PDO instead of the mysql_ functions. PDO is a lot better in handling parameterized queries, which you really should have here for better security, and it's more portable if someday you want to move to a different database system.
I'm still a little hazy on how your app is getting the $id. Most apps get it from a $_SESSION variable, making sure that the user has successfully validated a login. If you're not doing that, please do. You might want to thoroughly digest this article, it's got a lot of juicy best practices regarding authentication and "remember me"-type functionality.
Here's a bit of a rewrite. I haven't actually tested it, but it should give you a pretty good idea on where to go with your immediate needs. If it throws any errors (remember the disclaimer: I haven't actually tested it!), let me know and I'll try to debug it.
<?php
$message = '';
$pm_setting = '';
$id = 0;
// Put your $id retrieval logic here. It should look something like:
if (isset($_SESSION['id'])) {
$id = $_SESSION['id'];
if (!preg_match('/^\\d{1,10}$/', $id) > 0) {
// Someone is trying to hack your site.
header("location: scum.php");
exit();
}
$id = intval($id);
}
// Quick security note: You might want to read up on a topic called
// session hijacking if you want to ensure your site is secure and
// this $id isn't spoofed.
if (isset($_POST['Submit'])) {
// The form is being submitted. We don't need to read the current
// pm_mail_able setting from the database because we're going to
// overwrite it anyway.
if ($id > 0) {
$pm_mail_able = 0;
if (isset($_POST['pm_email']) && $_POST['pm_email'] === 'on') {
$pm_mail_able = 1;
$pm_setting = 'checked ';
}
$query = 'UPDATE members SET pm_mail_able='.$pm_mail_able.
' WHERE id = '.$id;
mysql_query($query);
// Another quick security note: You REALLY need to consider
// updating to PDO so that you can bind these parameters
// instead. The mysql_ functions are probably going to be
// deprecated soon anyway.
if (mysql_affected_rows($query) > 0)
$message = '<p style="color: #00a000;">Settings saved!</p>';
else
$message = '<p style="color: #a00000;">User id not valid.</p>';
}
else
$message = '<p style="color: #a00000;">User id not valid.</p>';
}
else {
// This is the first load of the form, we need to just display it
// with the existing setting.
if ($id > 0) {
$query = mysql_query('SELECT * FROM members WHERE id = '.$id);
if (($row = mysql_fetch_array($query, MYSQL_ASSOC)) !== FALSE)
if ($row['pm_mail_able'] === 1) $pm_setting = 'checked ';
}
}
?>
<html>
<body>
<?= $message ?>
<!-- Without action parameter, form submitted to this script. -->
<form name="testform" method="post">
E-mail notifications<br />
<input type="checkbox" name="pm_email" value="on" <?= $pm_setting ?>/>
When a friend sends me a private message
<br /><br />
<input type="submit" value="Submit" />
</form>
</body>
</html>
Try to do these settings and see if it will work:
1) You need to add an space between "on" and "checked=checked"
<input type="checkbox" name="pm_email" value="on" <?php echo $pm_setting;?> />
2) You have to reference the submit button by its name, not its value
<input type="submit" name="Submit" value="Send" />
3) When the setting is "0", set $pm_setting as a empty string, instead of NULL
case 0:
$pm_setting = '';
4) Maybe there is some problem with $_GET['pm_email'] and the else is always being executed
5) If the things work when you press the Submit button twice, it means that the form is passing some GET var that make the code work, so try to discover what var is this

how to avoid Form Re submission in php

I have a form in dashboard.php to create invoice and this is submitted to invoice.php
Now my invoice.php inserts the Invoice and the customer into the database and then shows me a invoice order filling form.
if i refresh this page, it inserts a new invoice for the same customer, how do i avoid this.
I was reading that we could avoid it by redirection, but in my case how do i use it. Some thing like a PRG(post/redirect/get) how to use it?
Do i need to make an intermediate page before going to insert items to invoice
The pattern you've heard about is this: Post/Redirect/Get.
In general, POST is for actions, GET is for views. So you never show a user a page on a POST request. Instead, you redirect them to a page they'll request with GET, which will not cause any changes in your database.
after successful form submission do a redirect to the same page and optionally indicate that the submission was successful
Example: invoice.php
if (count($_POST)) {
if (/*post data is valid*/) {
/*do whatever is needed*/
header('Location: invoice.php?success');
}
} else if (isset($_GET['success'])) {
echo "Form successfuly submitted";
}
Let dashboard.php post the form data to insert.php, which will process the data and then forward to invoice.php. Use sessions to transport the data from one file to another. Here is insert.php:
<?php
session_start();
if (session_is_registered("invoiceVars"))
session_unregister("invoiceVars");
if (!session_is_registered("errors"))
session_register("errors");
$errors = array();
if (!session_is_registered("formVars"))
session_register("formVars");
foreach($_POST as $f_varname => $f_value)
$formVars[$varname] = trim(EscapeShellCmd(stripslashes($value)));
// process your data and write it to the database or return to dashboard.php with errors, then:
session_unregister("errors");
session_register("invoiceVars");
$invoiceVars = array();
foreach ($formVars as $i_varname => $i_value)
$invoiceVars[$i_varname] = $i_value;
session_unregister("formVars");
// add additional variables
$invoiceVars["coupon"] = 'unique_coupon_code';
// invoice.php will process the data and display it
// it has session_start(); at the top, to have $invoiceVars available
header('Location: invoice.php');
exit();
?>
header(); and exit(); will flush $_POST, so it is no longer available when the user hits back on his browser.
Here is an example code for you:
# database.php
$db = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass);
session_start();
# dashboard.php
require_once("database.php");
function getSavedValue() {
global $db;
$sql = "SELECT input_text FROM temp_table WHERE sess_key='?'";
$query = $db->prepare($sql);
$query->bindParam(session_id());
$query->execute();
if ($query->rowCount() == 1)
return $query->fetch();
else
return " ";
}
<form action="invoice.php" method="POST">
<input type="text" name="getThisInfo" value="<?php echo getSavedValue(); ?>"/>
<input type="submit" value="Send"/>
</form>
# invoice.php
if (isset($_POST["getThisInfo"]) && /* validation check */ 1) {
require_once("database.php");
$textInput = $_POST["getThisInfo"];
$sql = "INSERT INTO perm_table(invoice_info) VALUES('?');";
$query = $db->prepare($sql);
$query->bindParam($textInput);
$query->execute();
$rows = $query->rowCount();
echo "$rows invoices were inserted.";
unset($_POST["getThisInfo"]);
header("success.php");
} else {
header("dashboard.php");
}

Categories