Not working. Validation and sanitizing via PHP suddenly not working - php

I have a weird problem. First of all, before I did form validation via PHP, I could insert and display data ( I have at least 30 fields). Then after I did validation and sanitizing, suddenly I cannot insert and display data. After I remove some fields and columns in the database, which left me a few, now I can insert data and display data, but if I add more than lets say 5 or 6 fields, I cannot insert data. Please tell me what's wrong?
<?php
echo var_dump($_POST);
echo var_dump($_FILES);
print_r($_SESSION);
error_reporting(E_ALL);
ini_set("display_errors",1);
//define variables and define to null.
$adtitleError = $dcrptnError = $rmError = $advertnameError = $apE = "";
$adtitle = $dcrptn = $rm = $advertname = $ap = "";
//Retrieve the field values from registration form.
$adtitle = !empty($_POST ['adtitle']) ? trim($_POST['adtitle']) : null;
$dcrptn = !empty($_POST ['dcrptn']) ? trim($_POST['dcrptn']) : null;
$rm = !empty($_POST ['rm']) ? trim($_POST['rm']) : null;
$advertname = !empty($_POST ['advertname']) ? trim($_POST['advertname']) : null;
$ap = !empty($_POST ['adphone']) ? trim($_POST['adphone']) : null;
function test_input($data){
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
$formValid = true;
if(isset($_POST["submit"])){
//insert record
if($conn->connect_error)
{die("Connection failed:".$conn->connect_error);}
$id=isset($_POST['id'])?$_POST['id']:"";
//insert data
$statement = $conn->prepare("INSERT INTO useradvert(id,image1,adtitle,dcrptn,rm,advertname,adphone)VALUES (?,?,?,?,?,?,?)");
//bind param
$statement->bind_param("issssss",$id,$target_file,$adtitle,$dcrptn,$rm,$advertname,$ap);
$target_file=isset($_FILES['image'])?$_FILES['image']:"";
$adtitle=isset($_POST['adtitle'])?$_POST['adtitle']:"";
$dcrptn=isset($_POST['dcrptn'])?$_POST['dcrptn']:"";
$rm=isset($_POST['rm'])?$_POST['rm']:"";
$advertname=isset($_POST['advertname'])?$_POST['advertname']:"";
$ap=isset($_POST['adphone'])?$_POST['adphone']:"";
//bind the variables to be called at other places
if (empty($adtitle)){
$adtitleError = "Ad title is required. Select category to activate form.";
$formValid = false;
}else{
$adtitle = test_input($_POST["adtitle"]);
// check name only contains letters and whitespace
if (!preg_match('/^[a-zA-Z\s]{3,50}+$/', $adtitle)) {
$adtitleError = "Letters only & spaces,(min 3),e.g: a, A)";
$formValid = false;
}
}
if (empty($dcrptn)){
$dcrptnError = "Decsription is required. Select category to activate form.";
$formValid = false;
}
if (empty($rm)){
$rmError = "A value is required, e.g: 123000 or 12,300.00. Select category to activate form.";
$formValid = false;
}
else{
$rm = test_input($_POST["rm"]);
// check name only contains letters and whitespace
if (!preg_match('/^[0-9]+(?:\.[0-9]{1,13})?$/',$rm)) {
$rmError = "Invalid value.E.g: 123000.45. Select category to activate form.";
$formValid = false;
}
}
if (empty($advertname)){
$advertnameError = "Name is required. Select category to activate form.";
$formValid = false;
}
else{
$advertname = test_input($_POST["advertname"]);
// check name only contains letters and whitespace
if (!preg_match('/^[a-zA-Z\s]{3,50}+$/',$advertname)) {
$advertnameError = "Letters only & spaces,(min 3),(e.g: a, A). Select category to activate form.";
$formValid = false;
}
}
if (empty($ap)){
$apE = "Tel number is required. Select category to activate form.";
$formValid = false;
}
else{
$ap= test_input($_POST["adphone"]);
// check name only contains letters and whitespace
if (!preg_match('/^\d{9,11}+$/',$ap)) {
$apE = "Invalid tel no format.( E.g:0123456789). Select category to activate form.";
$formValid = false;
}
}
//image
$target_dir="uploads/";
$target_file=$target_dir.basename($_FILES["image1"]["name"]);
$uploadOk=1;
$imageFileType=pathinfo($target_file,PATHINFO_EXTENSION);
//script for targetfile -image
// Check if image or not
$check=getimagesize($_FILES["image1"]["tmp_name"]);
if($check!==false){
echo "File is an image - ".$check["mime"].".";
$uploadOk=1;
}else{
echo "File is not an image.";
$uploadOk=0;
}
// Check if file already exists
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOk=0;
}
// Check file size
if ($_FILES["image1"]["size"]>500000) {
echo "Sorry, your file is too large.";
$uploadOk=0;
}
// Allow certain file formats
if($imageFileType!="jpg"&&$imageFileType!="png"&&$imageFileType!="jpeg"
&&$imageFileType!="gif")
{
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk=0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk==0) {
echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
}else{
if (move_uploaded_file($_FILES["image1"]["tmp_name"],$target_file)) {
echo "The file ".basename($_FILES["image1"]["name"])."has been uploaded.";
}else{
echo "Sorry, there was an error uploading your file.";
}
}
if ($formValid){
$statement->execute();
header('Location: userpppp.php');
exit;
}
}
?>

