简体   繁体   中英

How to know if a page is called via a POST method in PHP.

I am using the following code in order to modify the database using PHP:

<?php 

//connect to the database
$connect = mysql_connect("localhost","root","");
mysql_select_db("loginform",$connect); //select the table
//

if ($_FILES['csv']['size'] > 0) {

    //get the csv file
    $file = $_FILES['csv']['tmp_name'];
    $handle = fopen($file,"r");

    //loop through the csv file and insert into database
    do {
        if ($data[0]) {
            mysql_query("INSERT INTO mytable( name,country,age) VALUES
                (
                    '".addslashes($data[0])."',
                    '".addslashes($data[1])."',
                    '".addslashes($data[2])."'
                )
            ");
        }
    } while ($data = fgetcsv($handle,1000,",","'"));
    //

    //redirect
    header('Location: sample.php?success=1'); die;

}

?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Import a CSV File with PHP & MySQL</title>
</head>

<body>

<?php if (!empty($_GET[success])) { echo "<b>Your file has been imported.</b><br><br>"; } //generic success notice ?>

<form action="" method="post" enctype="multipart/form-data" name="form1" id="form1">
  Choose your file: <br />
  <input name="csv" type="file" id="csv" />
  <input type="submit" name="Submit" value="Submit" />
</form>

</body>
</html>

I am able to insert the data in to MySQL table but the problem is I am getting an error:

Notice: Undefined index: csv in C:\xampp\htdocs\deepthi\excel\sample.php on line 8

Notice: Use of undefined constant success - assumed 'success' in C:\xampp\htdocs\deepthi\excel\sample.php on line 44 

I think it is because while the page is loading without a postback even then the code is executing. How to check that page is loaded via a Submit button click? Can someone help me?

 if ($_SERVER['REQUEST_METHOD'] === 'POST') {
echo "Page is called via a POST method";

}

Use the following code just before your if statement

if($_SERVER['REQUEST_METHOD'] == 'POST')

The above code indicates that the page request came from a submit button. (of POST type)

eg:

    <?php 

    //connect to the database
    $connect = mysql_connect("localhost","root","");
    mysql_select_db("loginform",$connect); //select the table
    //
    if($_SERVER['REQUEST_METHOD'] == 'POST')
     if ($_FILES['csv']['size'] > 0) {

        //get the csv file
        $file = $_FILES['csv']['tmp_name'];
        $handle = fopen($file,"r");

        //loop through the csv file and insert into database
        do {
            if ($data[0]) {
                mysql_query("INSERT INTO mytable( name,country,age) VALUES
                    (
                        '".addslashes($data[0])."',
                        '".addslashes($data[1])."',
                        '".addslashes($data[2])."'
                    )
                ");
            }
        } while ($data = fgetcsv($handle,1000,",","'"));
        //

        //redirect
        header('Location: sample.php?success=1'); die;

     }

    ?>

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
    <title>Import a CSV File with PHP & MySQL</title>
    </head>

    <body>

    <?php if (!empty($_GET[success])) { echo "<b>Your file has been imported.</b><br><br>"; } //generic success notice ?>

    <form action="" method="post" enctype="multipart/form-data" name="form1" id="form1">
      Choose your file: <br />
      <input name="csv" type="file" id="csv" />
      <input type="submit" name="Submit" value="Submit" />
    </form>

    </body>
    </html>

Your variable is not having value and you are accessing it. Please update

if ($_FILES['csv']['size'] > 0) {

To,

if (isset($_FILES['csv']['size'])) {
if ($_FILES['csv']['size'] > 0) {

Also, add closing brace }

Your success is a key of array, it should be enclosed by commas( ' ). And also change:

<?php if (!empty($_GET[success])) { echo "<b>Your file has been imported.</b><br><br>"; } //generic success notice ?>

to

<?php if (isset($_GET['success']) && !empty($_GET['success'])) { echo "<b>Your file has been imported.</b><br><br>"; } //generic success notice ?>

As Sunny Gupta says,

  1. check the method : if the form has been submitted (the submit button clicked), then $_POST is set. You want to process $_FILES only is this is the case

  2. sidenote 1 : using unquoted indexes for arrays triggers warnings and logs. That's, in the best case, useless. Consider using quotes instead of non existing PHP constants :

    if (!empty($_GET['success']))

  3. sidenote 2 : your do/while will always log an error on the first loop. Prefer clean code and initialize $data before using it, not after. Also, don't check only $data[0] if you want to read 3 entries.

    while ($data = fgetcsv($handle,1000,",","'")) { if (count($data) > 2) { [...] } } ;

  4. sidenote 4 : last but not least, mysql_xxx functions are deprecated. Consider using mysqli_xxx functions instead. And prefer mysqli_real_rescape_string to addslashes() , it's safer.

POST Statement Check

if((isset($_POST['Submit']) && trim($_POST['Submit']) == "Submit") && ($_SERVER['REQUEST_METHOD'] == 'POST'))


<?php 

        //connect to the database
        $connect = mysql_connect("localhost","root","");
        mysql_select_db("loginform",$connect); //select the table
        //
        if((isset($_POST['Submit']) && trim($_POST['Submit']) == "Submit") && ($_SERVER['REQUEST_METHOD'] == 'POST'))
        {
             if ($_FILES['csv']['size'] > 0)
             {

                //get the csv file
                $file = $_FILES['csv']['tmp_name'];
                $handle = fopen($file,"r");

                //loop through the csv file and insert into database
                do {
                    if ($data[0]) {
                        mysql_query("INSERT INTO mytable( name,country,age) VALUES
                            (
                                '".addslashes($data[0])."',
                                '".addslashes($data[1])."',
                                '".addslashes($data[2])."'
                            )
                        ");
                    }
                } while ($data = fgetcsv($handle,1000,",","'"));
                //

                //redirect
                header('Location: sample.php?success=1'); die;

             }
        }

        ?>

        <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
        <html xmlns="http://www.w3.org/1999/xhtml">
        <head>
        <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
        <title>Import a CSV File with PHP & MySQL</title>
        </head>

        <body>

        <?php if (!empty($_GET[success])) { echo "<b>Your file has been imported.</b><br><br>"; } //generic success notice ?>

        <form action="" method="post" enctype="multipart/form-data" name="form1" id="form1">
          Choose your file: <br />
          <input name="csv" type="file" id="csv" />
          <input type="submit" name="Submit" value="Submit" />
        </form>

        </body>
        </html>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM