Jump to content

mahenda

Members
  • Posts

    146
  • Joined

  • Last visited

Posts posted by mahenda

  1. I have a form on which the filepond plugin send the file manually
     and it generate the base64 formated data of that file, unfortunately
    Icant get it's previous name so i randomize the name, and put the file directry in the final folder, is there any problem on security?, can i validate if its an image with all property such as size,dimension e.t.c Before adding it the directory? and how to get the it's
    new name to database.

     

    Look here

    if(empty($_POST['image'])) {
        echo 'add file!';
    }
    $myimage = $_POST['image'];
    $myimage = str_replace('data:image/png;base64,', '', $myimage);
    $myimage = str_replace(' ', '+', $myimage);
    $decode = base64_decode($myimage);
    $myfile = $_SERVER['DOCUMENT_ROOT'].'/mages/' . uniqid() . '.png';
    //now put the file
    file_put_contents($myfile, $decode);

     

  2. /*I'm trying to use dropzone js plugin for drag/drop single phote but it require me to create another form for file upload, but i want to use single form for both image and name input, i have no idea on how to combine this field in sinle request, the form to submit both image and name look like*/
    <form method="POST" enctype="multipart/form-data">
    <input type="text" name="name" id="name">
    <!--how to replace this field with dropzone but in this form in order to use the same ajax as below-->
    <input type="file" name="photo" id="photo">
    <button type="submit">send</button>
    </form>
    
    
    //ajax, how to add dropzone data in
    $("form").on('submit', function(e) {
            $.ajax({
                url: 'add.php',
                type: 'POST',
                data: new FormData(this),
                dataType: 'JSON',
                contentType: false,
                cache: false,
                processData:false,
            }).done( function (data) {
                
                if(data.success == false) { //for error message response
    
                    if(data.errors.name) {
                        $('#name').append('<span class="text-danger">' + data.errors.name + '</span>');
                    }
    				if(data.errors.photo) {
                        $('#photo').append('<span class="text-danger">' + data.errors.photo + '</span>');
                    }
    
    			}
            });
            e.preventDefault();
        });
      

     

  3. On 5/3/2021 at 9:20 AM, Iooker said:

    Can anyone help me to fix this two error?

    #upload directory path
        $uploads_dir = '/images';
        #To move the uploaded file to specific location
        move_uploaded_file($tname, $uploads_dir.'/'.$pname);

    mysqli_select_db($conn, "test2") or die(mysql_error());

    Thank you !

     

    access to image folder

    $uploads_dir = $_SERVER['DOCUMENT_ROOT'].'/yourapp/image_folder/';

  4.  

    On 4/22/2021 at 12:36 PM, mac_gyver said:

    that's not the FromData object, as was mentioned, and the jquery .serialize() method doesn't include the file data.

    //i changed it like this and it works, the submit button look like <button type="submit">
    $("form").on('submit', function(e) {
            $.ajax({
                url: 'add.php',
                type: 'POST',
                data: new FormData(this),
                dataType: 'JSON',
                contentType: false,
                cache: false,
                processData:false,
            }).done( function (data) { // this return undrfined
                
                if(data.success == false) {
    
                    if(data.errors.emptyphoto) {
                        $('input').append('<span class="text-danger">' + data.errors.emptyphoto + '</span>');
                    }
    			}
            });
            e.preventDefault();
        });
      
      //but i have another issue here
      
      //my php.ini
      upload_max_filesize=2M
      post_max_size=8M
      
      //my new photo validation
      $ext = array('png', 'PNG');
      if (in_array(pathinfo($_FILES['photo']['name'], PATHINFO_EXTENSION), $ext) &&   ($_FILES['photo']['size'] > 102400)) {
          $errors['image'] = "image greater than 100kb not allowed!";
      }
      
      /*But when I upload images larger than 2M they enter the server as usual while those that are larger than 100kb and less than 2M do not enter at the same time they enter those with size less than 100kb. How can I only allow less than 100kb to be uploaded to a server*/
      

     

  5. 1 hour ago, mac_gyver said:

    in order to upload a file using ajax, you need to use the FormData() object (current, best method) - https://developer.mozilla.org/en-US/docs/Web/API/FormData

    I have found that when I use formdata api I do not have to enter dataType: 'JSON',  and if I enter, it return undefined. now how do i get those error messages in php script since formdata api does not support JSON

     

    look

     

     $("#uploaad").click( function(e) {
    		var formData = $(form).serialize();
            $.ajax({
                url: 'add.php',
                type: 'POST',
                data: formData,
            }).done( function (data) { // this return undrfined
                
                if(data.success == false) {
    
                    if(data.errors.emptyphoto) {
                        $('input').append('<span class="text-danger">' + data.errors.emptyphoto + '</span>');
                    }
    			}
            });
            e.preventDefault();
        });
    
    
    //and this return an error message as usually even  if imagr name is available in the form field
     $("#uploaad").click( function(e) {
    		var formData = $(form).serialize();
            $.ajax({
                url: 'add.php',
                type: 'POST',
                data: formData,
                dataType: "JSON",
            }).done( function (data) {
                
                if(data.success == false) {
    
                    if(data.errors.emptyphoto) {
                        $('input').append('<span class="text-danger">' + data.errors.emptyphoto + '</span>');
                    }
    			}
            });
            e.preventDefault();
        });

     

  6. 6 minutes ago, Barand said:

    All that line does in your ajax script is send the name of the file. It is NOT uploading the file.

    https://www.php.net/manual/en/features.file-upload.php

    It actually sends the file name, and the php script above used to check if the file name does not exist then it will return the message in the above array.

    Surprisingly, when you upload a file it means that the file name is there and that message in the array is still coming back

  7. 22 hours ago, mac_gyver said:

    since a button of type = 'button' doesn't do anything by itself and you are outputting json encoded data back to the browser, what is the javascript/ajax code that's trying to upload the file?

    MY ajax look like,

     $("#uploaad").click( function(e) {
            $.ajax({
                url: 'add.php',
                type: 'POST',
                data: {photo: $('#photo').val()},
                dataType: "JSON",
                encode: true,
            }).done( function (data) {
                
                if(data.success == false) {
    
                    if(data.errors.emptyphoto) {
                        $('input').append('<span class="text-danger">' + data.errors.emptyphoto + '</span>');
                    }
    			}
            });
            e.preventDefault();
        });

     

  8. ///i have field like this
    
    <form method="POST" enctype="multipart/form-data">
    
    <input type="file" name="photo" id="photo">
    
    <button type="button" id="uploaad">upload</button>
    
    </form>
    
     
    
    //my php code
    
    <?php
    
    //validation code
    
    $errors=[];
    
    $data=[];
    //The Error not appearing at first, but when I submit an empty field the error appear that is good, the problem start here, even if image is selected the error still appearing why not disappearing
    
    if(empty($_FILES["photo"]["name"])) {
        $errors['emptyphoto'] = 'please upload photo!';
    }
    
    if(count($errors) !== 0) {
        $data['errors'] = $errors;
    }
    echo json_encode($data);
    
    ?>

     

  9. i have field like this

    <form method="POST" enctype="multipart/form-data">

    <input type="file" name="photo" id="photo">

    <button type="button" id="uploaad">upload</button>

    </form>

     

    <pre>

    <?php

    //my validation code

    $errors=[];

    $data=[];

    if(empty($_FILES["photo"]["name"])) {
        $errors['emptyphoto'] = 'please upload photo!';
    }

    if(count($errors) !== 0) {
        $data['errors'] = $errors;
    }
    echo json_encode($data);

    ?>

    </pre>

    The Error appearing not at first, but when I submit an empty field the error appear, again even if image is selected the error still appearing why not disappearing

     

     

  10. How can i play with these role in my database table as you can see here

    //I have a database table

    CREATE TABLE users ( id int(10) NOT NULL PRIMARY KEY AUTO_INCREMENT, urole varchar(10) );

    in the role column, I have 2 roles first role is only used once but the sound one can be assigned to more than one user, now I want to check my table if the first role is already registered, then we can't register user with that role, also the second role can exist two or more times

    //check role, a variable user role has been defined as 
    $urole = $_POST['urole'];
    $check = $connect -> prepare('SELECT * FROM users WHERE urole = ?');
    $check -> execute([$urole]); $checkfetch = $check -> fetch();
    
    //I'm stacking here, I want to put $checkfetch['urole'] in rowCount() to be counted but I think this is not a correct way of using rowCount() 
    
    if(($checkfetch['urole'] == 'MainAdmin') && ($checkfetch ->rowCount() == 1)) { 
       echo 'This role can be used by only once!';
    } 
    //another role 
    if(($checkfetch['urole'] == 'NormalAdmin') && ($checkfetch ->rowCount() < 4)) { 
       echo 'This role can be used 4 times only!';
    }

     

  11. //please dont talk about sql injection, i'll work on it, the problem with this code, it count all entries in a database table but i wantto count only with nid = 1
    $query = 'SELECT * FROM abc WHERE nid = 
    if(!empty($_POST["search"]["value"])){
    $query .= 'AND (a LIKE "%'.$_POST["search"]["value"].'%" 
    OR b LIKE "%'.$_POST["search"]["value"].'%" 
    OR c LIKE "%'.$_POST["search"]["value"].'%") ';      
    } 
    if(!empty($_POST["order"])){
                $query .= 'ORDER BY '.$_POST['order']['0']['column'].' '.$_POST['order']['0']['dir'].' ';
            } else {
                $query .= 'ORDER BY id DESC ';
            }
            if($_POST["length"] != -1){
                $query .= 'LIMIT ' . $_POST['start'] . ', ' . $_POST['length'];
            }   
            $result = mysqli_query(dbConnect, $query);
    

     

  12. is iy possible to auto dismiss the appended alert? 

    this doesn't work

     $("#slide-up").fadeTo(2000, 500).slideUp(500, function(){
            $("#slide-up").slideUp(500);
      });

     

    after adding  #slide-up id

    $('.card-header').append('<div class="alert alert-info alert-dismissible" role="alert" id="slide-up"> <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>'+data.errors.phonenoexist+'</div>');

  13. Just now, mahenda said:
    47 minutes ago, mac_gyver said:

    a phone number, despite being called a number, isn't an integer. it is a formatted string consisting of 3 or 4 fields, depending on  which country you live in and if you are including the country code with international numbers. the signed integer you are using (int(12) isn't even valid) can only hold a value up to 2147483647 (214 748 3647) which can only store some US phone numbers up to area-code 214.

    use a string data type and format the value into a common format before using it.

    once you define the column with a usable data type and as a unique index, just attempt to insert the data and detect if a duplicate index error number occurred to determine if the phone number already exists.

    Thanks it works

    
    // i changed the columns in a table mydata 
    create table mydata (
    	id int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
    	fname varchar(20) NOT NULL,	
        phoneno varchar(12) NOT NULL UNIQUE
        /*......*/
    );
    //it works, but i validated the phoneno so the user can't enter invalid number

     

  14. //database
    create table mydata (
    	id int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
    	fname varchar(20),	
        phoneno int(12) NOT NULL
        /*......*/
    );
    //class my data php
    
    <?php
    
    include('connect.php');
    class InsertMydata {
        public function insertnow($fname, $phoneno) {
            $connect = new Connect;
            $insrt = $db -> prepare('INSERT INTO mydata (fname, phoneno) VALUES (?,?)');
    		$insrt -> execute(array($fname, $phoneno));		
    	}
    }
    ?>
    
    
    //insernow validate form
    
    <?php
    include('../classs/mydata.php');
    //Declare data and error arrays
    $errors = [];
    $mydara = [];
    if(!preg_match('/^[a-zA-Z]{4,15}$/', $_POST['fname'])) {
    	$errors['fname'] = 'Enter full name!';
    }
    //this block not working even the phone exist
    $connect = new Connect;
    $phoneno = $_POST['phoneno'];
    $checkiexist = $connect -> prepare('SELECT * FROM mydata WHERE phoneno = ?');
    $checkiexist -> execute([$phoneno]);
    if($checkiexist->rowCount() > 0) {
          $errors['phonenoexist'] = 'Try another phone number!';
     }
    if(!empty($errors)){
          $data['success'] = false;
          $data['errors'] = $errors;
    }else{
          $data['success'] = true;
          $data['message'] = 'success message!';  
          $mydata = new InsertMydata;
          $mydata -> insertnow($fname, $phoneno);
    }
    echo json_encode($data);
    
    ?>
    
    //my ajax
    
    $("#insertbtn").click( function(e) {
         var fname = $('#fname').val(),
             phoneno = $('#phoneno').val(),
               
           $.ajax({
               url: 'insertnow.php',
               type: 'POST',
               data: {fname:fname, phoneno:phoneno},
               dataType: "JSON",
               encode: true,
            }).done( function (data) {
             
             if (data.success == false) {
               if (data.errors.fname) {
                     $('#fname').append('<p class="text-danger">' + data.errors.fname + '</p>');
                } 
                if (data.errors.phonenoexist) {
                  $('.card-header').append('<div class="alert alert-info alert-dismissible" role="alert">
                    <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>'+data.errors.phonenoexist+'</div>');
                }
                } else {
                 $('.card-header').append('<div class="alert alert-success alert-dismissible" role="alert"><button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>'+data.message+'</div>');
            }
        });
           e.preventDefault();
        });
    
    
    //the problem is, the code insert data even if the phone exist why?

    the problem is, the code insert data even if the phone exist why?

  15. As we know ,

    A post_max_size used to limit the size of posted data via POST method

    while 

    the upload_max_filesize used to limit the size of file to be uploaded

     

    I assume.

    post_max_size = 8m

    upload_max_filesize = 2m

     

    When i limit the user to only upload 100kb file, i say

    <pre>

      if (!empty($_FILES["myfile"]["tmp_name"]) && ($_FILES["myfile"]["size"] > 100000)) {
           echo "the file is too large";
        }

    </pre>

     

    This message occur even when the file is greater than 8 m

     

    The problem come when the file is greater than 10m the warning message for post content is on the page is

     

    Warning: POST Content-Length of 9767236 bytes exceeds the limit of 8388608 bytes in Unknown on line 0

     

    What i want?

    I want to create my own warning as an error

     

    ie

    <pre>

      if (post_max_size > 18388608)) {
           echo "the posted content exceed our server limit ";
        }

    </pre>

     

    NB: some developers says

    we have to adjust the post_max_size i.e 200M what if user upload the file with 210M, the warning message will come back again

     

    Warning: POST Content-Length of 9767236 bytes exceeds the limit of 8388608 bytes in Unknown on line 0

     

    In short i want to give a normal user a meaningful warning

     

  16. 7 minutes ago, requinix said:

    As both error messages clearly state, you cannot change session settings after you've already started the session. It should logically follow that if you want to change settings then you have to do it before the session is started.

    so this means

    ini_set('session.cache_limiter','public');

    session_cache_limiter(false);

    session_start();

     

    or

    session_start();

    ini_set('session.cache_limiter','public');

    session_cache_limiter(false);

     

    and what happen when am creating login  session

     

     

  17. ini_set('session.cache_limiter','public');
    session_cache_limiter(false);

     

    they give warning


    Warning: ini_set(): A session is active. You cannot change the session module's ini settings at this time in C:\xampp\htdocs\aps\init.php on line 3

    Warning: session_cache_limiter(): Cannot change cache limiter when session is active in C:\xampp\htdocs\aps\init.php on line 4

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.