PHP - Need Help Creating Secure Php,
Hey, Some of you may have noticed me posting this morning about needing help creating a comment system and securing down my PHP,
I have been hard at work and have nearly finished my comment system all I need to do now is the post form and insert script, and I have been looking into the various suggestions for securing my PHP from Injection attacks and the likes. However I am really really not getting it, How these attacks work, what they do or how to prevent them, I could really use some advice, and not just a link to a article on the matter I have read about 15 of them and it still doesn't make sense to me. Can anyone give me some advice or an explanation. If someone could secure this page here for me the I should be able to work out the rest. If you need my config.php file just shout. Code: [Select] <?php include("config/config.php"); $data = mysql_query("SELECT * FROM blog WHERE articleid = {$_GET['articleid']} ORDER by date ASC") or die(mysql_error()); while($row = mysql_fetch_array($data)) { echo "<table class='main'> <tr> <td> <a href='/news.php?articleid=" . $row['articleid'] . "' class='article_title'>" . $row['title'] . "</a> <p>" . $row['introduction'] . "</p></td><tr><td ALIGN='RIGHT' class='small'> Posted by:" . $row['author'] . ", on " . $row['date'] . ",</td></tr></table>"; } ?> COMMENTS: <? $data = mysql_query("SELECT * FROM comments WHERE articleid = {$_GET['articleid']} ORDER by date ASC") or die(mysql_error()); while($row = mysql_fetch_array($data)) { echo "<table class='main'><tr><td> <p>" . $row['comment'] . "</p></td><tr><td ALIGN='RIGHT' class='small'> Posted by:" . $row['author'] . ", on " . $row['date'] . ",</td></tr></table>"; } ?> Thanks Blaze Similar TutorialsHow 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 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 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? 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); } 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>'; } } ?> 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 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 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(); ?> 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 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 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? 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 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 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') ?> Are there any PHP hashes that are extremely secure and that CANNOT be reverse-engineered?
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 I'm connecting to my database using the following... @ $db = new mysqli('host', 'username', 'password', 'database') The .php file that is connecting to the database is in my root (htdocs) folder on the server. I know that I am not supposed to put my actual 'host', 'username', 'password', 'database' inside the mysqli function for security purposes. I know that I am supposed to put variables in instead. But here is where I am confused. Where do I set those variables? Do I set them in another file and include that file? If so, where do I store the file that holds the passwords, and what prevents a hacker from simply navigating to that file? Thanks for the help Hi friends I have a form with mysqli comnnection <label for="fullname">Fullname</label> <input type="text" name="fullname" /> <label for="photo">Upload photo</label> <input name="photo" type="file"/> and on the php ends I have $fullname = $_POST['fullname']; $uploaddir = './uploads/'; //upload file in folder $uploadfile = $uploaddir. basename($_FILES['photo']['name']); //insert filename in db $upload_filename = basename($_FILES['photo']['name']); move_uploaded_file($_FILES['photo']['tmp_name'], $uploadfile); $photo = $upload_filename; $sql = "INSERT INTO members(fullname,photo) VALUES('$fullname', '$photo'); $stmt = $link->query($sql) or die($link->error); $stmt->close; Please help me, I am using this on a live site |