Related

Upload Multiple Images with php & mysql

I need to upload multiple images with php and MySQL but every time I try to upload it's only upload 1 image to database but in the file (uploads\companies) it shown me 4 images
I tried, but I don't find any solution so if anyone can help me
This is my code
$name = $_POST['name'];
$field = $_POST['field'];
$address = $_POST['address'];
$email = $_POST['email'];
$description = $_POST['description'];
$phone = $_POST['phone'];
$mobile = $_POST['mobile'];
$mapLink = $_POST['maplink'];
// Image Details
$images = $_FILES['images'];
$imageName = $images['name'];
$imageSize = $images['size'];
$imageTmpName = $images['tmp_name'];
$imageType = $images['type'];
// Image Count
$imagecount = count($imageName);
// Check For Errors
$formErrors = [];
if(empty($name)) { $formErrors[] = 'Name Can Not Be Empty'; }
if(empty($address)) { $formErrors[] = 'Address Can Not Be Empty'; }
if(empty($description)) { $formErrors[] = 'Description Can Not Be Empty'; }
if(empty($field)) { $formErrors[] = 'Field Can Not Be Empty'; }
if(empty($email)) { $formErrors[] = 'Email Can Not Be Empty'; }
if(empty($phone)) { $formErrors[] = 'Phone Can Not Be Empty'; }
if(empty($mobile)) { $formErrors[] = 'Mobile Can Not Be Empty'; }
if(empty($mapLink)) { $formErrors[] = 'Map Link Can Not Be Empty'; }
// Loop Through Images
for($i = 0;$i < $imagecount;$i++) {
// Images Allowed Extension
$allowedExtension = ['jpg','jpeg','png'];
$imageExtensionExp = explode('.', $imageName[$i]);
$imageExtension = end($imageExtensionExp);
// Check Errors
if(empty($imageName[$i])) {
$formErrors[] = 'Image Can Not be Empty';
}
if(!empty($imageName[$i]) && !in_array($imageExtension, $allowedExtension)) {
$formErrors[] = 'This Extension Is Not Allowed';
}
if($imageSize[$i] > 5242880) { $formErrors[] = 'Size Can\'t be More 5 MB'; }
// Generate A Random Name
$imageNameStore = rand(0,10000000) . '_' . $imageName[$i];
move_uploaded_file($imageTmpName[$i], 'uploads\companies\\' . $imageNameStore);
}
// Print All Errors
if(!empty($formErrors)) {
echo '<div class="error-container">';
foreach ($formErrors as $error) {
echo '<h4>' . $error . '</h4>';
}
echo '</div>';
}
// Add To Database
if(empty($formErrors)) {
// Add Items To Database
/* $stmt = $conn->prepare("INSERT INTO
companies(Name, Field, Address, Email, Mobile, Phone, Description, Map,Images)
VALUES(?,?,?,?,?,?,?,?,?)");
$stmt->execute(array($name, $field,$address,$email,$mobile,$phone,$description,$mapLink, $imageNameStore));
*/
// Print Success Message
?>
<div class="container">
<div class="alert alert-success mt-5 text-center">Success, Company Added Successfully</div>
</div>
<?php
}
Initialize the following variable before the start of FOR Loop:
$imageNameStoreForDB='';
Add the following line code after your move_uploaded_file function before your for loop ends to concatenate all images' names:
$imageNameStoreForDB .= $imageNameStore." , ";
Replace the Query as below to use the new variable:
$stmt->execute(array($name, $field,$address,$email,$mobile,$phone,$description,$mapLink, $imageNameStoreForDB));
Note: It will save all images names in the DB separated by "," comma and if you wanna fetch the record then use explode function for images to separate each image.

Extecuting Query With The Condition in PHP

