Skip to content

Instantly share code, notes, and snippets.

@N-Molham
Created February 9, 2015 17:22
Show Gist options
  • Save N-Molham/1c7ee6570a00171ed862 to your computer and use it in GitHub Desktop.
Save N-Molham/1c7ee6570a00171ed862 to your computer and use it in GitHub Desktop.
Handling inputs' errors - that is one way to go
<?php
$con = mysqli_connect( 'localhost' , 'root' , '' , 'market' );
// Inputs from post
$inputs = filter_input_array( INPUT_POST, $_POST, [
'kind' => FILTER_SANITIZE_STRING,
'salary' => FILTER_SANITIZE_NUMBER_FLOAT,
'advantage' => FILTER_SANITIZE_STRING,
] );
foreach ( $inputs as $input_name => $input_value )
{
// redirect if there are any invalid value
// Null values will be seen as empty value
if ( empty( $input_value ) )
safe_redirect( 'error_'. $input_name );
}
// create variables from inputs array in runtime
extract( $inputs );
// File input validation
$file = isset( $_FILES['file'] ) ? $_FILES['file'] : null;
if ( !$file )
safe_redirect( 'error_file_messing' );
// parse file data type
// return false if the file is not an image
$file_info = getimagesize( $file['tmp_name'] );
if ( !$file_info )
safe_redirect( 'error_image_file' );
// check image type
if ( !in_array( $file_info['mime'], [ 'image/jpeg', 'image/jpg', 'image/pjpeg', 'image/png' ] ) )
safe_redirect( 'error_image_type' );
// no file size !!!!! it is your choice
// generate unique file name to save with to void conflicts and file overwrite
$file_name = uniqid( 'img_' ) .'.'. pathinfo( $file['name'], PATHINFO_EXTENSION );
// save the file
$save_file = move_uploaded_file( $file['tmp_name'], 'image/'. $file_name );
if ( !$save_file )
safe_redirect( 'error_saving_file' );
// DB statement
$stmt = mysqli_prepare( $con, "INSERT INTO mobile VALUES ( '', ?, ?, ?, ? )" );
mysqli_stmt_bind_param( $stmt, "sdss", $kind, $salary, $advantage, $file_name );
// run command
if ( !mysqli_stmt_execute( $stmt ) )
safe_redirect( 'error_db' );
// all success
safe_redirect( 'data_inserted' );
/**
* Redirect to main page
* @param string $msg
* @return void
*/
function safe_redirect( $msg )
{
header( 'location: main1.php?msg='. $msg, true, 302 );
die();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment