public function login() { if (!empty($_SESSION["id"])) { $this->redirect('/mvc/public/'); } $model = $this->model('User'); if ($_SERVER["REQUEST_METHOD"] == "POST") { // validate submission if (empty($_POST["username"])) { apologize("You must provide your username."); } else { if (empty($_POST["password"])) { apologize("You must provide your password."); } } $rows = $model->check($_POST["username"]); // if we found user, check password if (count($rows) == 1) { // first (and only) row $row = $rows[0]; // compare hash of user's input against hash that's in database if (crypt($_POST["password"], $row["hash"]) == $row["hash"]) { // remember that user's now logged in by storing user's ID in session $_SESSION["id"] = $row["id"]; $_SESSION["username"] = $row["username"]; // redirect to portfolio $this->redirect("/mvc/public"); } } // else apologize $this->apologize("Invalid username and/or password."); } else { $this->render("login_form", ["title" => "Log In"]); } }
/** * Renders the next profile to view. */ function render_next() { //find current viewnum $viewNum = CS50::query("SELECT viewNum FROM users WHERE id = ?", $_SESSION["id"]); $viewnum = $viewNum[0]["viewNum"]; //find id of last viable profile $last = CS50::query("SELECT MAX(id) FROM users"); //increment viewnum to next viable profile do { CS50::query("UPDATE users SET viewNum = viewNum + 1 WHERE id = ?", $_SESSION["id"]); $viewnum++; if ($viewnum > $last[0]["MAX(id)"]) { apologize("You've seen e'rybody!"); break; } } while (count(CS50::query("SELECT * FROM users WHERE id = ?", $viewnum)) == 0 || $viewnum == $_SESSION["id"]); // render homepage; show new profile. render("home.php", ["title" => "home", "profile" => prof_lookup($viewnum)]); }
/** * Executes multiple SQL statements in a single transaction, each with its own parameters */ function tquery() { // sql statements in transaction $sqls = explode(";", rtrim(func_get_arg(0), ";")); // parameters, if any $params_list = array_slice(func_get_args(), 1); if (count($sqls) != count($params_list)) { apologize("sql error"); } static $handle; if (!isset($handle)) { try { // connect to database $handle = new PDO("mysql:dbname=" . DATABASE . ";host=" . SERVER, USERNAME, PASSWORD); // ensure that PDO::prepare returns false when passed invalid SQL $handle->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); $handle->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); } catch (Exception $e) { // trigger (big, orange) error trigger_error($e->getMessage(), E_USER_ERROR); exit; } } foreach ($sqls as $sql) { // prepare SQL statement if (($statements[] = $handle->prepare($sql)) === false) { trigger_error($handle->errorInfo()[2], E_USER_ERROR); exit; } } try { $handle->beginTransaction(); for ($i = 0; $i < count($statements); $i++) { $statements[$i]->execute($params_list[$i]); } $handle->commit(); } catch (Exception $e) { $handle->rollback(); trigger_error($e->getMessage(), E_USER_ERROR); return false; } }
<?php // configuration require "../includes/config.php"; // if user reached page via GET (as by clicking a link or via redirect) if ($_SERVER["REQUEST_METHOD"] == "GET") { // else render form render("invitation_form.php", ["title" => "Invite"]); } else { if ($_SERVER["REQUEST_METHOD"] == "POST") { $email = $_POST["invite-email"]; if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { apologize("Invalid email address - please enter a valid email."); } else { $self = query("SELECT * FROM users WHERE id = ?", $_SESSION["id"]); $data = query("SELECT * FROM invite WHERE id = ? AND email = ?", $_SESSION["id"], $email); $users = query("SELECT COUNT(email) AS count FROM users WHERE email = ?", $email); if ($users[0]["count"] > 0) { apologize("This email address is already registered under a user!"); } elseif (count($data) > 0) { apologize("You've already invited this user!"); } else { query("INSERT INTO invite VALUES (?, ?)", $_SESSION["id"], $email); inviteEmail(["username" => $self[0]["username"], "id" => $self[0]["id"], "email" => $email]); redirect("/"); } } } }
function display_poll($poll, $url) { // open form echo("<form action=\"submit_poll.php?url=$url\" method=\"post\">"); // open the table echo("<table class=\"poll\">"); // counter for participants $participants = 0; // get preliminary participant data foreach($poll['keys']['NAME'] as $key => $value) { $name[$participants] = $poll['text'][$value]['value']; $participants++; } // print dates row echo("<tr>"); // print blank space before times echo("<td></td>"); // counter for day entries $day = 0; // create date strings foreach($poll['keys']['OPTION'] as $key => $value) { // break once out of dates if($poll['text'][$value]['level'] != TIME_LEVEL) break; // update counter $day++; // set string value if(isset($poll['text'][$value]['attributes']['STARTDATETIME'])) $string[$day] = substr($poll['text'][$value]['attributes']['STARTDATETIME'], 0, 10); else if(isset($poll['text'][$value]['attributes']['DATETIME'])) $string[$day] = substr($poll['text'][$value]['attributes']['DATETIME'], 0, 10); } // counter for number of days per entry $num_days = 1; for($i = 1, $j = 2; $i < $day; $i++, $j++) { // if multiple dates of same, continue if($string[$i] == $string[$j]) $num_days++; // if last of this date, print html else if($string[$i] != $string[$j]) { // print html echo("<td class=\"date\" colspan=\"{$num_days}\">"); echo("$string[$i]"); echo("</td>"); // reset counter $num_days = 1; } } // if last possible date, print html (must be last of this echo("<td class=\"date\" colspan=\"{$num_days}\">"); echo("$string[$day]"); echo("</td>"); // close dates row echo("</tr>"); // print time slots row echo("<tr>"); // print number of participants echo("<td>"); // update counter (ignore initiator) $participants--; echo("Participants: $participants"); echo("</td>"); // counter for time entries $time = 0; // create time strings foreach($poll['keys']['OPTION'] as $key => $value) { // break once out of times if($poll['text'][$value]['level'] != TIME_LEVEL) break; // update counter $time++; // display time if only 1 time exists if(isset($poll['text'][$value]['attributes']['DATETIME'])) $time_range[$time] = substr($poll['text'][$value]['attributes']['DATETIME'], 11, -3); else if(isset($poll['text'][$value]['attributes']['STARTDATETIME'])) { // set start string value (save total string for later use) $start[$time] = substr($poll['text'][$value]['attributes']['STARTDATETIME'], 11, -3); // set end string value $end[$time] = substr($poll['text'][$value]['attributes']['ENDDATETIME'], 11, -3); // set time range value $time_range[$time] = $start[$time]." - <br>".$end[$time]; } else apologize("Sorry, an error occurred. Please try again."); } for($i = 1; $i <= $time; $i++) { echo("<td class=\"time\">"); echo("$time_range[$i]"); echo("</td>"); } // close time slots row echo("</tr>"); // check if any participants exist if($participants != 0) { // initialize counters $checks = 1; $participant_num = 1; // print out previous submissions foreach($poll['keys']['OPTION'] as $key => $value) { // check if this "option" array is for a participant and not a time if($poll['text'][$value]['level'] == PARTICIPANT_LEVEL) { if($checks <= $time) { // set array value of response $participant[$participant_num][$checks] = $poll['text'][$value]['value']; // update counter $checks++; } else { // update counters $checks = 1; $participant_num++; // set array value of response $participant[$participant_num][$checks] = $poll['text'][$value]['value']; // add to checks $checks++; } } } // update counter $checks--; // initialize counter for 'yesses' for($collumn = 1; $collumn <= $time; $collumn++) $yes_num[$collumn] = 0; // error check for api limitations $posts = 0; // loop through participants for($i = 1; $i <= $participant_num; $i++) { // open participants row echo("<tr>"); // print participant name echo("<td class=\"name\">"); echo("$name[$i]"); echo("</td>"); for($j = 1; $j <= $time; $j++) { // update counter $posts++; // print html echo("<td class=\"check\">"); // check (or not) availibility if($participant[$i][$j] == 1) { echo("<img src=\"extras/check.jpg\" alt=\"X\">"); // add to counter for number of 'yesses' $yes_num[$j]++; } else echo("<img src=\"extras/x.jpg\" alt=\"O\">"); echo("</td>"); } // close participants row echo("</tr>"); // break if post limit reached (prevent printing server error messages) if($posts >= POST_LIM) break; } } // print out blank submission field echo("<tr>"); echo("<td>"); // print text field echo("<input class=\"poll_box\" name=\"name\" type=\"text\" value=\"Your Name\">"); echo("</td>"); // print check boxes for($i = 1; $i <= $time; $i++) { echo("<td class=\"checkbox\">"); // initialize checkbox variable $checked = NULL; // decide whether box is checked or not if(isset($_GET["option$i"])) { // if prepopulated, change value of $selected if(htmlspecialchars($_GET["option$i"]) == "1") $checked = "checked=\"checked\""; } echo("<input class=\"box\" type=\"checkbox\" name=\"option$i\" {$checked} value=\"1\">"); echo("</td>"); } // close row echo("</tr>"); // print dates at bottom if more than 10 participants if($participants > 10) { // print time slots row again echo("<tr>"); // print blank space echo("<td>"); echo("</td>"); for($i = 1; $i <= $time; $i++) { echo("<td class=\"time\">"); echo("$time_range[$i]"); echo("</td>"); } // close time slots row echo("</tr>"); // print dates row again echo("<tr>"); // print blank space before dates echo("<td></td>"); // counter for number of days per entry $num_days = 1; for($i = 1, $j = 2; $i < $day; $i++, $j++) { // if multiple dates of same, continue if($string[$i] == $string[$j]) $num_days++; // if last of this date, print html else if($string[$i] != $string[$j]) { // print html echo("<td class=\"date\" colspan=\"{$num_days}\">"); echo("$string[$i]"); echo("</td>"); // reset counter $num_days = 1; } } // if last possible date, print html (must be last of this echo("<td class=\"date\" colspan=\"{$num_days}\">"); echo("$string[$day]"); echo("</td>"); // close dates row echo("</tr>"); } // print out number of 'yesses' per time echo("<tr>"); // print blank space echo("<td>"); echo("</td>"); // print values for($i = 1; $i <= $time; $i++) { echo("<td class=\"yesses\">"); echo("$yes_num[$i]"); echo("</td>"); } // close row echo("</tr>"); // print blank space, then... echo("<tr>"); echo("<td colspan=\"$time\">"); echo("</td>"); // print submit button echo("<td>"); echo("<input class=\"poll_submit\" type=\"submit\" value=\"Save\">"); echo("</td>"); echo("</tr>"); // close tags echo("</table>"); echo("</form>"); // print disclaimer if neccessary if($posts >= POST_LIM) { echo("<div class=\"disclaimer\">"); echo(DISCLAIMER); echo("<a href=\"$url\"> $url </a>. "); echo(THANKS); echo("</div>"); } }
<?php // Mostly original code // configuration require "../startbootstrap-business-casual-1.0.4/config.php"; //query username from users and stock from recruiter_userss $rows = CS50::query("SELECT company, event_date, event_time FROM events WHERE school = ? AND company= ?", $_POST["school"], $_POST["company"]); if ($rows != false) { $new_insertion = CS50::query("INSERT INTO user_events (company, event_time, event_date, user_id) \n VALUES (?, ?, ?, ?)", $_POST["company"], $rows[0]["event_time"], $rows[0]["event_date"], $_SESSION["id"]); if ($new_insertion !== false) { redirect("students.php"); } } else { apologize("sorry, there is no event for this company"); }
// kontrollo moshen if (!preg_match("/^[1-9][0-9]\$/", $_POST["mosha"])) { showAlert("Moshë e pavlefshme."); renderNoMenu("register_" . $_POST["type"] . ".php", ["title" => "Regjistrohu", "fields" => $_POST]); // shko tek fusha e moshes echo "<script>"; echo "document.getElementById('myForm').mosha.focus()"; echo "</script>"; return; } // shto perdoruesin e ri ne tabelen student if (query("INSERT INTO student (id, emri, gjinia, mosha, email, cel) VALUES (?, ?, ?, ?, ?, ?)", $rows[0]["id"], $_POST["emri"], $_POST["gjinia"], intval($_POST["mosha"]), $_POST["email"], $_POST["cel"]) === false) { apologize("Nuk mund të regjistroheni për momentin. Provoni sërish më vonë."); } } else { if ($_POST["type"] == "kompani") { // shto perdoruesin e ri ne tabelen kompani if (query("INSERT INTO kompani (id, emri_kompani, qyteti, adresa, email, cel, pershkrimi) VALUES (?, ?, ?, ?, ?, ?, ?)", $rows[0]["id"], $_POST["emri_kompani"], $_POST["qyteti"], $_POST["adresa"], $_POST["email"], $_POST["cel"], $_POST["pershkrimi"]) === false) { apologize("Nuk mund të regjistroheni për momentin. Provoni sërish më vonë."); } } } // nese cdo gje ka shkuar mire // regjistro perdoruesin per session-in aktual $_SESSION["id"] = $rows[0]["id"]; // kujto username $_SESSION["username"] = $_POST["username"]; // regjistro llojin e perdoruesit per kete session $_SESSION["type"] = $_POST["type"]; // shko tek faqja kryesore redirect("/");
<?php require "../includes/config.php"; if (!isset($_POST["del_comm_id"])) { apologize("Comment not specified."); } session_start(); if (del_comment($_POST["del_comm_id"], $_GET["soc"], $_POST["del_comm_reason"]) === false) { apologize("Something went wrong."); } redirect("post.php?soc=" . $_GET["soc"] . "&pid=" . $_GET["pid"]);
<?php require '../includes/config.php'; if (!isset($_POST["symbol"])) { render('../templates/quote_form.php'); } else { // look up stock's symbol, name, price $stock = lookup($_POST["symbol"]); if ($stock === false) { apologize("invalid symbol"); } else { // get formatted price $price = number_format($stock['price'], 2); // render price render('../templates/display_stock.php', ["symbol" => $stock['symbol'], "name" => $stock['name'], "price" => $price]); } }
} else { if ($_SERVER["REQUEST_METHOD"] == "POST") { // check to make sure form is filled out correctly if (empty($_POST["username"])) { apologize("You must provide your username."); } else { if (empty($_POST["password"])) { apologize("You must provide your password."); } else { if ($_POST["password"] != $_POST["confirmation"]) { apologize("Two passwords do not match!"); } } } // check to make sure random uniqueID is actually unique do { $identifier = generateRandomID(); $checkuniqueID = CS50::query("SELECT * FROM users WHERE uniqueID = ?", $identifier); } while (!empty($checkuniqueID)); // check to see username was unique $test = CS50::query("INSERT IGNORE INTO users (username, hash, uniqueID, email) VALUES(?, ?, ?, ?)", $_POST["username"], password_hash($_POST["password"], PASSWORD_DEFAULT), $identifier, $_POST["email"]); if ($test == 0) { apologize("This username is taken!"); } else { $rows = CS50::query("SELECT LAST_INSERT_ID() AS id"); $id = $rows[0]["id"]; $_SESSION = $id; redirect("/"); } } }
// generate xml for post request $input['xml'] = update_xml($input); // send request using this input $response = submit_poll($input); // if unknown error... if($response == false) apologize("Sorry, an unknown error occurred. Please try again."); /*if user reaches this point, submission successful*/ } else // prevent user from jumping straight to this page apologize("Sorry, an error occurred. Please try again."); ?> <!DOCTYPE html> <html> <head> <link href="css/style.css" rel="stylesheet" type="text/css"> <title>Crimson Calendar Doodle Tool: Submitted!</title> </head> <body> <div class="logo"> <a href="index.php"><img id ="logo" src="extras/harvard-logo.jpg" alt="Crimson Calendar"><h1 class="logo_text">Crimson Calendar</h1></a> </div> <div class="border_hor"></div>
<?php // configuration require "../includes/config.php"; //get history info $rows = query("SELECT * FROM log WHERE id = ?", $_SESSION["id"]); if (empty($rows)) { apologize("Sorry- you have no history!"); } render("history_table.php", ["logs" => $rows, "title" => "History"]);
if ($_SERVER["REQUEST_METHOD"] == "POST") { // if username field was left empty if (empty($_POST["username"])) { apologize("Please provide a username."); } else { if (empty($_POST["password"])) { apologize("Please provide a password."); } else { if ($_POST["password"] != $_POST["confirmation"]) { apologize("Password and confirmation did not match."); } } } // else insert user into database $query = query("INSERT INTO users (username, hash, numcities) VALUES(?, ?, 0)", $_POST["username"], crypt($_POST["password"])); // if query fails if ($query === false) { apologize("Could not register user."); } else { // find id assigned to new user $rows = query("SELECT LAST_INSERT_ID() AS id"); $id = $rows[0]["id"]; // remember new user is logged in $_SESSION["id"] = $id; // redirect to portfolio redirect("/"); } } else { // else render form render("register_form.php", ["title" => "Register"]); }
} else { if (empty($_POST["confirmation"])) { apologize('Please confirm your password.'); return false; } else { if ($_POST["password"] != $_POST["confirmation"]) { apologize('Your password and confirmation don\'t match up.'); return false; } } } } //check if username already taken $rows = CS50::query("SELECT * FROM users WHERE username = ?", $_POST["username"]); if (count($rows) == 1) { apologize('Username already taken.'); return false; } else { //if all previous steps are successful, register user CS50::query("INSERT IGNORE INTO users (username, hash, cash) VALUES(?, ?, 10000.0000)", $_POST["username"], password_hash($_POST["password"], PASSWORD_DEFAULT)); //get id of user $rows = CS50::query("SELECT LAST_INSERT_ID() AS id"); $id = $rows[0]["id"]; //remember id in $_SESSION $_SESSION["id"] = $id; //remember username $_SESSION["username"] = $row["username"]; //remember balance $_SESSION["cash"] = $row["cash"]; //redirect to index.php redirect("/index.php");
* * * Code common to (i.e., required by) most pages. **********************************************************************/ // display errors and warnings but not notices ini_set("display_errors", true); error_reporting(E_ALL ^ E_NOTICE); // enable sessions, restricting cookie to /~username/pset7/ if (preg_match("{^(/~[^/]+/TJ/)}", $_SERVER["REQUEST_URI"], $matches)) { session_set_cookie_params(0, $matches[1]); } session_start(); //establishing time zone date_default_timezone_set('America/Sao_Paulo'); // requirements require_once "constants1.php"; require_once "helpers.php"; // require authentication for most pages if (!preg_match("{/(:?login|logout|register)\\d*\\.php\$}", $_SERVER["PHP_SELF"])) { if (!isset($_SESSION["id"])) { header("Location:login.php"); } } // connect to database server if (($connection = @mysql_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD)) === false) { apologize("Could not connect to database server."); } // select database if (@mysql_select_db(DB_NAME, $connection) === false) { apologize("Could not select database (" . DB_NAME . ")."); }
$shares = $_POST["shares"]; if (preg_match("/^\\d+\$/", $shares) == false) { apologize("You must enter a whole number!"); } elseif ($shares <= 0) { apologize("Enter a number greater than zero!"); } $symbol = strtoupper($_POST["symbol"]); $id = $_SESSION["id"]; $action = "BUY"; // get a quote for the requested share $quote = lookup($symbol); if (!$quote) { apologize("Symbol not found!"); } // users are unique so select the first row [0] $user = cs50::query("SELECT * FROM users WHERE id = ?", $id)[0]; $value = $shares * $quote["price"]; $cash_available = $user["cash"]; if ($value > $cash_available) { apologize("You don't have enough cash!"); } // add purchase to user's portfolio cs50::query("INSERT INTO portfolios (user_id, symbol, shares) VALUES (?, ?, ?)\n ON DUPLICATE KEY UPDATE shares = shares + ?", $id, $symbol, $shares, $shares); // set user's cash to reflect purchase cs50::query("UPDATE users SET cash = cash - ? WHERE id = ?", $value, $id); // add purchase information into history cs50::query("INSERT INTO history (date, action, user_id, symbol, shares, price) \n VALUES (NOW(), ?, ?, ?, ?, ?)", $action, $id, $symbol, $shares, $quote["price"]); // redirect user back to their porfolio redirect("/"); } }
if ($_SERVER["REQUEST_METHOD"] == "GET") { render("buy_form.php", ["title" => "Sell"]); } else { if ($_SERVER["REQUEST_METHOD"] == "POST") { if (!preg_match("/^\\d+\$/", $_POST['quantity'])) { apologize("Sale canceled. You can only buy whole shares, please indicate a positive integer"); } if (lookup($_POST["symbol"]) === false) { apologize("Sale canceled. Please choose a valid stock symbol"); } $sharearray = lookup(strtoupper($_POST["symbol"])); $stock = strtoupper($_POST["symbol"]); $idrows = query("SELECT * FROM users WHERE id = ?", $_SESSION["id"]); $saleprice = moneyformat($sharearray["price"] * $_POST["quantity"]); if ($saleprice > $idrows[0]['cash']) { apologize("Sale canceled. Poor you! you don't have enough money to buy these shares of " . $_POST["symbol"]); } else { query("INSERT INTO portfolio (id, symbol, shares) VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE shares = \n shares + VALUES(shares)", $_SESSION["id"], "{$stock}", $_POST["quantity"]); $newbalance = $idrows[0]['cash'] - $saleprice; query("UPDATE users SET cash = ? WHERE id = ?", $newbalance, $_SESSION["id"]); query("INSERT INTO history (id, symbol, soldorbought, number, price) VALUES (?, ?, 0, ?, ?)", $_SESSION["id"], "{$stock}", $_POST["quantity"], $saleprice); redirect("/"); } } } ?>
<?php // configuration require "../includes/directory_functions.php"; // delete the person if (delete_person($_GET['id']) === false) { apologize("There was an error deleting the entry"); } // redirect to home page redirect("/");
if (empty($_POST["cantidad"])) { apologize("¡Debes ingresar una cantidad!"); } else { // insertar un nuevo usuario a la base de datos $stock = lookup($_POST["simbolo"]); if ($stock === false) { apologize("¡El simbolo es incorrecto!"); } else { if (preg_match("/^\\d+\$/", $_POST["cantidad"])) { $filas = query("SELECT cash FROM users WHERE id = ?", $_SESSION["id"]); // calcular el costo $costo = $stock["price"] * $_POST["cantidad"]; // verificar cantidad de cash if ($costo > $filas[0]["cash"]) { apologize("¡No Tiene sufuciente cash!"); } else { $_POST["simbolo"] = strtoupper($_POST["simbolo"]); query("INSERT INTO portfolios (id, simbolo, shares) VALUES (?, ? ,?)\n\t\t\t\t\tON DUPLICATE KEY UPDATE shares = shares + VALUES(shares)", $_SESSION["id"], $_POST["simbolo"], $_POST["cantidad"]); query("UPDATE users SET cash = cash - ? WHERE id = ?", $stock["price"] * $_POST["cantidad"], $_SESSION["id"]); // Actualizar historial query("INSERT INTO historial (id, transaccion, simbolo, shares, precio) VALUES (?, ? ,?, ?, ?)", $_SESSION["id"], "COMPRA", $_POST["simbolo"], $_POST['cantidad'], $stock["price"]); } } else { apologize("Debes ingresar una cantidad correcta"); } } redirect("/"); } } } }
// configuration require "../includes/config.php"; // if user reached page via GET (as by clicking a link or via redirect) if (empty($_SESSION["id"])) { apologize("You don't have the proper authorization to access this page..."); } if ($_SERVER["REQUEST_METHOD"] == "GET" && empty($_GET["match_id"])) { $matches = CS50::query("SELECT * FROM matches"); render("remove_scores_view.php", ["title" => "Remove Scores", "matches" => $matches, "sport_map" => $sport_map]); } else { if ($_SERVER["REQUEST_METHOD"] == "GET") { $remove = CS50::query("SELECT * FROM matches WHERE id = ?", $_GET["match_id"]); if ($remove == false) { apologize("No match found."); } $college_names = "BK, BR, CC, DC, ES, JE, MC, PC, SM, SY, TC, TD"; foreach ($remove[0] as $key => $value) { if (strpos($college_names, $key) !== false) { CS50::query("UPDATE stats SET total = total - ?," . $remove[0]["sport"] . " = " . $remove[0]["sport"] . " - ? WHERE college = ?", $value, $value, $key); } } if (CS50::query("DELETE FROM matches WHERE id = ?", $_GET["match_id"]) == false) { apologize("Error deleting match from database"); } render("score_removed.php", ["title" => "Success"]); } } ?>
<?php /** * json.php * sample test to generate json data from balance databases */ // configuration require "../includes/config.php"; $users = []; // search database $search = query("SELECT trans_name, trans_sub_cat, trans_amount, trans_time FROM `transactions` WHERE `id` = ? AND trans_category = 'income'", $_SESSION["id"]); if ($search === false) { apologize("Error fetching income transactions"); } foreach ($search as $value) { $users[] = ["trans_name" => $value["trans_name"], "trans_sub_cat" => $value["trans_sub_cat"], "trans_amount" => $value["trans_amount"], "trans_time" => date('D d M Y', strtotime($value["trans_time"]))]; } // output as JSON header("Content-type: application/json"); print json_encode($users, JSON_PRETTY_PRINT);
require "../includes/config.php"; // get the user's current password for validation $id = $_SESSION["id"]; $hash = cs50::query("SELECT hash FROM users WHERE id = ?", $id)[0]["hash"]; if ($_SERVER["REQUEST_METHOD"] == "GET") { render("password_change_form.php", ["title" => "Password Change"]); } else { if ($_SERVER["REQUEST_METHOD"] == "POST") { // validate form input if (empty($_POST["password"])) { apologize("You must enter your current password!"); } else { if (!password_verify($_POST["password"], $hash)) { apologize("Your password is incorrect!"); } else { if (empty($_POST["new_password"])) { apologize("You must provide a new password!"); } else { if (!($_POST["new_password"] == $_POST["confirmation"])) { apologize("Your passwords do not match!"); } else { // update the current user's password hash cs50::query("UPDATE users SET hash = ? WHERE id = ?", password_hash($_POST["new_password"], PASSWORD_DEFAULT), $id); success("Your password has been changed!"); } } } } } }
<?php require "../includes/config.php"; // if user reached page via GET (as by clicking a link or via redirect) if (!isset($_GET['upvote'])) { apologize("You didn't enter anything!"); } else { // set variables $id = $_GET['id']; $new = 0; // increment upvote by 1 $new = $_GET['upvote'] + 1; $s = "UPDATE posts SET upvotes={$new} WHERE id={$id}"; // update upvotes for the post CS50::query("UPDATE posts SET upvotes='" . $new . "' WHERE id='" . $id . "'"); } // forces URL change so browser obtains latest data $millitime = round(microtime(true) * 1000); header("Location: /financial_aid.php?UTC={$millitime}&NEW={$new}&SQL={$s}");
<?php // configuration require "../includes/config.php"; // if file form was submitted if ($_SERVER["REQUEST_METHOD"] == "POST") { if (empty($_POST["symbol"])) { // inform registrants of their error apologize("You must select a stock to sell."); } else { // look for the current price of the stock $stock = lookup($_POST["symbol"]); // look for number of shares of this stock $shares = query("SELECT shares FROM portfolios WHERE id = ? AND symbol = ?", $_SESSION["id"], strtoupper($_POST["symbol"])); // add selling stock to the history query("INSERT INTO history (id, transaction, time, symbol, shares, price) VALUES (?, ?, CURRENT_TIMESTAMP, ?, ?, ?)", $_SESSION["id"], "SELL", strtoupper($_POST["symbol"]), $shares[0]["shares"], $stock["price"]); // update the cash query("UPDATE users SET cash = cash + ? WHERE id = ?", $stock["price"] * $shares[0]["shares"], $_SESSION["id"]); // remove that stock from the portfolio query("DELETE FROM portfolios WHERE id = ? AND symbol = ?", $_SESSION["id"], $_POST["symbol"]); redirect("/"); } } else { // stores all the symbols user owes $rows = query("SELECT symbol FROM portfolios WHERE id = ?", $_SESSION["id"]); // render to sell_form passing symbols user owes render("sell_form.php", ["rows" => $rows, "title" => "Sell"]); }
<?php // configuration require "../includes/config.php"; // if user reached page via GET (as by clicking a link or via redirect) if ($_SERVER["REQUEST_METHOD"] == "POST") { //insert the posted message into the database. if (CS50::query("INSERT INTO messages (match_id, sender_id, message) VALUES(?, ?, ?)", $_SESSION["temp_match"], $_SESSION["id"], $_POST["message"]) == 0) { apologize("could not upload message to database"); } } //regardless of whether we had to insert a new message, render current messages. $messages = CS50::query("SELECT * FROM messages WHERE match_id = ?", $_SESSION["temp_match"]); render("match_chat.php", ["title" => "Match Profile", "messages" => $messages, "chat_buddy" => $_SESSION["chat_buddy"]]);
<?php // configuration require "../includes/config.php"; // if user reached page via GET (as by clicking a link or via redirect) if ($_SERVER["REQUEST_METHOD"] == "GET") { // else render form render("register_form.php", ["title" => "Register"]); } else { if ($_SERVER["REQUEST_METHOD"] == "POST") { // TODO if (empty($_POST["username"]) || empty($_POST["password"])) { apologize("please provide both username and password"); exit; } else { if ($_POST["password"] != $_POST["confirmation"]) { apologize("password's do not match"); exit; } else { if (query("INSERT INTO users (username, hash, cash) VALUES(?, ?, 10000.00)", $_POST["username"], crypt($_POST["password"])) === false) { apologize("username already exist"); exit; } $rows = query("SELECT LAST_INSERT_ID() AS id"); $id = $rows[0]["id"]; $_SESSION["id"] = $id; redirect("index.php"); } } } }
if (empty($_POST["confirmation"])) { apologize("You must provide a password confirmation."); } else { if ($_POST["newPassword"] != $_POST["confirmation"]) { apologize("Your new password and confirmation must be matching."); } } } } } // query database for user $rows = query("SELECT * FROM users WHERE username = ?", $_POST["username"]); // if we found user, check password if (count($rows) == 1) { // first (and only) row $row = $rows[0]; // compare hash of user's input against hash that's in database if (crypt($_POST["oldPassword"], $row["hash"]) == $row["hash"]) { // Change password in SQL query("UPDATE users SET hash = ? WHERE id = ?", crypt($_POST["newPassword"]), $_SESSION["id"]); // redirect to portfolio redirect("/"); } } // else apologize apologize("Invalid username and/or password."); } else { if ($_SERVER["REQUEST_METHOD"] == "GET") { render("changePswrd_form.php", ["title" => "ChangePswrd"]); } }
if ($_SERVER["REQUEST_METHOD"] == "POST") { $name = $_POST["name"]; $cell = $_POST["cell"]; $email = $_POST["email"]; // update information in database if (!empty($name)) { CS50::query("UPDATE users SET name = ? WHERE userid = ?", $name, $_SESSION["id"]); if (!empty($cell)) { CS50::query("UPDATE users SET cell_number = ? WHERE userid = ?", $cell, $_SESSION["id"]); if (!empty($email)) { CS50::query("UPDATE users SET email = ? WHERE userid = ?", $email, $_SESSION["id"]); } } } else { if (!empty($cell)) { CS50::query("UPDATE users SET cell_number = ? WHERE userid = ?", $cell, $_SESSION["id"]); if (!empty($email)) { CS50::query("UPDATE users SET email = ? WHERE userid = ?", $email, $_SESSION["id"]); } } else { if (!empty($email)) { CS50::query("UPDATE users SET email = ? WHERE userid = ?", $email, $_SESSION["id"]); } else { apologize("Please choose one to submit."); } } } // redirect redirect("/update_info.php"); } }
render("buy.php"); } else { if ($_SERVER["REQUEST_METHOD"] == "POST") { if (empty($_POST["symbol"])) { apologize("Something went wrong"); } $stock = lookup($_POST["symbol"]); if ($stock === false) { apologize("Error ocurred - there are no shares with that symbol."); } if (!preg_match("/^\\d+\$/", $_POST["shares"])) { apologize("You can't buy fractions of shares or non-positive number of shares."); } $money = query("SELECT cash FROM users WHERE id =?", $_SESSION["id"]); if ($_POST["shares"] * $stock["price"] > $money[0]["cash"]) { apologize("I'm sorry, you can't afford so many shares."); } $_POST["symbol"] = strtoupper($_POST["symbol"]); date_default_timezone_set('Europe/Warsaw'); $time = date('Y-m-d H:i:s'); query("INSERT INTO usersStocks (id, symbol, shares) VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE shares = shares + ?", $_SESSION["id"], $_POST["symbol"], $_POST["shares"], $_POST["shares"]); query("UPDATE users SET cash = cash - ? WHERE id =?", $_POST["shares"] * $stock["price"], $_SESSION["id"]); query("INSERT INTO history (id, symbol, shares, transaction, price, time) VALUES (?, ?, ?, 'BUY', ?, ?)", $_SESSION["id"], $_POST["symbol"], $_POST["shares"], $stock["price"], $time); $users = query("SELECT * FROM users WHERE id =?", $_SESSION["id"]); $address = $users[0]["mail"]; require_once "libphp-phpmailer/class.phpmailer.php"; $mail = new PHPMailer(); $mail->IsSMTP(); $mail->Host = "mail.upcpoczta.pl"; $mail->SetFrom("*****@*****.**"); $mail->AddAddress("{$address}");
// validate inputs if (empty($_POST["username"])) { apologize("You must provide a username."); } else { if (empty($_POST["password"])) { apologize("You must provide a password."); } else { if (empty($_POST["confirmation"]) || $_POST["password"] != $_POST["confirmation"]) { apologize("Those passwords did not match."); } } } // try to register user $rows = CS50::query("INSERT IGNORE INTO users (username, hash) VALUES(?, ?)", $_POST["username"], password_hash($_POST["password"], PASSWORD_DEFAULT)); if ($rows !== 1) { apologize("That username appears to be taken."); } // get new user's ID $rows = CS50::query("SELECT LAST_INSERT_ID() AS id"); if (count($rows) !== 1) { apologize("Can't find your ID."); } $id = $rows[0]["id"]; // log user in $_SESSION["id"] = $id; // redirect to portfolio redirect("/"); } else { // else render form render("register_form.php", ["title" => "Register"]); }