I have a page in which user can update their posts.
I need to update the database with different query(for different Conditions).
But every time I run update using this code, image filename changes automatically (even if I have a condition). Am I doing something wrong?
if(empty($up_image)){
$up_image = $image;
$update_query = "UPDATE posts SET title = '$up_title', image = '$up_image', categories = '$up_categories', tags = '$up_tags', post_data = '$up_post_data', status = '$up_status' WHERE id = $edit_id";
if(mysqli_query($con, $update_query)){
$msg = "Post has been Updated";
$path1 = "img/$up_image";
header("refresh:1;edit-post.php?edit=$edit_id");
if(move_uploaded_file($up_tmp_name, $path1)){
copy($path1, "../$path1");
}
}
else{
$error = "Unable to Update Post";
}
}
if(!empty($up_image)){
$up_image = preg_replace('/\s+/','',$up_image);
$image_size = $_FILES['image']['size'];
$allowed_img_ext = array("jpg", "jpeg", "png", "bmp");
$ext = pathinfo($up_image, PATHINFO_EXTENSION);
$trimed_img_name = pathinfo($up_image, PATHINFO_FILENAME);
if(in_array($ext, $allowed_img_ext))//check valid file extension
{
if($image_size < 2097152) {
$ren_image = substr($trimed_img_name,0,3)."".substr($title,0,11)."_".date("mj")."_".date("Y")."_".date("His").".".$ext;
$path = "img/".$ren_image;
$update_query = "UPDATE posts SET title = '$up_title', image = '$ren_image', categories = '$up_categories', tags = '$up_tags', post_data = '$up_post_data', status = '$up_status' WHERE id = $edit_id";
}
else{
$img_error = "Please Upload the Image File Size Less than 2 MB";
}
}
else{
$img_error = "Invalid Image File";
}
if(mysqli_query($con, $update_query)){
$msg = "Post has been Updated";
header("refresh:1;edit-post.php?edit=$edit_id");
if(move_uploaded_file($up_tmp_name, $path)){
copy($path, "../$path");
}
}
else{
$error = "Unable to Update Post";
}
} //End
So I removed $up_image = $image; and image = $up_image section from first query now it is working. Thanks for your comment

You have an error in your SQL syntax error message when inserting record

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')";

My code is showing no errmsg but is not inserting any data into database

So I am trying to make a simple e-commerce site. Once I submit the form (btn-submit), I am not able to insert any data to my database. Only the address and contact number verification works.
Here is my code:
if ( isset($_POST['btn-submit']) ) {
// clean user inputs
$oadd = trim($_POST['oadd']);
$oadd = strip_tags($oadd);
$oadd = htmlspecialchars($oadd);
$contact = trim($_POST['contact']);
$contact = strip_tags($contact);
$contact = htmlspecialchars($contact);
// address validation
if (empty($oadd)) {
$error = true;
$oaddError = "Please enter a valid address.";
} else if (strlen($oadd) < 5) {
$error = true;
$oaddError = "Please enter a valid address.";
}
// contact number validation
if (empty($contact)) {
$error = true;
$contactError = "Please enter your contact number.";
} else if (strlen($contact) < 7) {
$error = true;
$contactError = "Contact number must have atleast 7 digits.";
} else if (!preg_match("/^[0-9 ]+$/",$lname)) {
$error = true;
$lnameError = "Please enter a valid contact number.";
}
// if there's no error, continue to place order
if( !$error ) {
$query = 'INSERT INTO cust_order(Order_Date, Order_Status, Order_Total , Address, Contact_No) VALUES (CURDATE(), "in process" , (SELECT SUM(p.Product_Price) FROM cart c, product p WHERE c.Prod_ID = p.Product_ID and c. User_ID = "'.$userRow['User_ID'].'"),"'.$oadd.'","'. $contact.'")';
$res = mysql_query($query);
if ($res) {
$errTyp = "success";
$errMSG = "Your order has been placed. To view the details, go to your order history";
unset($oadd);
unset($contact);
} else {
$errTyp = "danger";
$errMSG = "Something went wrong. Please try again later.";
}
}
}
What could possibly be wrong with my code? I did similar queries in the other pages but this is the only one not working. Any help would be greatly appreciated! Thanks in advance!
Try to understand the code flow:
if( !$error ) {
// This will only works when **$error is false and the not of false is true**, otherwise this block does not execute
}
So this code works only when there is no validation error occurs in your code and $error contains false
//$userRow is not define any where...
//to check error occur or not :
echo $error;
if(!$error)
{
echo "IN IF";
//also go with die..
$res = mysql_query($query) or die();
}
else
{
echo "IN ELSE";
}

Form submit PHP code broken only in Wordpress

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.

Categories