function validate_user($username, $password, $remember_me) { $current_page = substr($_SERVER["SCRIPT_NAME"], strrpos($_SERVER["SCRIPT_NAME"], "/") + 1); open_db(); //Need to sanitize the input $username = mysql_real_escape_string($username); $password = mysql_real_escape_string($password); if ($username && $password) { $query = "SELECT * FROM users WHERE username = '******' and (password = '******' OR password = password('{$password}'))"; $result = mysql_query($query); if (!$result || mysql_num_rows($result) < 1) { $_SESSION["error"] = "Your login could not be validated"; } else { $info = mysql_fetch_array($result); $_SESSION["username"] = $info[username]; $_SESSION["logged_in"] = "Y"; if ($remember_me) { setcookie("username", $info[username], time() + 60 * 60 * 24 * 90, "/"); setcookie("password", $info[password], time() + 60 * 60 * 24 * 90, "/"); setcookie("remember_me", $remember_me, time() + 60 * 60 * 24 * 90, "/"); } } } else { if ($username && !$password) { $_SESSION["error"] = "Please enter your password"; } else { if ($current_page != 'cp' && $current_page != 'cp.php') { $_SESSION["error"] = "You must be logged in to access this page"; } } } }
function save_xml_tutorial(&$file) { global $username; debug_msg("File type is XML"); $tmpfile = $file["tmp_name"]; $filename = $file["name"]; $filepath = "users/{$username}"; debug_msg("Path: {$filepath}"); $pathname = "{$filepath}/{$filename}"; debug_msg("File will be saved as ../{$pathname}"); // Check if file exists and if not, write the data if (file_exists("../{$pathname}")) { debug_msg("File exists - temporary storage"); if (!is_dir("../{$filepath}/temp/")) { mkdir("../{$filepath}/temp/"); } move_uploaded_file($tmpfile, "../{$filepath}/temp/{$filename}"); $result = false; } else { move_uploaded_file($tmpfile, "../{$pathname}"); debug_msg("Move succeeded"); // update database $filenoext = stripextension($filename); open_db(); $date = date("Y-m-d"); $sql = "INSERT INTO file (file_date, file_author, file_path, file_name)" . " VALUES ('{$date}','{$username}','{$filepath}','{$filenoext}')" . " ON DUPLICATE KEY UPDATE file_date='{$date}';"; query_db($sql); $result = $filenoext; } return $result; }
public function getGroupProfile($report_group_id) { //error_log(__FILE__.__FUNCTION__.'.$report_group_id: '.$report_group_id); //$report_group_id = 48; //This will be the selected report group from the drop down //require "config.php"; $db = open_db(); //Check to see if the user is still logged in if (isset($_SESSION["user_id"])) { $params = array("report_group_id" => $report_group_id, "user_id" => $_SESSION["user_id"]); } else { //Logged out header("Location: /login"); //Go to login page exit; } $sth = $db->prepare(' SELECT report_group_id, report_group_name, email_subject_line, report_time_zone, service_addr1, service_addr2, service_addr3, org_name, mail_address1, mail_address2, mail_city, mail_state, mail_zip, rate_name, rate_notes, tariff_name, tariff_notes, report_gen_file_name, default_report_file_base_name FROM report_groups rg, sys_users su, rates r, rate_tariffs rt WHERE report_group_id = :report_group_id AND report_group_id IN (SELECT report_group_id FROM link_report_group_sys_user WHERE user_id = :user_id) AND rg.enabled = TRUE AND rg.requestor_user_id = su.user_id AND rg.rate_id = r.rate_id AND rt.tariff_id = r.tariff_id '); $sth->execute($params); $results = $sth->fetchAll(PDO::FETCH_ASSOC); $db = null; return json_encode($results); }
function planned_delete($db_array, $path) { # used to cleanup outdated mailboxes $dbhandler = ""; open_db($dbhandler, $db_array); $request = $dbhandler->query("SELECT * FROM `mailboxlist`"); while ($row = mysqli_fetch_array($request)) { $current = time(); $current_readable = date('Y-m-d H:i:s', time()); $creation = strtotime($row["creationdate"]); $creation_readable = $row["creationdate"]; $ttl = $row["duration"] * 60 * 60; $removing = $creation + $ttl; $removing_readable = date('Y-m-d H:i:s', $removing); # converts if ($current >= $removing) { # Action for expired mailboxes $boxname = $row["boxname"]; delete_mailbox($db_array, $boxname, $path); $to = $row["destination"]; sent_status_mail($to); #echo "Die Mailbox ".$row["boxname"]." wurde gelöscht!<br \>"; } else { #echo "for debug purposes<br \>"; } } mysqli_close($dbhandler); }
function update_data($sql, $arr) { $db = open_db(); try { $sth = $db->prepare($sql); for ($i = 0; $i < count($arr); $i++) { $sth->bindParam($arr[$i][0], $arr[$i][1], $arr[$i][2]); } $sth->execute(); } catch (PDOException $e) { echo "database error: " . $e->getMessage(); } }
function query_with_row_count($sql) { $row_count = 0; try { $db = open_db(); foreach ($db->query($sql) as $row) { // print_r($row); $row_count++; } $db = NULL; } catch (PDOException $e) { echo $e->getMessage(); } $db = NULL; return $row_count; }
function overwrite_old_file($fname) { debug_msg("overwrite {$fname}"); global $username; $filepath = "users/{$username}"; $pathname = "../{$filepath}/{$fname}"; debug_msg("File will be saved as {$pathname}"); // move the file move_uploaded_file("../{$filepath}/temp/{$filename}", $pathname); debug_msg("Move succeeded"); // update database $filenoext = stripextension($fname); open_db(); $date = date("Y-m-d"); $sql = "INSERT INTO file (file_date, file_author, file_path, file_name)" . " VALUES ('{$date}','{$username}','{$filepath}','{$filenoext}')" . " ON DUPLICATE KEY UPDATE file_date='{$date}';"; query_db($sql); }
function db_get_records_with_condition($p_dbh, $table_name, $key_field, $key_value, $key_operator = null, $sortby = null, $user = null) { $q = "select * from " . $table_name; if (!empty($key_operator)) { $q .= " where "; $q .= "("; $count = count($key_value); for ($i = 0; $i < $count; $i++) { $q .= $key_field . " = ? "; if ($i < $count - 1) { $q .= $key_operator . " "; } } $q .= ")"; if ($user != null) { $key_value[] = $user; $q .= " AND reviewer = ? "; } } if ($sortby) { $q .= " order by " . $sortby; } try { $dbh = $p_dbh == null ? open_db() : $p_dbh; $dbh->beginTransaction(); $sth = $dbh->prepare($q); $vals = $key_value; $sth->execute($vals); $res = $sth->fetchAll(PDO::FETCH_ASSOC); $dbh->commit(); $dbh = null; if (count($res) > 0) { return $res; } else { return null; } } catch (PDOException $ex) { $dbh = null; return null; } }
public function getPrevBills($report_group_id) { //TODO: Check to see if the user is still logged in error_log(__FILE__ . __LINE__ . '.$report_group_id: ' . $report_group_id . ' - user_id: ' . $_SESSION["user_id"]); //require "config.php"; $db = open_db(); //Set time zone /* $sth = $db->prepare(' SET TIME ZONE :user_tz; '); if (isset($_SESSION["user_tz"])) //If the user_tz is set $params = array("user_tz"=>$_SESSION["user_tz"]); else $params = array("user_tz"=>'UTC'); $sth->execute($params); */ //Get previous bills $params = array("user_id" => $_SESSION["user_id"], "report_group_id" => $report_group_id); $sth = $db->prepare("\n SELECT " . $report_group_id . " AS report_group_id, rate_effective_id, date_effective AT TIME ZONE 'UTC' AS bill_start_date,\n (SELECT to_timestamp(param_value) + '23:59:59'::INTERVAL FROM rate_params\n WHERE rate_effective_id = re.rate_effective_id\n AND param_value_id=0) as bill_end_date,\n (SELECT param_value FROM rate_params\n WHERE rate_effective_id = re.rate_effective_id AND param_value_id=1) AS bill_amount\n FROM rates r, rates_effective re\n WHERE r.rate_id = (SELECT rate_id FROM report_groups rg, link_report_group_sys_user lr\n WHERE rg.report_group_id = lr.report_group_id AND\n rg.report_group_id = :report_group_id and user_id = :user_id)\n AND r.rate_id = re.rate_id\n ORDER BY date_effective desc\n "); $sth->execute($params); $results = $sth->fetchAll(PDO::FETCH_ASSOC); //error_log(__FILE__.__LINE__.'$params: '.print_r($params, true)); //error_log(__FILE__.__LINE__.'$results: '.print_r($results, true)); //Perform formatting //$fmt = new NumberFormatter( $_SESSION["user_locale"], NumberFormatter::CURRENCY ); //Properly format the results $final = array(); foreach ($results as $result) { $result['bill_start_date'] = date("c", strtotime($result['bill_start_date'])); //ISO 8601 $result['bill_end_date'] = date("c", strtotime($result['bill_end_date'])); //ISO 8601 $final[] = $result; } echo json_encode($final); }
function init(&$db, $checkSession = NULL) { $ok = TRUE; // Set timezone if (!ini_get('date.timezone')) { date_default_timezone_set('UTC'); } // Set session cookie path ini_set('session.cookie_path', getAppPath()); // Open session session_name(SESSION_NAME); session_start(); if (!is_null($checkSession) && $checkSession) { $ok = isset($_SESSION['consumer_key']) && isset($_SESSION['resource_id']) && isset($_SESSION['user_consumer_key']) && isset($_SESSION['user_id']) && isset($_SESSION['isStudent']); } if (!$ok) { $_SESSION['error_message'] = 'Unable to open session.'; } else { // Open database connection $db = open_db(!$checkSession); $ok = $db !== FALSE; if (!$ok) { if (!is_null($checkSession) && $checkSession) { // Display a more user-friendly error message to LTI users $_SESSION['error_message'] = 'Unable to open database.'; } } else { if (!is_null($checkSession) && !$checkSession) { // Create database tables (if needed) $ok = init_db($db); // assumes a MySQL/SQLite database is being used if (!$ok) { $_SESSION['error_message'] = 'Unable to initialise database.'; } } } } return $ok; }
<h1>Full Program</h1> <?php require_once "lib/app.php"; $db = open_db($db_address_abs); require "data/events.php"; $fmt = 'H:i'; $cur = NULL; $all = array_merge($presentations, $breaks); function cmp($a, $b) { $fmt = 'Y-m-d\\TH:i:s'; return strcmp($a->start->format($fmt), $b->start->format($fmt)); } usort($all, "cmp"); foreach ($all as $p) { #print "//{$p->id}"; #if (!$p->is_plenary) { continue; } $day = $p->start->format('l jS \\of F Y'); if (!($day == $cur)) { if (!is_null($cur)) { print "</ul>\n"; } print "<h2>{$day}</h2>\n"; print "<ul class='fullprog'>\n"; $cur = $day; } #print "<!-- " . $day . " " . $cur . "-->\n"; print <<<EOT
<? require_once("../_shared/config.inc.php"); include_once("../_shared/func.inc.php"); open_db($db_host,$db_user,$db_passw,$datbase); $data = get_row("referenz","name,pos,imgs","id='".$id."'"); if ($f_cancel) { echo "<script language=\"javascript\">window.close(this)</script>"; exit; } if ($f_rem) { if ($data['imgs']) { $pics = explode("#",$data['imgs']); for ($x = 0; $x < 6; $x++) { if ($pics[$x] != "---") { unlink($img_ref.$id."_".$x."_sm.jpg"); unlink($img_ref.$id."_".$x."_lg.jpg"); } } } remove_data("referenz","id=".$id); update_data("referenz","pos=pos-1","pos>".$data['pos']); mysql_close; echo "<script language=\"javascript\">window.opener.location.href='list.php'</script>"; echo "<script language=\"javascript\">window.close(this)</script>"; } echo "<html>\n"; echo "<head>\n";
function put() { require 'config.php'; $request = check_and_clean_json('collector_id'); if (EC_DEBUG) { error_log(__FILE__ . __LINE__ . ":REST:get_new_device_id:REQUEST" . print_r($request, true)); } if ($request != null) { //Check for valid inputs if (!$request->collector_id) { error_log(__FILE__ . __LINE__ . ":REST:get_new_device_id:No collector_id provided"); echo "RESTRICTED SYSTEM"; return; } if (!$request->device_type_id) { error_log(__FILE__ . __LINE__ . ":REST:get_new_device_id:No device_type_id provided"); echo "RESTRICTED SYSTEM"; return; } if (!$request->device_name && strlen($request->device_name) > 0) { error_log(__FILE__ . __LINE__ . ":REST:get_new_device_id:No device_name provided"); echo "RESTRICTED SYSTEM"; return; } } $conn = open_db(); //Verify that a proper collector_id and device_type_id was supplied $sth = $conn->prepare(' SELECT owner_user_id FROM device_types dt, collector_types ct, collectors c WHERE ct.collector_type_id = dt.collector_type_id AND c.collector_type_id = ct.collector_type_id AND c.collector_id = :collector_id AND device_type_id = :device_type_id; '); if (EC_DEBUG) { error_log(__FILE__ . __LINE__ . ":REST:get_new_device_id:DATA: " . $request->collector_id . " - " . $request->device_type_id . " - " . $request->device_name); } $sth->execute(array('collector_id' => $request->collector_id, 'device_type_id' => $request->device_type_id)); $owner_user_id = $sth->fetchColumn(); if (EC_DEBUG) { error_log(__FILE__ . __LINE__ . ":REST:get_new_device_id:owner_user_id: " . $owner_user_id); } if ($owner_user_id) { //Valid device type for the collector type if the query returns $owner_user_id //Insert into devices and get new device_id $sth = $conn->prepare(' SELECT device_id FROM devices WHERE collector_id = :collector_id AND device_name = :device_name; '); $sth->execute(array('collector_id' => $request->collector_id, 'device_name' => $request->device_name)); $device_id = $sth->fetchColumn(); if (!$device_id) { //if device does not already exist //Insert row into devices table $sth = $conn->prepare(' INSERT INTO devices (device_name, device_type_id, collector_id, device_comm_data1, enabled, gmt_last_config_update) VALUES(:device_name, :device_type_id, :collector_id, :device_comm_data1, true, now()) RETURNING device_id; '); $sth->execute(array('device_name' => $request->device_name, 'device_type_id' => $request->device_type_id, 'collector_id' => $request->collector_id, 'device_comm_data1' => $request->device_comm_data1)); //error_log(print_r($sth->errorInfo(), true)); $device_id = $sth->fetchColumn(); //Get the new device_id //Give the sys admin access to the new device $sth = $conn->prepare(' INSERT INTO link_users_devices (user_id, device_id) VALUES (1, :device_id) '); $sth->execute(array('device_id' => $device_id)); //Give the creator access to the new device $sth = $conn->prepare(' INSERT INTO link_users_devices(user_id, device_id) VALUES(:user_id, :device_id); '); $sth->execute(array('user_id' => $owner_user_id, 'device_id' => $device_id)); } else { error_log("REST:get_new_device_id:ERROR: Device already exists"); } //Create the response $response = array('device_id' => $device_id, 'enabled' => true); if (EC_DEBUG) { error_log(__FILE__ . __LINE__ . ":REST:get_new_device_id:RESPONSE1: " . print_r($response, true)); } //Send the response echo json_encode($response); } else { //Error or other problem //Create the response $response = array('device_id' => -1, 'enabled' => false); error_log(__FILE__ . __LINE__ . "REST:get_new_device_id:RESPONSE2: " . print_r($response, true)); //Send the response echo json_encode($response); } }
function db_save_session($p_dbh, $session_id, $username, $account_id) { $q_insert = "insert into session (id, username, account_id, created_on) values (?,?,?,NOW())"; $q_update = "update session set username=?, account_id=?, created_on=NOW() where id=?"; try { $dbh = $p_dbh == null ? open_db() : $p_dbh; $sess = db_get_session($dbh, $session_id); if ($sess === null) { $q = $q_insert; $vals = array($session_id, $username, $account_id); } else { $q = $q_update; $vals = array($username, $account_id, $session_id); } $dbh->beginTransaction(); $sth = $dbh->prepare($q); $sth->execute($vals); $dbh->commit(); $dbh = null; return true; } catch (PDOException $ex) { echo "Error Message: " . $ex->getMessage(); if ($dbh) { $dbh->rollBack(); $dbh = null; } return false; } }
<?php session_start(); /*print_r($_POST);*/ if (!isset($_SESSION['username'])) { json_encode(array('status' => 'error', 'error' => 'not logged in', 'code' => 500)); exit; } require 'database.php'; $dbconn = open_db(); $action = $_POST['action']; // Here I have ajax file which can handle any ajax calls based on aciton like delete-device history switch ($action) { case "delete-device": $userId = $_POST['userid']; $getDev = "SELECT devid FROM devices WHERE users_id = " . $userId . " AND status = 1"; /*$query = "UPDATE devices SET status = 0 WHERE id=$id"; if(mysqli_query($dbconn, $query)) { $deleted = true; }*/ $query = "UPDATE mob_signal SET status = 0 WHERE devid=({$getDev})"; if (mysqli_query($dbconn, $query)) { $deleted = true; } $deleted = true; if (isset($deleted) && ($deleted = true)) { echo json_encode(array('status' => 'ok', 'msg' => "You have deleted Successfully")); } else { echo json_encode(array('status' => 'error', 'code' => 500)); }
--- title: Avatar Hotel -List all --- <?php include '../../php/db.php'; include '../../php/form.php'; $table = params('table'); if (open_db()) { $number_of_rows = list_rows($table, '1'); $failure = FALSE; } else { $failure = TRUE; } ?> <h1>Listing</h1> <?php if (!$failure) { ?> <table id='list'> <thead> <tr> <?php $tabs = odbc_tables($dbConn); $tables = array(); while (odbc_fetch_row($tabs)) { if (odbc_result($tabs, "TABLE_TYPE") == "TABLE") { $table_name = odbc_result($tabs, "TABLE_NAME"); if ($table_name == $table) { $tables["{$table_name}"] = array(); $cols = odbc_exec($dbConn, 'select * from ' . $table_name . ' order by 1'); $ncols = odbc_num_fields($cols);
function init_db() { open_db(); init_config(); }
function process_login($login_info, $username, $password, $sitename) { if (is_array($login_info)) { // if an array is returned, then login was successful $bapi = $login_info['binding']; $sessionID = $login_info['sessionID']; $accountID = $login_info['accountID']; $isAgency = $login_info['isAgency']; if ($isAgency == true) { print_agency_login_form($username, $password, $sitename, "", $sessionID, $login_info['accounts']); } else { $dbh = open_db(); if ($dbh) { $rc = db_save_user($dbh, $username, $password, 'BRONTO', 'REQUESTER', $sitename); if ($rc == false) { display_warnbox("Unable to save user information (user="******",sitename=" . $sitename . ")"); } $rc = db_save_session($dbh, $sessionID, $username, $accountID); if ($rc == false) { display_warnbox("Unable to save session information (id=" . $sessionID . ",user="******")"); } if (db_update_user_last_login($dbh, $username) == false) { echo "Unable to record login date/time."; } // Confirm that user information is available. $userinfo = db_get_user($dbh, $username); if (empty($userinfo['firstname']) || empty($userinfo['lastname']) || empty($userinfo['email'])) { print_user_info_form($sessionID, $userinfo); } else { if (print_message_select_form($bapi, $sessionID) == false) { display_errorbox("Unable to connect to Bronto API."); print_request_login_form($username, $password, $sitename); } } } else { display_errorbox("Unable to connect to database."); print_request_login_form($username, $password, $sitename); } } } else { if ($login_info === false) { // if "false" was returned, then login was unsuccessful (incorrect username, password, or sitename) display_errorbox("Invalid username, password, or sitename."); } else { // otherwise, "null" is returned, meaning no connectivity to Bronto API display_errorbox("Unable to connect to the Bronto API server."); } print_request_login_form($username, $password, $sitename); } }
} // send e-mail to requesters } } } } else { if ($fm_stage == "reject") { if (!is_authenticated()) { display_errorbox("You are not authenticated; please log in."); print_review_login_form(); } else { if (empty($fm_notes)) { display_errorbox("One or more reasons for rejecting the message must be provided."); print_verify_form(VERIFY_TYPE_REJECT, $fm_sessionid, $fm_requestid); } else { $dbh = open_db(); //db_update_request_status($dbh, $fm_requestid, "REJECTED", $fm_notes); db_update_request_status_user($dbh, $fm_requestid, "REJECTED", $fm_notes, $_SESSION['username']); $reqinfo = db_load_request($dbh, $fm_requestid); $requserinfo = db_get_user($dbh, $reqinfo['requester']); $revuserinfo = db_get_user($dbh, $reqinfo['reviewer']); if (send_rejection_to_requester($reqinfo, $revuserinfo, $requserinfo) == true) { //echo "<p>Sent notice of rejection to requester.</p>"; ?> <script type="text/javascript"> alert('Sent notice of rejection to requester.'); </script> <?php require_once './include/display_listrequest.php'; //AB print_requestid_form();
function get_cohort_list($userid) { $dbh = open_db(); $cohorts = array(); if (($res = $dbh->query("SELECT * FROM cohortuser NATURAL JOIN cohort WHERE userid={$userid};", PDO::FETCH_ASSOC)) == false) { die("Could not query database"); } foreach ($res as $row) { $row['userid'] = (int) $row['userid']; $row['cohortid'] = (int) $row['cohortid']; array_push($cohorts, $row); } return $cohorts; }
function delete_mailbox($db_array, $boxname, $path) { $dbhandler = ""; open_db($dbhandler, $db_array); $request = "DELETE FROM `mailboxlist` WHERE `boxname` = '" . $boxname . "'"; echo "<div align='center'>"; if ($dbhandler->query($request) === TRUE) { echo $GLOBALS["text_db_entry_removed"] . ": " . $boxname . "<br />"; } else { echo "Error removing DB entry: " . $dbhandler->error . "<br />"; } mysqli_close($dbhandler); $boxname = str_replace(".", ":", $boxname); $filepath = $path . ".qmail-" . $boxname; if (unlink($filepath)) { echo $GLOBALS["text_file_removed"] . ": .qmail." . $boxname . "<br />"; } else { echo $GLOBALS["text_file_error"] . "<br />"; } echo "<a href='" . htmlentities($_SERVER['PHP_SELF']) . "'>" . $GLOBALS["text_back"] . "</a><br />"; echo "</div>"; }
function list_room_types() { global $dsn, $dbConn; open_db(); $sql = "select room_type_id, desc_en from room_types order by desc_en"; $dbResult = odbc_exec($dbConn, $sql); while (odbc_fetch_row($dbResult)) { echo '<option label="' . odbc_result($dbResult, "desc_en") . '">' . odbc_result($dbResult, "room_type_id") . '</option>'; } close_db(); return true; }
if ($stamp == $prev) { } else { echo "<p style='font-size:medium'>{$stamp}</p><p>"; } echo "- <a href='{$url}' target='_NEW{$id}'>{$title}</a><br/>\n"; $prev = $stamp; } echo "\n<p style='font-size:x-small'>Above was generated by a homegrown bolt-on script for <a href='https://www.wallabag.org/' target='_NEWWALLA'>Wallabag</a>, which is a free utility for capturing web content so that it can be read later.</p>"; echo "</textarea>"; close_db($dbh); } if ($action == "view") { $now = date('Ymd'); echo "<p>What's been in my bag this week? ({$now})\n\n"; $prev = ""; $dbh = open_db($database); $query = "select title,url,stamp,id from bag order by stamp"; $result = $dbh->query($query); while ($row = $result->fetchArray()) { $title = preg_replace('/[^A-za-z0-9\'\\"\\?\\.\\&\\!\\$\\:\\;\\/\\- ]/', ' ', $row['title']); $url = $row['url']; $stamp = $row['stamp']; $id = $row['id']; if ($stamp == $prev) { } else { echo "<p style='font-size:medium'>{$stamp}</p><p>"; } echo "- <a href='{$url}' target='_NEW{$id}'>{$title}</a><br/>\n"; $prev = $stamp; } echo "\n<p style='font-size:x-small'>Above was generated by a homegrown bolt-on script for <a href='https://www.wallabag.org/' target='_NEWWALLA'>Wallabag</a>, which is a free utility for capturing web content so that it can be read later.</p>";
// Authenticate to the LDAP server. ldap_auth() throws // an exception if there's an error, so if it returns, // we know we're good to go. ldap_auth(); // The file to be downloaded is looked up using the job ID and the // job ID is specified as a GET var $_GET_lower = array_change_key_case($_GET, CASE_LOWER); $jobid = $_GET_lower['jobid']; if (!$jobid) { // Job ID must be specified on the command line header('HTTP/1.1 400 Bad Request'); echo "JobID parameter not specified in the requested URL<BR/>\n"; return; } try { $pdo = open_db(); // Check to see if the user is asking about one of his own jobs $user = find_user($pdo, $jobid); if ($user === false) { header('HTTP/1.1 404 Not Found'); echo "Job ID {$jobid} does not exist.<BR/>\n"; return; } if ($user != $_SERVER['PHP_AUTH_USER']) { header('HTTP/1.1 403 Forbidden'); echo "Job ID {$jobid} not owned by {$_SERVER['PHP_AUTH_USER']}.<BR/>\n"; // Strictly speaking, this is something of a security hole in that // it confirms the existance of a job that the user doesn't own. // That info is probably available elsewhere - showq and such - so // we're probably ok here. return;
<?php require_once "mylib.php"; // test with: logtriple.php?s=testuser&p=drank&v=water&k=testkey $db = open_db(); log_to_db($db); function log_to_db($db) { $ERROR_MSG = "usage logger.php?s=subject&p=predicate&v=value&k=key"; // #1 - grab values from query string $subject = array_key_exists('s', $_GET) ? sanitize_string($_GET['s']) : die($ERROR_MSG); $predicate = array_key_exists('p', $_GET) ? sanitize_string($_GET['p']) : die($ERROR_MSG); $value = array_key_exists('v', $_GET) ? sanitize_string($_GET['v']) : die($ERROR_MSG); $key = array_key_exists('k', $_GET) ? sanitize_string($_GET['k']) : die($ERROR_MSG); $timestamp = time(); // #2 - Check to see if user is authorized // if they are, we should get one match from the table $queryString = "SELECT * FROM AuthKey WHERE username = '******' AND key='{$key}'"; // log the query string for debugging purposes echo "\$queryString={$queryString}<br>"; $result = $db->query($queryString); $numRows = count($result->fetchAll()); // #3 - no match? Exit program! if ($numRows == 0) { die("Bad username or key!"); } // #4 - INSERT values into Triple table $queryString = "INSERT INTO Triple (id, subject, predicate, value, timestamp) VALUES (NULL, '{$subject}', '{$predicate}', '{$value}', '{$timestamp}')"; // log the query string for debugging purposes echo "\$queryString={$queryString}<br>"; $result = $db->query($queryString);
<?php include '../functions.php'; #Is this a proper key? Possibly invalid format of the key, injection-attempt, etc... $act_key = $_GET['act_key']; $act_key = trim($act_key); if (!preg_match('/^[a-z|A-Z|0-9]{32}$/', "{$act_key}")) { header("Location: no_such_key.html"); die; } #------------------------------------------------------------------------------------------------------------------------- #Open MySQL-DB $link = open_db(); #Has someone this activation key? $result = mysql_query("SELECT * FROM Yane WHERE activation_key = '{$act_key}'") or die(mysql_error()); #If no, show error if (mysql_num_rows($result) == 0) { mysql_close($link); header("Location: no_such_key.html"); die; } else { #Get mailaddress $result = mysql_query("SELECT email_address FROM Yane WHERE activation_key = '{$act_key}';") or die(mysql_error()); $row = mysql_fetch_assoc($result); #If yes, set activation-key to NULL mysql_query("UPDATE Yane SET activation_key = NULL WHERE CONVERT( activation_key USING utf8 ) = '{$act_key}'") or die(mysql_error()); mysql_close($link); # Log the correct login log_correct_login($row['email_address'], $_SERVER['REMOTE_ADDR']); # Set account modification-time log_change($row['email_address']);
<?php require_once 'auth_config.php'; session_start(); if (!(isset($_SESSION['uid']) && $_SESSION['uid']) or isset($_SESSION['ip']) && !$_SESSION['ip'] == $_SERVER['REMOTE_ADDR'] or $_SESSION['last_action'] + SESSION_MAX_IDLE_TIME < time()) { header('Status: 403 Forbidden'); header('Location: ' . $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['HTTP_HOST'] . rtrim(dirname($_SERVER['SCRIPT_NAME']), '/') . '/login.php'); #print_r($_SESSION); #echo SESSION_MAX_IDLE_TIME; #echo $_SESSION['last_action'] + SESSION_MAX_IDLE_TIME; #echo "auto logout"; exit; } require_once "../lib/app.php"; $_SESSION['last_action'] = time(); $_SESSION['loggedin'] = TRUE; // need to set this here for get login $db = open_db($db_address); $stmt = $db->prepare("SELECT * FROM {$tableName} WHERE id = :id"); $stmt->bindParam(":id", $_SESSION['uid']); $res = $stmt->execute(); $P = $stmt->fetch(PDO::FETCH_ASSOC); #PDO::FETCH_OBJ); // Kein Exit, da das aufrufende Skript weiter arbeiten muss!
<?php /** * Funzioni di utilità. * @author Erika Fabris - Matricola: 1045853 */ // ini_set('display_errors',1); session_start(); require_once "../function/conn.php"; $conn = open_db(); /** * chiamato quando un utente inizia la batteria di test, salva una nuova tupla nel database * * @access public */ function save_test() { global $conn; $timeIniz = $_SESSION['startTime']; try { $sth = $conn->prepare("LOCK TABLES test WRITE;"); $sth->execute(); $sth = $conn->prepare("SELECT max(id) AS ma FROM test;"); $sth->execute(); $sth->setFetchMode(PDO::FETCH_ASSOC); $result = $sth->fetch(); if ($result['ma'] != null) { $_SESSION['id_test'] = intval($result['ma']) + 1; } else { $_SESSION['id_test'] = 1; }
<?php $page_file = "editdeejay.php"; $page_title = "Edit Deejay"; require "ext/main_fns.php"; require "ext/header.php"; require "ext/deejay_fns.php"; open_db(); if (!$_SESSION["logged_in"]) { loginPrompt($_POST[username], $_POST[remember_me], $_SESSION["error"]); } else { /*----- CONTENT ------*/ ?> <div id="cp"> <?php $id = $_GET['id']; if (!$id) { echo 'Error - missing value(s)'; exit; } editdeejay($id); ?> <p> <a href="viewalldeejays.php"><< Back to All Deejays</a> </div> <?php } require "ext/footer.php";
$classes_to_save[] = $a_class_to_save; } } // build the array of fields to pass through $fields = array(); if (isset($classes_to_save[0]) && count($classes_to_save[0]) > 0) { foreach ($classes_to_save[0] as $k => $v) { $fields[] = $k; } } else { echo "no classes"; return "no classes"; } saveData($semester, $year, $subclasses_to_save, $fields, "subclass_identifier", "classes", array("last_mod_time"), array("crn" => "0")); return saveData($semester, $year, $classes_to_save, $fields, "crn", "classes", array("last_mod_time"), array("parent_class" => "0")); } if (!open_db()) { echo "failed to connect to database, aborting"; return FALSE; } $term = loadTerm(getNextTerm()); while ($term !== NULL) { echo "===============================================================================\n"; echo "===============================================================================\n"; echo "..." . $term["name"] . "\n"; echo "...subjects\n"; saveSubjects($term); echo "...classes\n"; saveClasses($term); $term = loadTerm(getNextTerm()); }