function add($user_id, $object_type = NULL, $object_id = NULL, $action, $params = NULL) { // Add a new entry to the log global $mysqli; $user_id = sanitize_input($user_id); $object_type = sanitize_input($object_type); $object_id = sanitize_input($object_id); $action = sanitize_input($action); $params = sanitize_input($params); $sql = "INSERT INTO log SET user_id = {$user_id}, object_type = {$object_type}, object_id = {$object_id}, action = {$action}, params = {$params}"; $query = mysqli_query($mysqli, $sql); }
function check_form($form_name) { // get form $form = $GLOBALS[$form_name . "_form"]; // check for presence of input $sanitized_input = sanitize_input($form); // put input to the right format for treatment $formatted_input = format_input_forward($sanitized_input, $form); // save input in case of error $_SESSION[$form_name . "_form"] = $formatted_input; // validate input correctness; redirects if not valid validate_formatted_input($formatted_input, $form); // unset now useless session variable unset($_SESSION[$form_name . "_form"]); // replace $_POST variable with input nicely structured $_POST = structured_input($formatted_input, $form); }
public static function list_all($limit = 10, $offset = 0) { global $mysqli; $config = new Config(); $sql = "SELECT `id` FROM `{$config->database->{$config->site_identifier}->prefix}likes` ORDER BY `date` DESC"; // Limit string $limit = sanitize_input($limit); $sql .= " LIMIT {$limit}"; // Offset string $offset = sanitize_input($offset); $sql .= " OFFSET {$offset}"; // Get likes $query = mysqli_query($mysqli, $sql); // Loop through likes, fetching objects $likes = array(); while ($query && ($result = mysqli_fetch_assoc($query))) { $likes[] = Like::get_by_id($result['id']); } return $likes; }
function database_user_login($username, $password) { global $mysqli; $username = sanitize_input($username); $password = sanitize_input($password); $userID = database_get_userID($username); $q = "SELECT password FROM users WHERE userID='{$userID}'"; $result = mysqli_query($mysqli, $q); $row = mysqli_fetch_array($result); $datapass = $row['password']; // If the database password and the passed in password are the same // the user is verified. Otherwise, return 0. if (validate_password($password, $datapass)) { set_user_logged_in($userID); } else { set_user_logged_out(); $userID = 0; } return $userID; }
function database_get_user_posts($userID) { global $mysqli; $userID = sanitize_input($userID); $posts = ""; $q = "SELECT message,timestamp FROM posts WHERE userID='{$userID}' ORDER BY timestamp DESC"; $result = mysqli_query($mysqli, $q); while ($row = mysqli_fetch_array($result)) { $message = stripslashes($row['message']); $timestamp = "<b>" . $row['timestamp'] . "</b>"; $posts = $posts . $timestamp . ":<br>" . $message . "<br /><br />"; } return $posts; }
$comment = ""; if (isset($_GET['performanceId'])) { $performanceId = intval($_GET['performanceId']); } if (isset($_GET['artistId'])) { $artistId = intval($_GET['artistId']); } if ($_GET['action'] == "editcomment" && isset($_GET['commentId'])) { $commentId = intval($_GET['commentId']); $details = get_comment_by_id($commentId); $comment = $details['comment']; $performanceId = $details['performanceId'] == null ? -1 : $details['performanceId']; $artistId = $details['artistId'] == null ? -1 : $details['artistId']; } if ($_SERVER['REQUEST_METHOD'] === 'POST') { $comment = sanitize_input($_POST['comment']); $performanceId = intval($_POST['performanceId']); $artistId = intval($_POST['artistId']); if (isset($_POST['commentId'])) { $commentId = intval($_POST['commentId']); } $has_error = false; if (!$has_error) { // Successful $postDate = date("Y-m-d"); if ($artistId != -1) { $redirect_page = "artists.php?action=details&id=" . $artistId; } else { if ($performanceId != -1) { $redirect_page = "performance.php?action=details&id=" . $performanceId; } else {
function checkPostResult() { global $REPDATA; $REPDATA = new_repdata(); $REPDATA["id"] = sanitize_input($_POST["reportid"]); $REPDATA["date"] = sanitize_input($_POST["date"]); $REPDATA["time"] = sanitize_input($_POST["time"]); $REPDATA["sightingType"] = isset($_POST["type"]) ? sanitize_input($_POST["type"]) : null; $REPDATA["comments"] = sanitize_input($_POST["comments"]); $REPDATA["email"] = sanitize_input($_POST["email"]); $REPDATA["latitude"] = sanitize_input($_POST["latitude"]); $REPDATA["longitude"] = sanitize_input($_POST["longitude"]); $errors = array(); if (empty($REPDATA["time"])) { $errors["time"] = "Time is a required field"; } if (empty($REPDATA["sightingType"])) { $errors["type"] = "Please select 'sighting' or 'encounter'"; } //if (empty($REPDATA["email"])) $errors["email"] = "Please provide your email"; $REPDATA["errors"] = $errors; db_checkOrphan(); // this may change $REPDATA["id"] return count($errors) == 0; }
$joinDate_error = ""; $leaveDate = ""; $leaveDate_error = ""; $name = ""; $name_error = ""; if ($_GET['action'] == "editmember" && isset($_GET['memberId'])) { $memberId = intval($_GET['memberId']); $details = get_member_details($memberId); $joinDate = $details['joinDate']; $leaveDate = $details['leaveDate']; $name = $details['name']; } if ($_SERVER['REQUEST_METHOD'] === 'POST') { $joinDate = sanitize_input($_POST['joinDate']); $leaveDate = sanitize_input($_POST['leaveDate']); $name = sanitize_input($_POST['name']); $artistId = intval($_POST['artistId']); if (isset($_POST['memberId'])) { $memberId = intval($_POST['memberId']); } $has_error = false; if (!$has_error) { // Successful if ($memberId == -1) { $ret = add_member_to_artist($artistId, $joinDate, $leaveDate, $name); } else { $ret = update_member($memberId, $artistId, $joinDate, $leaveDate, $name); } if (!$has_error) { header('Location: artists.php?action=details&id=' . $artistId, true); die;
$duration = ""; $duration_error = ""; $track_number = ""; $track_number_error = ""; if ($_GET['action'] == "editsong" && isset($_GET['songId'])) { $songId = intval($_GET['songId']); $details = get_song($songId, $albumId); $title = $details['title']; $duration = $details['duration']; $track_number = $details['track_number']; $artistId = $details['artistId']; } $origArtistId = $artistId; if ($_SERVER['REQUEST_METHOD'] === 'POST') { $artistId = intval($_POST['artistid']); $title = sanitize_input($_POST['title']); $duration = doubleval($_POST['duration']); $track_number = intval($_POST['track_number']); $albumId = intval($_POST['albumId']); if (isset($_POST['songId'])) { $songId = intval($_POST['songId']); } $has_error = false; if (empty($title)) { $title_error = "Title cannot be empty"; $has_error = true; } if (empty($duration)) { $duration_error = "Duration cannot be empty"; $has_error = true; }
public static function update_item($id, $title = NULL, $byline = NULL, $content = NULL, $status = 1) { global $mysqli; $config = new Config(); $id = sanitize_input($id); $update_string = ''; if ($title != NULL) { $title = sanitize_input($title); $update_string .= "title = {$title}, "; } if ($content != NULL) { $content = sanitize_input($content); $update_string .= "content = {$content}, "; } $status = sanitize_input($status); $update_string .= "status = {$status}"; $sql = "UPDATE `{$config->database->{$config->site_identifier}->prefix}items` SET {$update_string} WHERE id = {$id}"; $query = mysqli_query($mysqli, $sql); }
requires mySQL access --> <?php session_start(); // We'll keep some variables across pages include_once 'header.php'; // header info (CSS, etc) is consistent. This will make updating style easier. I think. include_once 'GetPoints.php'; // Functions used to collect points information ?> <body> <div id="container"> <h1> Chapin Hall Points - View Points </h1> <?php $netid = strtolower(sanitize_input($_POST['netid'])); $name = GetName($netid); // This returns 'INVALID_NETID' if it fails to find a single record if ($name != 'INVALID_NETID') { $currentmonth = date('n'); // n is format symbol for numerical month, no leading zeros $currentyear = date('Y'); // Y is format symbol for numerical year, 4 digits // if it's July or later, we can assume it's fall quarter, and the year is correct. // If it's earlier than that, it's winter or spring, and the current year is not // the same as the school year as held by the database (That is defined as the year of fall quarter) // (See 'AdminSetDates.php for clarification if this doesn't make sense) if ($currentmonth <= 7) { $currentyear--; // the year of fall quarter was the numerical year before 'now' }
public static function check_password_reset_code($code) { global $mysqli; $config = new Config(); $code = sanitize_input($code); $sql = "SELECT `user_id` AS id FROM `{$config->database->{$config->site_identifier}->prefix}users_password_reset` WHERE `reset_code` = {$code} AND `date` > DATE_SUB(NOW(), INTERVAL 1 DAY) ORDER BY `date` DESC"; $query = mysqli_query($mysqli, $sql); $user = mysqli_fetch_assoc($query); return isset($user['id']) ? $user['id'] : FALSE; }
$email = $profile['email']; $firstname = $profile['firstName']; $lastname = $profile['lastName']; $age = $profile['age']; $zipcode = $profile['zipcode']; } if ($_SERVER['REQUEST_METHOD'] === 'POST') { if (isset($_GET['action']) && $_GET['action'] == "update" && isset($_GET['id'])) { $username = $_SESSION['username']; } else { $username = sanitize_input($_POST['username']); } $email = sanitize_input($_POST['email']); $password = sanitize_input($_POST['password']); $firstname = sanitize_input($_POST['firstname']); $lastname = sanitize_input($_POST['lastname']); $age = intval($_POST['age']); $zipcode = intval($_POST['zipcode']); $has_error = false; if (empty($username)) { $username_error = "Username cannot be empty"; $has_error = true; } if (empty($email)) { $email_error = "Email cannot be empty"; $has_error = true; } if (empty($password)) { $password_error = "Password cannot be empty"; $has_error = true; }
$res = cat(sanitize_input($_GET['file'])); } break; case 'head': if (isset($_GET['file'])) { isset($_GET['lines']) and $lines = sanitize_input($_GET['lines']) or $lines = 10; $res = catN(sanitize_input($_GET['file']), $lines); } break; case 'file': if (isset($_GET['file'])) { $res = fileinfo(sanitize_input($_GET['file'])); } break; case 'info': if (isset($_GET['dir'])) { $res = showinfo(sanitize_input($_GET['dir'])); } else { $res = showinfo('.'); } break; /*case 'grep': if (isset($_GET['dir']) and isset($_GET['expr'])) { $res = grep($_GET['dir'],$_GET['expr']); } break;*/ } $res[1] = sanitize_output($res[1]); //debug: error_log(implode(" ",$res)); echo json_encode($res); }
public static function check_code_valid($code, $email) { global $mysqli; $config = new Config(); if ($code == '') { return false; } $code = sanitize_input($code); $email = sanitize_input($email); $sql = "SELECT `result` FROM `{$config->database->{$config->site_identifier}->prefix}invites` WHERE `code` = {$code} AND `email` = {$email}"; $query = mysqli_query($mysqli, $sql); $status = mysqli_num_rows($query); if ($status > 0) { return true; } else { return false; } }
// collect all the variables submitted. This requires some work. $name = $_SESSION['name']; // from P1 $netid = $_SESSION['netid']; // from P1 $category = $_SESSION['category']; // from P1 $event = sanitize_input($_POST['event']); $date = sanitize_input($_POST['date']); if (!empty($_POST['info'])) { $info = sanitize_input($_POST['info']); } else { $info = ""; } if (!empty($_POST['points'])) { $points = sanitize_input($_POST['points']); } else { $points = 0; //meaningless default value } // Assign points. This switch mirrors the one on page two nicely. You may ask why I chose to assign // events a cryptic code there only to translate the code back to English here, to which I have // no solid explanation, but a well-trained programming intuition that this is far harder to screw // up when updating the points system. I could, however, be completely wrong. // // note how the English goes to the database; the code stays behind in the PHP // points assumed unrestricted unless otherwise proven guilty. This is 'MURICA! $restricted = FALSE; switch ($event) { // Academic Events case 'ac1':
function _getAdvancedSearchSQLStatement(&$words) { $join = ""; $multiple_join = 0; $has_OR = false; $criteria = "WHERE "; foreach ($_POST as $k => $v) { $v = sanitize_input($v); if ($v == "") { continue; // Skip, if the input string is empty } // Get values from dynamic INPUT fields if (preg_match("/^keyword_type_(\\d+)\$/", $k, $matchs)) { $number = $matchs[1]; $v_col = $v; $k_txt = "keyword_text_" . $number; $v_txt = sanitize_input($_POST[$k_txt]); if ($v_txt == "") { continue; // Skip when the input string is empty } // Prepare an expression for the criteria // do nothing if an input is the first one $v_exp = ""; if (strcmp($criteria, "WHERE ") > 0) { $k_exp = "expression_" . $number; $v_exp = $_POST[$k_exp]; // Special variable is used to apply 'HAVING' clause if (strcmp($v_exp, "or") == 0) { $has_OR = true; } // Insert 'NOT' into the query string in next steps. if (strcmp($v_exp, "not") == 0) { $v_exp = " AND "; $tmp_v_exp = "not"; } } else { // The first one with an expression $k_exp = "expression_" . $number; $v_exp = $_POST[$k_exp]; } if (strcmp($v_exp, "") > 0) { $criteria .= strtoupper($v_exp) . " "; } // Make a query string. if (strcmp($v_col, "title") == 0) { if (strcmp($tmp_v_exp, "not") == 0) { $criteria .= "NOT biblio.title LIKE '%" . $v_txt . "%' "; } else { $criteria .= "biblio.title LIKE '%" . $v_txt . "%' "; } } elseif (strcmp($v_col, "author") == 0) { if (empty($join)) { $join .= "LEFT JOIN biblio_field ON biblio_field.bibid=biblio.bibid "; } if (strcmp($tmp_v_exp, "not") == 0) { $str = "NOT biblio.author LIKE '%" . $v_txt . "%' OR " . "NOT biblio.responsibility_stmt LIKE '%" . $v_txt . "%' OR " . "NOT " . " biblio_field.tag='700' AND " . " (biblio_field.subfield_cd='a' OR biblio_field.subfield_cd='b') AND " . " biblio_field.field_data LIKE '%" . $v_txt . "%'"; } else { $str = "biblio.author LIKE '%" . $v_txt . "%' OR " . "biblio.responsibility_stmt LIKE '%" . $v_txt . "%' OR " . "(biblio_field.tag='700' AND " . " (biblio_field.subfield_cd='a' OR biblio_field.subfield_cd='b') AND " . " biblio_field.field_data LIKE '%" . $v_txt . "%')"; } $criteria .= "(" . $str . ") "; // Special variable is used to apply 'HAVING' clause $multiple_join++; } elseif (strcmp($v_col, "subject") == 0) { if (strcmp($tmp_v_exp, "not") == 0) { $str = "NOT biblio.topic1 LIKE '%" . $v_txt . "%' OR " . "NOT biblio.topic2 LIKE '%" . $v_txt . "%' OR " . "NOT biblio.topic3 LIKE '%" . $v_txt . "%' OR " . "NOT biblio.topic4 LIKE '%" . $v_txt . "%' OR " . "NOT biblio.topic5 LIKE '%" . $v_txt . "%'"; } else { $str = "biblio.topic1 LIKE '%" . $v_txt . "%' OR " . "biblio.topic2 LIKE '%" . $v_txt . "%' OR " . "biblio.topic3 LIKE '%" . $v_txt . "%' OR " . "biblio.topic4 LIKE '%" . $v_txt . "%' OR " . "biblio.topic5 LIKE '%" . $v_txt . "%'"; } $criteria .= "(" . $str . ") "; } elseif (strcmp($v_col, "isbn") == 0) { if (empty($join)) { $join .= "LEFT JOIN biblio_field ON biblio_field.bibid=biblio.bibid "; } if (strcmp($tmp_v_exp, "not") == 0) { $str = "NOT " . " biblio_field.tag='20' AND " . " biblio_field.subfield_cd='a' AND " . " biblio_field.field_data LIKE '%" . $v_txt . "%'"; } else { $str = "biblio_field.tag='20' AND " . "biblio_field.subfield_cd='a' AND " . "biblio_field.field_data LIKE '%" . $v_txt . "%'"; } $criteria .= "(" . $str . ") "; // Special variable is used to apply 'HAVING' clause $multiple_join++; // } elseif (strcmp($v_col, "language") == 0) { #fix aumetar para varios cmapos marc JALG 3-2015 if (empty($join)) { $join .= "LEFT JOIN biblio_field ON biblio_field.bibid=biblio.bibid "; } if (strcmp($tmp_v_exp, "not") == 0) { $str = "NOT " . " biblio_field.tag='41' AND " . " biblio_field.subfield_cd='a' AND " . " biblio_field.field_data LIKE '%" . $v_txt . "%'"; } else { #fix revisar si este if es necesario para el idioma $str = "biblio_field.tag='41' AND " . "biblio_field.subfield_cd='a' AND " . "biblio_field.field_data LIKE '%" . $v_txt . "%'"; } $criteria .= "(" . $str . ") "; // Special variable is used to apply 'HAVING' clause $multiple_join++; } elseif (strcmp($v_col, "call_nmbr") == 0) { if (strcmp($tmp_v_exp, "not") == 0) { $str = "NOT biblio.call_nmbr1 LIKE '%" . $v_txt . "%' OR " . "NOT biblio.call_nmbr2 LIKE '%" . $v_txt . "%' OR " . "NOT biblio.call_nmbr3 LIKE '%" . $v_txt . "%'"; } else { $str = "biblio.call_nmbr1 LIKE '%" . $v_txt . "%' OR " . "biblio.call_nmbr2 LIKE '%" . $v_txt . "%' OR " . "biblio.call_nmbr3 LIKE '%" . $v_txt . "%'"; } $criteria .= "(" . $str . ") "; } } elseif (preg_match("/^language\$/", $k)) { if (empty($join)) { $join .= "LEFT JOIN biblio_field ON biblio_field.bibid=biblio.bibid "; } if (strcmp($criteria, "WHERE ") > 0) { if ($multiple_join > 0) { $criteria .= "OR "; $has_OR = true; } else { $criteria .= "AND "; } } $criteria .= "(biblio_field.tag='041' " . "AND biblio_field.subfield_cd='a' " . "AND biblio_field.field_data='" . $v . "') "; // Special variable is used to apply 'HAVING' clause $multiple_join++; } elseif (preg_match("/^publishedYear\$/", $k)) { if (empty($join)) { $join .= "LEFT JOIN biblio_field ON biblio_field.bibid=biblio.bibid "; } if (strcmp($criteria, "WHERE ") > 0) { if ($multiple_join > 0) { $criteria .= "OR "; $has_OR = true; } else { $criteria .= "AND "; } } $criteria .= "(biblio_field.tag='260' " . "AND biblio_field.subfield_cd='c' " . "AND biblio_field.field_data='" . $v . "') "; // Special variable is used to apply 'HAVING' clause $multiple_join++; } elseif (preg_match("/^materialCd\$/", $k)) { if (strcmp($criteria, "WHERE ") > 0) { $criteria .= "AND "; } $criteria .= "biblio.material_cd='" . $v . "' "; } elseif (preg_match("/^collectionCd\$/", $k)) { if (strcmp($criteria, "WHERE ") > 0) { $criteria .= "AND "; } $criteria .= "biblio.collection_cd='" . $v . "' "; } } // No criteria pass through if (strcmp($criteria, "WHERE ") == 0) { $criteria = "WHERE 1 "; } // Intersect the result if ($multiple_join > 1 && $has_OR) { $criteria .= " GROUP BY biblio.bibid HAVING COUNT(biblio.bibid) > 1 "; } // Remove redundant whitespace $criteria = preg_replace("/[[:space:]]+/i", " ", $criteria); return array("join" => $join, "criteria" => $criteria); }
<?php //session_start(); // Not sure if I'll be using this for this part of the page or not. Left commented until needed include_once '../header.php'; // header info (CSS, etc) is consistent. This will make updating style easier. I think. include_once '../GetPoints.php'; // Functions used to collect points information ?> <body> <div id="container"> <h1> Chapin Hall Points - Points Summary </h1> <a href="http://chapin-points.net16.net/admin/AdminPage1.php"> Return to Admin Home Page</a><br /> <br /> <?php // get our year, with a little rudimentary stupid error catching $raw_year = sanitize_input($_POST['year']); $raw_year = round($raw_year); $currentyear = $raw_year; // output the year $nextyear = $currentyear + 1; echo "Record for {$currentyear}-{$nextyear} <br />"; // Fire up our trusty mySQL connection function $connection = connect_to_mySQL(); // defined in header.php // First, get a list of all netid $sql = "SELECT DISTINCT netid FROM Raw_Submissions;"; // Run the query $result = mysql_query($sql) or die(mysql_error()); if (mysql_num_rows($result) > 0) { // clear out the old points_summary table. We're rewriting it from scratch $sql = "DELETE FROM Points_Summary;";
function validate_type($variable, $allowed_list, $greedy = false) { $results = false; $allowed_list = explode(':', $allowed_list); $count = count($allowed_list); foreach ($allowed_list as $variable_type) { if ($variable_type == 'password') { $variable_type = 'string'; } $callable_function = 'is_' . sanitize_input($variable_type); if (function_exists($callable_function)) { if (call_user_func($callable_function, $variable) || $results == true) { $results = true; $count -= 1; } } if ($greedy) { if ($count != 0) { $results = false; } } } return $results; }
return $callback . "(" . $jsondata . ");"; } else { header('Content-Type: application/json; charset=utf-8'); return $jsondata; } } else { // invalid username or media header("HTTP/1.0 400 BAD REQUEST"); header('Content-Type: text/html; charset=utf-8'); die("invalid {$requestType}"); } } /***** Get user's input *****/ $user = sanitize_input($_GET['user']); // expects something like "instagram" (username) $media = sanitize_input($_GET['media']); // expects something like "mOFsFhAp4f" (shortcode) /***** set context *****/ $context = stream_context_create(array('http' => array('timeout' => 10))); /***** validate request type and return response *****/ // user, including last 20 media posts if (!empty($user) && empty($media)) { $requestType = "user"; $dataFile = @file_get_contents("http://instagram.com/" . $user, NULL, $context); echo process_data($dataFile, $requestType); } elseif (empty($user) && !empty($media)) { $requestType = "media"; $dataFile = @file_get_contents("http://instagram.com/p/" . $media, NULL, $context); echo process_data($dataFile, $requestType); } elseif (!empty($user) && !empty($media)) { header("HTTP/1.0 400 BAD REQUEST");
# You should have received a copy of the GNU General Public License # along with this program or from the site that you downloaded it # from; if not, write to the Free Software Foundation, Inc., 59 Temple # Place, Suite 330, Boston, MA 02111-1307 USA # # First thing first: it's a modern script supposed to be used on # decent browsers. header('Content-type: text/html; charset=utf8'); # Start a new session or open an existing one session_start(); $CONFIGFILE = dirname(__FILE__) . '/config.php'; # Load the common stuff include_once './lib/commonfunctions.php'; require_once './lib/password.php'; # Pre-sanitize all inputs $SANITIZED_POST = sanitize_input($_POST); # Launch the setup script if the config file is not found if (!file_exists($CONFIGFILE)) { require './lib/setup.php'; } else { # Load configuration options require_once $CONFIGFILE; try { $dbh = new PDO("mysql:host=" . $CONFIG['dbhostname'] . ";dbname=" . $CONFIG['mydb'] . ";charset=UTF8", $CONFIG['dbuser'], $CONFIG['dbpass']); $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); if (isset($SANITIZED_POST['newmember'])) { require './lib/newmember.php'; } else { if (isset($_SESSION['MemberID'])) { printf("Logged in as user '%s'<br />\n", $_SESSION['hsbuser']);
echo 'is_ready(" "): ' . (is_ready(" ") ? 'true' : 'false') . '<br/>'; echo '<br/>Passed<br/><hr/>'; /* function sanitize_input($string_input) * takes in the user input, returns the trimmed and escaped user input. * @$string_input will process strings or an array of strings * original value of the variable will be returned if it is unable to trim or/and escape the input. */ echo 'Signature: sanitize_input($string_input)<br/>'; echo '//removes all trailing spaces for individual input and array input<br/><br/>'; echo 'sanitize_input("x"): "' . sanitize_input('x') . '"<br/>'; echo 'sanitize_input("x "): "' . sanitize_input('x ') . '"<br/>'; echo 'sanitize_input(array()):'; print_r(sanitize_input(array())); echo '<br/>'; echo 'sanitize_input(array("sample one", "sample two ", "three ")): --result:'; print_r(sanitize_input(array("sample one", "sample two ", "three "))); echo '<br/>'; echo '<br/>Passed<br/><hr/>'; /* checks if the variable is unset, null or empty and assign the default value * if the variable is unset, null or empty (if string), the default value will be set to the variable. * $variable will not be able to take in a value for eg. is_ready('abc');, a variable has to be used, eg. $x; is_ready($x); */ echo 'Signature: set_default(&$variable, $default)<br/>'; echo '//sets a default if variable is not ready. variable must be passed. value is return and assigned.<br/><br/>'; $default_value = 'defaultvalue'; $normal_item = 'x'; $null_item = null; $empty_item = ''; $single_space = ' '; echo 'set_default($normal_item, "default"): ' . set_default($normal_item, 'default') . '<br/>'; echo 'set_default($null_item, "default"): ' . set_default($null_item, 'default') . '<br/>';
/** * Function: sanitize_input * Makes sure no inherently broken ideas such as magic_quotes break our application * * Parameters: * $data - The array to be sanitized, usually one of @$_GET@, @$_POST@, @$_COOKIE@, or @$_REQUEST@ */ function sanitize_input(&$data) { foreach ($data as &$value) { if (is_array($value)) { sanitize_input($value); } else { $value = get_magic_quotes_gpc() ? stripslashes($value) : $value; } } }
sanitize_input($_POST['user']); sanitize_input($_POST['source']); sanitize_input($_POST['target']); sanitize_input($_POST['text']); if (!$_POST['text']) { exit; } if (!isset($_SESSION[$session]['user'])) { $_SESSION[$session]['user'] = $_POST['user'] ? $_POST['user'] : '******' . time(); } $_SESSION[$session]['source'] = $_POST['source']; $_SESSION[$session]['target'] = $_POST['target']; $lang = $_POST['source'] && $_POST['target'] ? $_POST['source'] . '-' . $_POST['target'] : $_POST['target']; $text = $_POST['text']; if ($lang) { $args = ['key' => KEY, 'lang' => $lang, 'text' => sanitize_input($_POST['text'])]; $query = '?' . http_build_query($args); $result = json_decode(file_get_contents('https://translate.yandex.net/api/v1.5/tr.json/translate' . $query)); $code = $result->code; if ($code > 200) { print $code; exit; } $text = trim(current($result->text)); //$lang = explode('-', $result->lang); //$_SESSION[$session]['source'] = $lang[0]; //$_SESSION[$session]['target'] = $lang[1]; } if (!$_SESSION[$session]['target']) { $_SESSION[$session]['target'] = $_SESSION[$session]['source']; }
} if (empty($_POST["subject"])) { $subjectErr = "*"; $error = true; } else { $subject = sanitize_input($_POST["subject"]); if (!preg_match("/^[a-zA-Z0-9 ]*\$/", $subject)) { $subjectErr = "Only letters, numbers and white space allowed"; $error = true; } } if (empty($_POST["message"])) { $messageErr = "Please enter a message!"; $error = true; } else { $message = sanitize_input($_POST["message"]); } // use wordwrap() if lines are longer than 70 characters $timestamp = date("h:i:sa l, Y/m/d"); $msg = "Name: " . $name1 . "\nEmail: " . $email1 . "\nTime: " . $timestamp . "\n\n" . wordwrap($message, 70); $sbj = "website contact form - " . $subject; // send the email $sent = mail("*****@*****.**", $sbj, $msg); // notify the user of success of fail if ($sent) { $confirm1 = "Message sent"; } else { $confirm1 = "Message failed to send"; } } }
$duration_error = ""; $date = ""; $date_error = ""; if ($_GET['action'] == "editperformance" && isset($_GET['performanceId'])) { $performanceId = intval($_GET['performanceId']); $details = get_performance_details($performanceId); $title = $details['title']; $venueId = $details['venueId']; $duration = $details['duration']; $date = $details['date']; } if ($_SERVER['REQUEST_METHOD'] === 'POST') { $title = sanitize_input($_POST['title']); $venueId = intval($_POST['venueId']); $duration = doubleval($_POST['duration']); $date = sanitize_input($_POST['date']); if (isset($_POST['performanceId'])) { $performanceId = intval($_POST['performanceId']); } $has_error = false; if (!$has_error) { // Successful if ($performanceId == -1) { $performanceId = add_performance($duration, $venueId, $date, $title); } else { $ret = update_performance($performanceId, $title, $duration, $venueId, $date); } if (!$has_error) { header('Location: performance.php?action=details&id=' . $performanceId, true); die; }
<?php session_start(); include_once 'class.phpmail.php'; $pm_app_form_name = sanitize_input($_POST['pm_app_form_name']); $pm_app_form_email = sanitize_input($_POST['pm_app_form_email']); $pm_app_form_phone = sanitize_input($_POST['pm_app_form_phone']); $pm_app_form_date = $_POST['pm_app_form_date']; $pm_app_form_time = sanitize_input($_POST['pm_app_form_time']); $pm_app_form_recipient = sanitize_input($_POST['pm_app_form_recipient']); if (empty($pm_app_form_name)) { header('Content-type: application/json'); echo json_encode(array('status' => 'name_error')); exit; } elseif (validate_email($pm_app_form_email) == false) { header('Content-type: application/json'); echo json_encode(array('status' => 'email_error')); exit; } elseif (empty($pm_app_form_phone)) { header('Content-type: application/json'); echo json_encode(array('status' => 'phone_error')); exit; } elseif (empty($pm_app_form_date)) { header('Content-type: application/json'); echo json_encode(array('status' => 'date_error')); exit; } elseif (empty($pm_app_form_time)) { //print 'Please provide a short message for your inquiry.'; //exit; header('Content-type: application/json'); echo json_encode(array('status' => 'time_error'));
<?php /* Include helper validation functions */ include 'helpers.php'; /* Define global field array for use in custom error messages */ $labels = array('principal' => 'PrincipalAmount', 'interest' => 'InterestRate', 'depositDuration' => 'DepositDuration', 'name' => 'Name', 'phone' => 'Phone', 'email' => 'Email', 'contactMethod' => 'PreferredContact', 'contactTime' => 'ContactTime'); /* Define validation rule messages */ $rules = array('empty' => ' field cannot be left blank', 'numeric_above_zero' => ' entered has to be numeric and greater than zero', 'numeric_not_negative' => ' entered has to be numeric and not negative', 'valid_phone' => ' has to be in the format of NNN-NNN-NNNN', 'valid_email' => ' has to be in valid email format', 'valid_contact_time' => ' is your preferred contact method, you must select a preferred time'); /* Set initial error status */ $error_flag = false; /* Iterate through POST variables assign key/value */ foreach ($_POST as $key => $value) { // Only sanitize the text fields if ($key !== 'PreferredContact' && $key !== 'ContactTime') { $value = sanitize_input($value); // Check for invalid fields if (!is_valid($value) || !is_num_above_zero($_POST[$labels['principal']]) || !is_num_not_negative($_POST[$labels['interest']]) || !is_valid_phone($_POST[$labels['phone']]) || !is_valid_email($_POST[$labels['email']]) || !isset($_POST[$labels['contactTime']])) { $error_flag = true; } } } ?> <!DOCTYPE html> <html> <head> <title>Deposit Calculator</title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="description" content="" />
require_once INCLUDES_DIR . "/lib/PasswordHash.php"; require_once INCLUDES_DIR . "/class/Config.php"; require_once INCLUDES_DIR . "/class/SQL.php"; require_once INCLUDES_DIR . "/class/Model.php"; require_once INCLUDES_DIR . "/model/User.php"; # Prepare the Config interface. $config = Config::current(); # Atlantic/Reykjavik is 0 offset. Set it so the timezones() function is # always accurate, even if the server has its own timezone settings. $default_timezone = oneof(ini_get("date.timezone"), "Atlantic/Reykjavik"); set_timezone($default_timezone); # Sanitize all input depending on magic_quotes_gpc's enabled status. sanitize_input($_GET); sanitize_input($_POST); sanitize_input($_COOKIE); sanitize_input($_REQUEST); $protocol = (!empty($_SERVER['HTTPS']) and $_SERVER['HTTPS'] !== "off" or $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://"; $url = $protocol . $_SERVER['HTTP_HOST'] . str_replace("/install.php", "", $_SERVER['REQUEST_URI']); $index = parse_url($url, PHP_URL_PATH) ? "/" . trim(parse_url($url, PHP_URL_PATH), "/") . "/" : "/"; $htaccess = "<IfModule mod_rewrite.c>\nRewriteEngine On\nRewriteBase {$index}\nRewriteCond %{REQUEST_FILENAME} !-f\n" . "RewriteCond %{REQUEST_FILENAME} !-d\nRewriteRule ^.+\$ index.php [L]\n</IfModule>"; $path = preg_quote($index, "/"); $htaccess_has_chyrp = (file_exists(MAIN_DIR . "/.htaccess") and preg_match("/<IfModule mod_rewrite\\.c>\n([\\s]*)RewriteEngine On\n([\\s]*)RewriteBase {$path}\n" . "([\\s]*)RewriteCond %\\{REQUEST_FILENAME\\} !-f\n([\\s]*)RewriteCond %\\{REQUEST_FILENAME\\}" . " !-d\n([\\s]*)RewriteRule \\^\\.\\+\\\$ index\\.php \\[L\\]\n([\\s]*)<\\/IfModule>/", file_get_contents(MAIN_DIR . "/.htaccess"))); $errors = array(); $installed = false; if (file_exists(INCLUDES_DIR . "/config.yaml.php") and file_exists(MAIN_DIR . "/.htaccess")) { $sql = SQL::current(true); if ($sql->connect(true) and !empty($config->url) and $sql->count("users")) { error(__("Already Installed"), __("Chyrp is already correctly installed and configured.")); } } if (!is_writable(MAIN_DIR) and !file_exists(MAIN_DIR . "/.htaccess") or file_exists(MAIN_DIR . "/.htaccess") and !is_writable(MAIN_DIR . "/.htaccess") and !$htaccess_has_chyrp) {
<?php /* Define global field array for use in custom error messages */ $requiredField = array('amount' => 'amount', 'unit' => 'unit'); /* Define validation rule messages */ $errorMessage = array('no_amount' => 'You did not enter an amount', 'no_unit' => 'You did not enter a unit to convert to', 'num_above_zero' => 'The entered amount must be numeric and greater than zero'); /* Define error array */ $errors = array(); /* If the convert button was pressed */ if (isset($_POST['convert'])) { /* Check if an amount has been entered */ if (!is_valid(sanitize_input($_POST[$requiredField['amount']]))) { array_push($errors, [$requiredField['amount'] => $errorMessage['no_amount']]); } /* If an amount has been entered and is valid, check if numeric and greater than zero */ if (is_valid(sanitize_input($_POST[$requiredField['amount']])) && !is_num_above_zero($_POST[$requiredField['amount']])) { array_push($errors, [$requiredField['amount'] => $errorMessage['num_above_zero']]); } /* Check if a unit has been selected */ if ($_POST[$requiredField['unit']] == 'default') { array_push($errors, [$requiredField['unit'] => $errorMessage['no_unit']]); } /* If there are no errors, convert! */ if (!has_items($errors)) { /* Send the submitted values to the convert function */ $convertedValue = ConvertLiquid($_POST[$requiredField['amount']], $_POST[$requiredField['unit']]); } } else { if (isset($_POST['reset'])) { unset($errors); }