I know separately these questions are quite common although I have searched around for usable answers and am not having much luck finding a lot of information for MySQLi or the new PHP version. Hopefully one of you experts might be able to help me out.
I have a 'simple' html form running a PHP script to the database, which seems to work perfectly, also includes a file upload, which also works. I have some knowledge over security and protection and I am pretty sure my script isn't at all secure. I am also have problems displaying anything if the script doesn't run properly.
I attempted to add a code such as:
} else {
header('Location: addpcn.php?pcnerror=4');
}
Although there are so many '}' at the end of my code, I am not sure where to add it. Also, there are a lot of issues I may be forgetting to alert the user if the code is unsuccessful and the error would never be displayed?
Here is my code so far:
if(isset($_POST['pcn'])){
$pcn_number = $_POST['pcn_number'];
$vehicle_reg = $_POST['vehicle_reg'];
$street_name = $_POST['street_name'];
$offence = $_POST['offence'];
$vehicle_make = $_POST['vehicle_make'];
$vehicle_model = $_POST['vehicle_model'];
$vehicle_colour = $_POST['vehicle_colour'];
$date_issued = $_POST['date_issued'];
$time_issued = $_POST['time_issued'];
$witnessed_from = $_POST['witnessed_from'];
$witnessed_to = $_POST['witnessed_to'];
$issued_by = $_POST['issued_by'];
$target_dir = "evidence/";
$target_file = $target_dir . basename($_FILES["evidence"]["name"]);
$name = $_FILES["evidence"]["name"];
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
$check = getimagesize($_FILES["evidence"]["tmp_name"]);
if($check !== false) {
$uploadOk = 1;
} else {
$uploadOk = 0;
}
// Check if file already exists
if (file_exists($target_file)) {
$uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo '';
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["evidence"]["tmp_name"], $target_file)) {
echo '';
} else {
echo '';
}
}
if(empty($pcn_number) === true){
header('Location: addpcn.php?pcnerror=2');
} else {
if(empty($vehicle_reg) === true){
header('Location: addpcn.php?pcnerror=2');
} else {
if(empty($street_name) === true){
header('Location: addpcn.php?pcnerror=2');
} else {
if(empty($offence) === true){
header('Location: addpcn.php?pcnerror=2');
} else {
if(empty($vehicle_make) === true){
header('Location: addpcn.php?pcnerror=2');
} else {
if(empty($vehicle_colour) === true){
header('Location: addpcn.php?pcnerror=2');
} else {
if(empty($date_issued) === true){
header('Location: addpcn.php?pcnerror=2');
} else {
if(empty($time_issued) === true){
header('Location: addpcn.php?pcnerror=2');
} else {
if(empty($witnessed_from) === true){
header('Location: addpcn.php?pcnerror=2');
} else {
if(empty($witnessed_to) === true){
header('Location: addpcn.php?pcnerror=2');
} else {
if(empty($issued_by) === true){
header('Location: addpcn.php?pcnerror=2');
} else {
mysqli_query($conn, "INSERT INTO parkingtickets (id, pcn_number, date_issued, vehicle_reg, vehicle_make, vehicle_model, vehicle_colour, street_name, witnessed_from, witnessed_to, time_issued, offence, issued_by, special_fine_discount, special_fine, paid, paid_date, evidence) VALUES ('','$pcn_number', '$date_issued', '$vehicle_reg', '$vehicle_make', '$vehicle_model', '$vehicle_colour', '$street_name', '$witnessed_from', '$witnessed_to', '$time_issued', '$offence', '$issued_by', '', '', '0', '', '$name')");
header('Location: addpcn.php?pcnerror=3');
}
}
}
}
}
}
}
}
}
}
}
}
I know that you guys will see it as the wrong way to go about it, but I'm still a novice, and hopefully you'll be able to point me in the right direction with a few better examples as error reporting for this code as well as MySQLi injection prevention could be improved drastically.
Thanks!
I made some changes at your code. For consistency i used underscore for all variables and not the camelCase convention. Same for table name in database (parking_tickets).
It is a good practice to validate your inputs so if one of them isn't of correct type you will be able to show info messages for it.
Also, i used associative arrays instead of multiple if statements.
Thanks to # Scott Arciszewski i added the prepared statements with the difference i omit the paid column so make sure it has 0 as default value in your database.
if (isset($_POST['pcn'])) {
$pcn_number = $_POST['pcn_number'];
$vehicle_reg = $_POST['vehicle_reg'];
$street_name = $_POST['street_name'];
$offence = $_POST['offence'];
$vehicle_make = $_POST['vehicle_make'];
$vehicle_model = $_POST['vehicle_model'];
$vehicle_colour = $_POST['vehicle_colour'];
$date_issued = $_POST['date_issued'];
$time_issued = $_POST['time_issued'];
$witnessed_from = $_POST['witnessed_from'];
$witnessed_to = $_POST['witnessed_to'];
$issued_by = $_POST['issued_by'];
//User input validation chekcs
$is_valid = true;
//e.g
if (!(is_numeric((int)$pcn_number) && ctype_digit((string)$pcn_number))) {
$is_valid = false;
echo 'The pcn_number is not valid. It must be an integer.';
}
if (!(is_numeric((int)$vehicle_reg) && ctype_digit((string)$vehicle_reg))) {
$is_valid = false;
echo 'The vehicle_reg is not valid. It must be an integer.';
}
if (!$is_valid) {
//Do something here and dont continue if one of the inputs is not valid
}
$target_dir = "evidence/";
$target_file = $target_dir . basename($_FILES["evidence"]["name"]);
$name = $_FILES["evidence"]["name"];
$upload_ok = true;
$image_file_type = pathinfo($target_file, PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
$check = getimagesize($_FILES["evidence"]["tmp_name"]);
if ($check !== false) {
$upload_ok = true;
} else {
$upload_ok = false;
}
// Check if file already exists
if (file_exists($target_file)) {
$upload_ok = false;
}
// Allow certain file formats
$valid_formats = array('jpg', 'png', 'jpeg', 'gif');
if (!in_array($image_file_type, $valid_formats)) {
$upload_ok = false;
}
// Check if $uploadOk is set to false by an error
if ($upload_ok === false) {
echo '';
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["evidence"]["tmp_name"], $target_file)) {
echo '';
} else {
echo '';
}
}
$checks = array(
array (
'var'=>$pcn_number,
'condition'=>true,
'location'=>'addpcn.php?pcnerror=2'
),
array (
'var'=>$vehicle_reg,
'condition'=>true,
'location'=>'addpcn.php?pcnerror=2'
),
/*
* More elements here
*/
);
foreach($checks as $key => $value) {
if (empty($value['var']) === $value['condition'] ) {
header('Location: '.$value['location']);
exit;
}
}
$connection = mysqli_connect('localhost', 'root', 'your_password', 'your_database');
mysqli_set_charset($connection, 'utf8');
if (!$connection) {
die("Database connection failed: " . mysqli_error());
}
$stmt = mysqli_prepare($connection, "INSERT INTO parking_tickets (pcn_number, date_issued, vehicle_reg, vehicle_make, vehicle_model, vehicle_colour, street_name, witnessed_from, witnessed_to, time_issued, offence, issued_by, evidence) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?");
if (mysqli_stmt_bind_param($stmt, 'sssssssssssss', $pcn_number, $date_issued, $vehicle_reg, $vehicle_make, $vehicle_model, $vehicle_colour, $street_name, $witnessed_from, $witnessed_to, $time_issued, $offence, $issued_by, $name)) {
mysqli_stmt_execute($stmt);
header('Location: addpcn.php?pcnerror=3');
exit;
}
}
Related
I tried to upload video filenames and other variables to the database, but the insert statement won't work. Anyway the videofile-name and the thumbnail-filename are both uploaded to the right folders.
I've checked and there's nothing wrong with the sql statement. But why won't it work can anyone tell me?
PHP code
<?php
session_start();
if (isset($_POST['submit'])) {
$videoName = $_POST['videoName'];
$videoDesc = $_POST['description'];
$category = $_POST['category'];
$level = $_POST['level'];
$userId = $_SESSION['userId'];
$videoFile = $_FILES["videoFile"];
$videoFileName = $videoFile['name'];
$videoFileType = $videoFile['type'];
$videoFileTempName = $videoFile['tmp_name'];
$videoFileError = $videoFile['error'];
$videoFileExt = explode(".", $videoFileName);
$videoFileActualExt = strtolower(end($videoFileExt));
$videoAllowed = array("mp4", "mov", "avi");
$thumbFile = $_FILES["thumbnail"];
$thumbFileName = $thumbFile["name"];
$thumbFileType = $thumbFile["type"];
$thumbFileTempName = $thumbFile["tmp_name"];
$thumbFileError = $thumbFile["error"];
$thumbFileExt = explode(".", $thumbFileName);
$thumbFileActualExt = strtolower(end($thumbFileExt));
$thumbAllowed = array("jpg", "jpeg", "png");
if (in_array($videoFileActualExt, $videoAllowed)) {
if(in_array($thumbFileActualExt, $thumbAllowed)) {
if ($videoFileError === 0) {
if ($thumbFileError === 0) {
$videoFullName = $videoFile . "." . uniqid("", true) . "." . $videoFileActualExt;
$videoFileDestination = "../video/" . $videoFullName;
$thumbFullName = $thumbFile . "." . uniqid("", true) . "." . $thumbFileActualExt;
$thumbFileDestination = "../thumbnail/" . $thumbFullName;
include 'dbh.inc.php';
if(empty($videoName) or empty($videoDesc)) {
header("Location: ../uploadVideo.php?upload=empty");
exit();
} else {
move_uploaded_file($videoFileTempName, $videoFileDestination);
move_uploaded_file($thumbFileTempName, $thumbFileDestination);
$sql = "INSERT INTO video (filnavn, thumbnail, videoName, descript, idMusician, categoryName, idLevel) VALUES ('$videoFullName', '$thumbFullName', '$videoName', '$videoDesc', $userId, '$category', $level);";
mysqli_query($conn, $sql);
header("Location: ../uploadVideo.php?upload=success");
exit();
}
} else {
echo "You had a thumbnail error!";
exit();
}
} else {
echo "You had a video error!";
exit();
}
} else {
echo "You need to upload a proper thumbnail file type";
exit();
}
} else {
echo "You need to upload a proper video file type!";
exit();
}
} else {
}
You cannot insert or in this way in the if() condition, you must always use the logical operator as
if(empty($videoName) || empty($videoDesc))
Because of that your execution of code must have stopped at that point.
I'm getting the error message when uploading a form in php.
"You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near"
I've followed instructions from other posts as follows, to no avail:
1-Wrapped the column heading names in backticks.
2-Made sure all strings were passed as strings, and ints as ints.
3-Cleaned up any strings before sending out.
4-Made sure the connection to the database works and we can query from it.
5-Checked and re-checked my html code.
Here's my php code:
<?php
include('../config/config.php');
// Redirect browser if the upload form WAS NOT submited.
if (!isset($_POST['submit_upload']))
{
header("location: upload.html");
}
// Continue if the upload form WAS SUBMITED
else
{
// Set the upload directory path
$target_path = realpath( dirname( __FILE__ ) ) . "/uploads/audio/";
// Array to store validation errors
$error_msg = array();
// Validation error flag, if this becomes true we won't upload
$error_flag = false;
// We get the data from the upload form
$filename = $_FILES['file']['name'];
$temp_filename = $_FILES['file']['tmp_name'];
$filesize = $_FILES['file']['size'];
$mimetype = $_FILES['file']['type'];
// Convert all applicable characters to HTML entities
$filename = htmlentities($filename);
$mimetype = htmlentities($mimetype);
// Check for empty file
if ($filename == "")
{
$error_msg[] = 'No file selected!';
$error_flag = true;
}
// Check the mimetype of the file
if ($mimetype != "audio/x-mp3" && $mimetype != "audio/mp3")
{
$error_msg[] = 'The file you are trying to upload does not contain expected data.
Are you sure that the file is an MP3 one?';
$error_flag = true;
}
// Get the file extension, an honest file should have one
$ext = substr(strrchr($filename, '.') , 1);
if ($ext != 'mp3')
{
$error_msg[] = 'The file type or extention you are trying to upload is not allowed!
You can only upload MP3 files to the server!';
$error_flag = true;
}
// Check that the file really is an MP3 file by reading the first few characters of the file
$open = #fopen($_FILES['file']['tmp_name'], 'r');
$read = #fread($open, 3);
#fclose($open);
if ($read != "ID3")
{
$error_msg[] = "The file you are trying to upload does not seem to be an MP3 file.";
$error_flag = true;
}
// Now we check the filesize.
// The file size shouldn't include any other type of character than numbers
if (!is_numeric($filesize))
{
$error_msg[] = 'Bad filesize!';
$error_flag = true;
}
// If it is too big or too small then we reject it
// MP3 files should be at least 1MB and no more than 10 MB
// Check if the file is too large
if ($filesize > 10485760)
{
$error_msg[] = 'The file you are trying to upload is too large!
Please upload a smaller MP3 file';
$error_flag = true;
}
// Check if the file is too small
if ($filesize < 1048600)
{
$error_msg[] = 'The file you are trying to upload is too small!
It is too small to be a valid MP3 file.';
$error_flag = true;
}
// Function to sanitize values received from the form. Prevents SQL injection
function clean($conn, $str)
{
$str = #trim($str);
if (get_magic_quotes_gpc())
{
$str = stripslashes($str);
}
return mysqli_real_escape_string($conn, $str);
}
// Sanitize the POST values
$title = clean($conn, $_POST['title']);
$context = clean($conn, $_POST['context']);
$source = clean($conn, $_POST['source']);
$interviewer = clean($conn, $_POST['interviewer']);
$interviewee = clean($conn, $_POST['interviewee']);
$intervieweeAge = (int)$_POST['intervieweeAge'];
$geoRegion = clean($conn, $_POST['geoRegion']);
$language = clean($conn, $_POST['language']);
$recDate = clean($conn,$_POST['recDate']);
$keywords = $_POST['keywords'];
if ($title == '')
{
$error_msg[] = 'Title is missing';
$error_flag = true;
}
if ($interviewee == '')
{
$error_msg[] = 'Interviewee name/anonymous is missing';
$error_flag = true;
}
// If there are input validations, show errors
if ($error_flag == true)
{
foreach($error_msg as $c => $p) echo "Error " . $c . ": " . $p . "<br />";
}
// Else, all checks are done, move the file.
else
{
if (is_uploaded_file($temp_filename))
{
// Generate an uniqid
$uniqfilename = $interviewee . '_' . str_replace("_", "", $recDate) . '.mp3';
$filePath = '/uploads/audio/' . $uniqfilename;
// If the file was moved, change the filename
if (move_uploaded_file($temp_filename, $target_path . $uniqfilename))
{
// Again check that the file exists in the target path
if (#file_exists($target_path . $uniqfilename))
{
// Assign upload date to a variable
$upload_date = date("Y-m-d");
// Create INSERT query
$qry = "INSERT INTO FDM177_AUDIO_CLIPS (title,context,source,interviewer,interviewee,intervieweeAge,geoRegion,language,recDate,fileName,filePath)
VALUES('$title','$context','$source','$interviewer',$interviewee',$intervieweeAge,'$geoRegion','$language','$recDate','$uniqfilename','$filePath')";
$result = mysqli_query($conn, $qry) or die(mysqli_error($conn));
if ($result)
{
$id = mysqli_insert_id($conn);
echo "File uploaded. Now it is called :" . $uniqfilename . "<br />" . $date . "<br />";
}
else
{
echo "There was an error uploading the file, please try again!";
}
if(1) {
//if (is_array($keywords) || is_object($keywords)) {
foreach($keywords as $k) {
// $idQuery = "SELECT keyword_ID from KEYWORDS WHERE keywordName=" . $k";
$idQuery = mysqli_query($conn, "SELECT * FROM FDM177_KEYWORDS WHERE (`keywordName` LIKE '%".$k."%')") or die(mysql_error());
$matchingKArray = mysqli_fetch_array($idQuery);
$keyword_FK = $matchingKArray[keyword_ID];
// echo $kQuery;
echo $keyword_FK;
$qry = "INSERT INTO FDM177_JNCT_KWDS_CLIPS (keyword_FK, clip_FK)
VALUES ('$keyword_FK', '$id')";
$result = mysqli_query($conn, $qry);
if ($result)
{
echo 'inserted with keyword.' . $k . ' <br />';
}
}
}
else {
echo "keywords are missing";
}
}
}
else {
echo "There was an error uploading the file, please try again!";
}
}
else
{
echo "There was an error uploading the file, please try again!";
}
}
}
?>
The problem occurs at the first MYSQL query that starts as MYSQL query INSERT INTO FDM177_AUDIO_CLIPS...
What am I missing?
Thank you!
quotes breaking in one query '$interviewer',$interviewee',
$qry = "INSERT INTO FDM177_AUDIO_CLIPS
(title, context, source,interviewer, interviewee,
intervieweeAge,geoRegion,language,recDate,fileName,filePath)
VALUES
('$title', '$context', '$source', '$interviewer', '$interviewee',
$intervieweeAge,'$geoRegion','$language','$recDate','$uniqfilename','$filePath')";
I have a simple form for submitting some data into the MySQL DB. On local machine works just fine, but inside a Wordpress page template doesn't work anymore, without getting me any error. The form is inside a page "sitename.com/upload" and i get redirected after submit to the same page (as shown in the link bar), but with 404 page content. I tried without get_header();and get_footer();tags because I thought it may conflict with some variables from wp, but I got the same result.
Here is the code:
<?php function renderForm($name, $price, $error)
{
// if there are any errors, display them
if ($error != '')
{
echo '<div style="padding:4px; border:1px solid red; color:red;">'.$error.'</div>';
}
?>
***** LONG HTML FORM IS HERE *****
<?php
}
// connect to the database
include('connect-db.php');
// check if the form has been submitted. If it has, start to process the form and save it to the database
if (isset($_POST['submit']))
{
// get form data, making sure it is valid
$name = mysqli_real_escape_string($connection, htmlspecialchars($_POST['name']));
$price = mysqli_real_escape_string($connection, htmlspecialchars($_POST['price']));
$shortdesc = mysqli_real_escape_string($connection, htmlspecialchars($_POST['shortdesc']));
$longdesc = mysqli_real_escape_string($connection, htmlspecialchars($_POST['longdesc']));
$current_version = mysqli_real_escape_string($connection, htmlspecialchars($_POST['current-version']));
$content_rating = $_POST['contentrating'];
if(isset($_POST['category'])) {
$category = implode(",", $_POST['category']);
} else {
$category = "";
}
if(isset($_POST['platform'])) {
$platform = implode(",", $_POST['platform']);
} else {
$platform = "";
}
if(isset($_POST['devices'])) {
$devices = implode(",", $_POST['devices']);
} else {
$devices = "";
}
if(isset($_POST['gamemodes'])) {
$gamemodes = implode(",", $_POST['gamemodes']);
} else {
$gamemodes = "";
}
//FILE UPLOAD
$images = array();
if(isset($_FILES['files'])){
$errors= array();
foreach($_FILES['files']['tmp_name'] as $key => $tmp_name ){
$file_name =$_FILES['files']['name'][$key];
$file_size =$_FILES['files']['size'][$key];
$file_tmp =$_FILES['files']['tmp_name'][$key];
$file_type=$_FILES['files']['type'][$key];
if($file_size > 2097152){
$errors[]='File size must be less than 2 MB';
}
$desired_dir="uploads/images";
if(empty($errors)==true){
if(is_dir($desired_dir)==false){
mkdir("$desired_dir", 0700); // Create directory if it does not exist
}
if(is_dir("$desired_dir/".$file_name)==true){
move_uploaded_file($file_tmp,"uploads/images/".$file_name);
}else{ //rename the file if another one exist
$file_name = time()."-".$file_name;
$new_dir="uploads/images/".$file_name;
rename($file_tmp,$new_dir) ;
}
$images[] = $file_name;
}else{
print_r($errors);
}
}
if(empty($error)){
$imglinks = implode(" | ", $images);
}
}
//FILE UPLOAD END
// check to make sure both fields are entered
if ($name == '' || $price == '')
{
// generate error message
$error = 'ERROR: Please fill in all required fields!';
// if either field is blank, display the form again
renderForm($name, $price, $error);
}
else
{
$sql = "INSERT INTO vr_submitted_apps ". "(name, price, shortdesc, longdesc, crtvers, rating, category, platform, devices, gamemodes, images, dtime) ". "VALUES('$name','$price','$shortdesc','$longdesc','$current_version','$content_rating','$category','$platform','$devices','$gamemodes', '$imglinks', NOW())";
// save the data to the database
mysqli_query( $connection, $sql )
or die(mysql_error());
$itemId = mysqli_insert_id($connection);
setcookie("last-inserted-id", $itemId, time() + (86400 * 3), "/"); // 86400 = 1 day
// once saved, redirect back to the view page
header("Location: uploader.html");
}
}
else
// if the form hasn't been submitted, display the form
{
renderForm('','','');
}
Problem solved: Wordpress has something important internal reserved for "name" parameter.
I have a validation with some if/else statements.
<?php
if (isset($_POST["join"])) {
if ($userpoint < $lessonpoint) { //pt
echo "you need more points";
} //pt
else { //has enough point
if ($row['num'] > 0) { //check if user took this lesson
echo "you took this lesson before.";
} //check if user took this lesson ends
else { //then let him apply to database
//define post:
$postvalue = (int)$_POST["postvalue"];
//and check
if($postvalue == '' || $postvalue <= 0 || $postvalue > $minimumpostvalue || $postvalue == is_int($postvalue)) { //check post
echo "Error.";
} //checkpost ends.
else { //insert
$sql = "INSERT into etc... VALUES (?, ?, ?)";
if($sql){ //to another database
$artibir = "UPDATE etc.";
echo "Done.";
} // to another database
}//insert
} //let him apply
} //has enough point
} //if post isset join
?>
This works very well.
But I want to echo out another error message for this condition: $postvalue > $minimumpostvalue
While trying it I get lost inside the if/else statements.
Wherever I put new statement I'm having an error.
All variables are defined.
Where and how can I place $postvalue > $minimumpostvalue to echo a different error message?
<?php
if (isset($_POST["join"])) {
if ($userpoint < $lessonpoint) { //pt
echo "you need more points";
} //pt
else { //has enough point
if ($row['num'] > 0) { //check if user took this lesson
echo "you took this lesson before.";
} //check if user took this lesson ends
else { //then let him apply to database
//define post:
$postvalue = (int) $_POST["postvalue"];
//and check
if ($postvalue == '' || $postvalue <= 0 || $postvalue > $minimumpostvalue || $postvalue == is_int($postvalue)) { //check post
if ($postvalue > $minimumpostvalue) {
echo "Another Error.";
}
else {
echo "Error.";
}
} //checkpost ends.
else { //insert
$sql = "INSERT into etc... VALUES (?, ?, ?)";
if ($sql) { //to another database
$artibir = "UPDATE etc.";
echo "Done.";
} // to another database
} //insert
} //let him apply
} //has enough point
} //if post isset join
?>
This is another variation without exceptions.
As soon as $valid becomes false, it will skip the next validation.
<?php
$valid = true;
$error = '';
if ($valid && !isset($_POST["join"])) {
$error = 'Not a join post request';
$valid = false;
}
if ($valid && ($userpoint < $lessonpoint)) {
$error = 'You need more points';
$valid = false;
}
...
if($valid) {
// Database insert; redirect
} else {
// User error feedback
}
//and check
if ($postvalue > $minimumpostvalue) { //check exception
echo "Error 1.";
} elseif ($postvalue == '' || $postvalue <= 0 || $postvalue == is_int($postvalue)) { //check the rest
echo "Error 2.";
} //checkpost ends.
This is untested code, and more an example of how to avoid nested if statements.
The point is to find to state the conditions you have an error state early and exit as soon as you can, at best by throwing an exception and avoiding else statements.
For simplicity I used only \RunTimeException(), yet I would most likely define my own exception depending on the case. The exception then can be caught and depending on their type show a different error page.
/**
* #param int $postvalue
* #param int $minimumpostvalue
*/
function saveToDatabase($postvalue)
{
if ($postvalue == '' || $postvalue <= 0 || $postvalue == is_int($postvalue)) {
throw new \RuntimeException('Error 2');
}
$sql = "INSERT into etc... VALUES (?, ?, ?)";
if ($sql) {
$artibir = "UPDATE etc.";
}
}
if (!isset($_POST["join"])) {
throw new \RuntimeException('Not a join post request');
}
if ($userpoint < $lessonpoint) {
throw new \RuntimeException('You need more points');
}
$userHasTakenCourse = $row['num'] > 0;
if ($userHasTakenCourse) {
throw new \RuntimeException('User has already taken the course.');
}
$postvalue = (int) $_POST["postvalue"];
if ($postvalue > $minimumpostvalue) {
throw new \RuntimeException('Error 1');
}
saveToDatabase($postvalue);
i am trying to allow users to update their profile picture using this code.
require("../connection.php");
$imgName = $_FILES['pic']['name'];
$imgTmp = $_FILES['pic']['tmp_name'];
$imgtype = $_FILES['pic']['type'];
$imgSize = $_FILES['pic']['size'];
$maxFileSize = 200000;
$pic = "../uploads/" . $user_id . "_" . time() . $imgName;
if ($imgSize > $maxFileSize) {
$error = "size";
}
if ($imgType == "image/jpeg" || $imgType == "image/gif") {
$error .= "";
} else {
$error = "type";
}
if (file_exists($pic)) {
$error = "exists";
}
if ($error == "" && $imgName != "") {
move_uploaded_file($imgTmp, $pic);
mysql_query("UPDATE users SET pic = '$pic', WHERE username = '$username'");
if (!mysql_query($query, $connect)) {
die(mysql_error());
} else {
mysql_close($connect);
header('location:http://www.WEBSITE.co.uk/users/upload-pic-thanks.php');
}
} else {
header("Location:edit-pic-error.php?e=".$error);
}
and it gives me this in the address bar: edit-pic-error.php?e=type, however the file i am trying to upload is .jpg, and its smaller than the 20000kb allowance.
The table in my mysql database is called 'users', and the table row is called 'pic', its Varchar, 60, allow null ticked.
The table is not being updated with the new time stamped profile picture.
Please help.
Thanks very much
$imgtype = $_FILES['pic']['type'];
if ($imgType == "image/jpeg" || $imgType == "image/gif") {
$imgType vs. $imgtype, notice the case.