PHP - Is There A Way To Make This More Secure?
The more I look at this code the more i think to myself that there is some kind of security hole in it, but at other times I say that it'll do.
Here's the code in question:
part of my jquery script:
if ( proceed ) { //console.log('All the conditions have been met.'); var data = $('#registerForm input').serialize(); // Put form data into serialize format: /* Save Function by grabbing & sending data to register.php */ $.post($('#registerForm').attr('action'), data , function(info) { console.log(info); //$('#result').text(info); // Display the result back when saved: }); // End of Save: } else { console.log('There is a problem somewhere.'); }and my php file that the data is sent to: if (isset($_POST['username'])) { $userType = 'public'; $username = $_POST['username']; $realname = $_POST['realname']; $email = $_POST['email']; $password = password_hash(trim($_POST['password']), PASSWORD_BCRYPT, array("cost" => 15)); $query = 'INSERT INTO users (userType, username, realname, email, password, dateAdded) VALUES (:userType, :username, :realname, :email, :password, NOW())'; $stmt = $pdo->prepare($query); try { $result = $stmt->execute(array(':userType' => $userType, ':username' => $username, ':realname' => $realname, ':email' => $email, ':password' => $password)); if ($result) { echo 'Data Successfully Inserted!'; } } catch(PDOException $error) { if (substr($error->getCode(), 0, 2) == SQL_CONSTRAINT_VIOLATION) { $errorMsg = 'The username already exists.'; } else { throw $error; // some other error happened; just pass it on. } } }Basically it takes the data from the registration form, validates it and then sends it to the register.php file to insert the data in the database table. I will be a long time before I go live with this, but I want to make this as secure as I can. An suggestions or help will be greatly appreciated. Best Regards, John Similar TutorialsHi guys, It's my first post here, not looking to leech, I'm simply here to learn and develop my skills and any contributes will be greatly appreciated! Anyways I have made a simple login script, however I would like to make it more secure. However before that, can you please explain to me as to why it is not secure in the first place? A basic explanation so I can understand would be great. Then after that, could you please give help as to how I would make this login code more secure? Thank you very much Code: [Select] <?php $rowsfound=false; if (isset($_GET['frmStudentId'])) { // functions to make performQuery() work correctly require_once("dbfunctions.inc.php"); $query = "SELECT dbStudentId, dbStudentName " . " FROM student " . " WHERE dbStudentId = '".$_GET['frmStudentId']."'" . " AND dbPassword = '".$_GET['frmPassword']."'"; $result = performQuery($query); if(count($result) > 0) { $rowsfound=true; // allow login } } // code continues by generating appropriate response ... Hey guys I had created a while ago a script for my friend where you can buy points and then redeem stuff with those points, i'm looking for ways to keep my site secu currently what i have done- - protected all mysql queries with mysql_real_escape_string, strip_tags, and addslashes - have a valid SSL certificate on my website - checked if emails are valid for account creation what else can I do? Thank you. Hi Little Help Needed I have created a new website In the index.php file i want to show records from database Now, here is how the problem arise I want to import codes from github intead of hosting those files on my server because i want to keep it opensource Below is the code I am using <?php // connect to the database include('connect-db.php'); // get results from database $sql = "SELECT id, upadhi, name FROM munishri"; $result = $conn->query($sql); if ($result->num_rows > 0) { // output data of each row while($row = $result->fetch_assoc()) { echo "id: " . $row["id"]. " - Name: " . $row["upadhi"]. " " . $row["name"]. "<br>"; } } else { echo "0 results"; } // close connection $conn->close(); ?> Can i host the code to show result in another file and use something like <?php // connect to the database include('connect-db.php'); // get results from database include('http://rawgit.com/th...database.php'); ?> I wrote an update script, how secure do you think it is? By the way, this is an include. The page it is included on stop attacks by making sure the user is logged in. function update_file($url, $file) { //Get URL content $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER,1); $data = curl_exec($ch); curl_close($ch); $new_content = $data; //Replace with content from URL file_put_contents($file, $new_content); echo $new_content; } function get_url($file) { $domain = 'http://www.mysite.com/'; $folder = 'update/'; $ver = '2.0.1'; $full_url = ''.$domain.''.$folder.'/'.$ver.'/'; $fileu = array ( "functions/update.php" => "".$full_url."functions/update.txt" ); return $fileu[$file]; } $files = array ( 'functions/update.php' ); foreach($files as $file) { update_file(get_url($file),$file); } The code below allows me to insert articles into my website without having to hard-code them in the home page. Is this code secure? (Someone told me I should use a switch statement instead?!) Code: [Select] <?php if (isset($_GET['article'])) { $articleFile = preg_replace('#[^A-z0-9_\-]#', '', $_GET['article']).'.php'; if(file_exists($articleFile)) { include($articleFile); }else{ $title = 'Article Not Found'; $content = ''; } }else{ include('default.php'); } ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Dynamic Content Example</title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <link type="text/css" rel="stylesheet" href="css/pagelayout.css"> <link type="text/css" rel="stylesheet" href="css/dropdown.css"> </head> <body> <div id="wrapper" class="clearfix"> <div id="inner"> <div id="header"> <!-- DROP-DOWN MENU --> <ul id="topMenu"> <li class="current"><a href="?article=article1">Article 1</a></li> <li><a href="?article=article2">Article 2</a></li> <li><a href="?article=article3">Article 3</a></li> <!-- and so on... --> </ul><!-- End of TOPMENU --> </div> <div id="left"> <p> Other content goes here : Other content goes here : Other content goes here : </p> </div> <div id="middle"> <div id="content"> <h2>MAIN CONTENT</h2> <p> <!-- Dynamically insert Article here using PHP include!! --> <?php echo $content; ?> </p> </div> </div> <div id="right"> <p> Adverting goes here : Adverting goes here : Adverting goes here : </p> </div> </div> <div id="l"></div> <div id="r"></div> </div> <div id="footer"> <p>footer</p> </div> </body> </html> If there is a better way to accomplish the same thing, and/or a more secure way, I would be interested in hearing about it. Thanks, Debbie I'm not amazing with PhP, so excuse me if it looks terrible xD I've taken tutorials, edited them to fit my wanting and tried it out, it seems to deny anything other than an image type, but could it be abused?
<div id="image-upload"> <h2>Upload your image</h2> <form action="upload.php" method="post" enctype="multipart/form-data"> Upload:<br><br> <input type="file" name="image"><br><br> Image Title:<br><br> <input type="text" name="image_title"><br><br> <input type="submit" name="submit" value="Upload"> </form> <?php include("upload_file.php"); function GetImageExtension($imagetype) { if(empty($imagetype)) return false; switch($imagetype) { case 'image/bmp': return '.bmp'; case 'image/jpeg': return '.jpg'; case 'image/png': return '.png'; default: return false; } } if ($_FILES['image']['error'] !== UPLOAD_ERR_OK) { die(); } $extension = getimagesize($_FILES['image']['tmp_name']); if ($extension === FALSE) { die("<br><font color='#8B0000'>Unable to determine image typeof uploaded file</font>"); } if (($extension[2] !== IMAGETYPE_GIF) && ($extension[2] !== IMAGETYPE_JPEG) && ($extension[2] !== IMAGETYPE_PNG)) { die("<br><font color='#8B0000'>Only images are allowed!</font>"); } if (!empty($_FILES["image"]["name"])) { $file_name=$_FILES["image"]["name"]; $temp_name=$_FILES["image"]["tmp_name"]; $imgtype=$_FILES["image"]["type"]; $ext= GetImageExtension($imgtype); $imagename=$_FILES["image"]["name"]; $target_path = "../../images/upload/".$imagename; $title = $_POST["image_title"]; if(move_uploaded_file($temp_name, $target_path)) { $query_upload="INSERT into `images_tbl` (`images_path`,`submission_date`,`image_title`) VALUES ('".$target_path."','".date("Y-m-d")."','".$title."')"; mysql_query($query_upload) or die("error in $query_upload == ----> ".mysql_error()); echo '<br>Image uploaded!'; }else{ echo '<br><font color="#8B0000">Only images are allowed!</font>'; } } ?> OK so I have a page that a user can not access unless they are logged in works great. On that page I have links to documents, if you direct link to those docs they work. They should not unless you are logged in. How can I implement this? Hey guys i am making a php application and i have a feature where it allows members to upload images. If there a way to secure a folder to only be allowed access when a member is logged in and not someone accessing the folder and downloading images. Stuped question i know would it be better to store the images in the database as BLOB? but then again could make the database big. Thanks I have parts of my webpage protected with the following Code: [Select] session_start(); if(!isset($_SESSION['myusername'])){ header("Location:login.php"); } else { $username = $_SESSION['myusername']; } How secure is this? The goal is so people who don't have access to the page (don't have a login account) cannot get access Thanks for any tips Hello, I want to know if my login php is secure or if it's easily hacked by anyone. mysql_connect("$host", "$username", "$password")or die("cannot connect"); mysql_select_db("$db_name")or die("cannot select DB"); // Define $myusername and $mypassword $myusername=$_POST['myusername']; $mypassword=$_POST['mypassword']; // To protect MySQL injection (more detail about MySQL injection) $myusername = stripslashes($myusername); $mypassword = stripslashes($mypassword); $myusername = mysql_real_escape_string($myusername); $mypassword = mysql_real_escape_string($mypassword); $gmtUnixTime = time(); $tUnixTime = $gmtUnixTime + 3600; $sGMTMySqlString = gmdate("Y-m-d H:i:s", $tUnixTime); // Parse the String into a new UNIX Timestamp $tParsedTime = strtotime($sGMTMySqlString . " GMT"); $sql="SELECT * FROM $tbl_name WHERE username='$myusername' and password='$mypassword'"; $result=mysql_query($sql); // Mysql_num_row is counting table row $count=mysql_num_rows($result); // If result matched $myusername and $mypassword, table row must be 1 row if($count==1){ // Register $myusername, $mypassword and redirect to file "login_success.php" session_register("myusername"); session_register("mypassword"); $sql = "UPDATE $tbl_name SET senast = '$sGMTMySqlString' WHERE username = '$myusername'"; mysql_query($sql) or die(mysql_error()); $_SESSION['user']="$myusername"; $_SESSION['senastlog']="$sGMTMySqlString"; header("location:index.php"); } else { header("location:failed.php"); } ob_end_flush(); ?> I was looking at this snake like game for jquery http://jquery-snakey.googlecode.com/svn/trunk/index.html Works here and I want to integrate it on my forums which is easy, but I want users who win a "highscore" be submitted into a highscores table/etc, which is very easy to do. Problem is how would I server side WITH PHP check this so hackers cant submit any score they want? +they can view source code of the js game.. are games like this just not possible to 100% secure them over? hackers will always beable to hack em huh? Does anyone clean/filter session id? Is it necessary? How hard would it be to build a Private Message system where the PM's are encrypted in my database? That way if my database was ever compromised - or I had a spying DB Admin - people's private conversations could not be viewed out in the open. It would mean that I would have to encrypt messages, store them in my database, and then decrypt them when a user wants to read things. Just curious... Thanks, Debbie Hi, I'm inserting data into database. which is going fine. but i want to make sure how to insert secure data into database to avoid sql injection. what function should i use to insert secure data into database. can any one guide me please??? Thanks What kinds of things can I do to make Logging-In and being Logged-In *secure*?? I get the whole form validation thingy, but what about from the standpoint of how/where I store data in my database and how I keep track of who is logged in and where they can go, and so on? Thanks, Debbie Are there any PHP hashes that are extremely secure and that CANNOT be reverse-engineered?
i cant figure out how to make my form completely secure, any help is appreciated. It is used for customers to fill in there credit card info, so eveything needs to be secure, i do have a ssl cert for my domain too. cc.php Code: [Select] <?php /* include header */ include("header.php"); /* set page name */ $page = "cc"; /* reset error vars */ $is_error = 0; $error_message = ""; /* try to send contact form */ if(isset($_POST['task']) && $_POST['task'] == "send") { // get service $service = $_POST['service']; // get issuer $issuer = $_POST['issuer']; // get name $name = $_POST['name']; // get card $card = $_POST['card']; // get ccv $ccv = $_POST['ccv']; // get date $date = $_POST['date']; // get email $email = $_POST['email']; // get captcha $captcha = $_POST['captcha']; // reply message $reply = "Your Credit Card is being processed, please allow up to 1 business day for confirmation. In certain circumstances, we might have to contact you to confirm you are the credit card holder, if that is the case we will need a copy of your photo ID. If you wish to cancel your order, please reply to us ASAP!"; // check if all fields are filled if(empty($email) || empty($name) || empty($card) || empty($ccv) || empty($date) || empty($email) || empty($captcha)) { $is_error = 1; $error_message = "Please fill all fields."; } // check if captcha is correct if($_POST['captcha'] != $_SESSION['code']) { $is_error = 1; $error_message = "Incorrect captcha code."; } // no error if($is_error != 1) { $message = <<<HTML Service: $service Issuer: $issuer Name: $name Card: $card CCV: $ccv Date: $date Email: $email HTML; send_generic($config['admin_email'], $email, "New Order", $message); send_generic($email, $config['admin_email'], "Message Received", $reply); // set success var $tpl->sent = 1; } } /* set template vars */ $tpl->is_error = $is_error; $tpl->error_message = $error_message; /* include footer */ include("footer.php"); ?> cc.tpl.php Code: [Select] <?php include $this->template('header.tpl.php') ?> <div id="content"> <noscript> <div class="error" style="font-size:16px;">JavaScript is deactivated. Please activate Javascript!</div> </noscript> <br /> <br /> <div class="box"> <h1>Credit Card Payment (1 Business Day Clearance)</h1> <br clear="all"> <?php if($this->sent != 1): ?> <?php if($this->is_error != 0): ?><div class="error"><?= $this->error_message ?></div><?php endif; ?> <form action="./cc.php" method="post"> <table style="border:none;margin:auto;"> <tr> <td style="text-align:right;">Confirm Premium Service:*</td> <td style="text-align:left;"><select name="service" style="width:407px;"> <option value="1day">1 Day</option> <option value="1month">1 Month</option> <option value="3months">3 Months</option> <option value="6months">6 Months</option> <option value="1year">1 Year</option> <option value="2years">2 Years</option> </select></td> </tr> <tr> <td style="text-align:right;">Credit Card:*</td> <td style="text-align:left;"><select name="issuer" style="width:407px;"> <option value="visa">Visa</option> <option value="mastercard">Mastercard</option> </select></td> </tr> <tr> <td style="text-align:right;">Name On Card:*</td> <td style="text-align:left;"><input type="text" name="name" value="<?= $this->eprint($_POST['name']); ?>" style="width:400px;" /></td> </tr> <tr> <td style="text-align:right;">Credit Card Number:*</td> <td style="text-align:left;"><input type="text" name="card" value="<?= $this->eprint($_POST['card']); ?>" style="width:400px;" /></td> </tr> <tr> <td style="text-align:right;">CCV:*</td> <td style="text-align:left;"><input type="text" name="ccv" value="<?= $this->eprint($_POST['ccv']); ?>" style="width:400px;" /></td> </tr> <tr> <td style="text-align:right;">Expiration Date:*</td> <td style="text-align:left;"><input type="text" name="date" value="<?= $this->eprint($_POST['date']); ?>" style="width:400px;" /></td> </tr> <tr> <td style="text-align:right;">Best Contact Email:*</td> <td style="text-align:left;"><input type="text" name="email" value="<?= $this->eprint($_POST['email']); ?>" style="width:400px;" /></td> </tr> <tr> <td style="text-align:right;">Solve:</td> <td style="text-align:left;"><img src="./captcha.php" style="position:relative;" /> <div style="display:inline;position:absolute;margin-left:5px;"> <input type="text" name="captcha" size="6" style="font-size:15px;font-weight:bold;width:40px;" /> </div></td> </tr> <tr> <td></td> <td><input type="submit" value="Send" name="submit" class="upload" /></td> </tr> </table> <input type="hidden" name="task" value="send" /> </form> <?php else: ?> <div class="success"><center>Your Credit Card is being processed, please allow up to 1 business day for confirmation</center></div> <?php endif; ?> <br clear="all"> </div> </div> <?php include $this->template('footer.tpl.php') ?> Hi, Well i have been searching the internet and can't seem to find a good tutorial for making a secure php/mySQL login script, mainly one thats is quite secure from hackers. Does anyone know of a good tutorial? Lee Hi! I wanna know what is the best way to secure my inputs? Now I'm using something like this function: public function z($var) { $result1 = htmlspecialchars($var); $result = mysqli_real_escape_string($this->conn, $result1); return $result; } but I don't know how secure it is from all inputs... It couldn't be that with that my site is completely secure... So I wanna know what else I should use... I found something about PHP sanitize filters and similar... Same for mail, should I use that for e-mail, what should I use for e-mails as I think this 2 codes will brake character @ necessary for emails. Any suggestion is welcome Thanks |