Codes works on local server but not on live server


#1

This codes works on local server(XAMPP) but does not seems to work on live server. And I can't really figure out what the problem is since there no error is output in the errorlog. In the script, I tried to use the--pre--tag but also nothing gets displayed

<?php session_start();?>
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Testimony</title>
    </head>
    <body>
        <?php
        try {
            $linkas = 2;
            require_once 'db/DBConnect.php';
            $errors = [];
            $good = true;
            if ($_SERVER['REQUEST_METHOD'] == 'POST' && !empty($_POST['testimony'])):
                $testimony = /*filter_input(INPUT_POST, 'testimony', FILTER_SANITIZE_STRING)*/$_POST['testimony'];
                echo $testimony;
                if (strlen($testimony) < 20):
                    //report error and do not go
                    $errors[] = 'It has to be more than 20 characters' . '<br>';
                    $good = false;
                else:
                    echo $testimony;
                    $good = true;
                    if ($good):
                        $insertTestimony = 'INSERT INTO testimony(content, j_member_id) ';
                        $insertTestimony .= 'VALUES (:testimony, :user_id)';
                        $insert = $conn1->prepare($insertTestimony);
                        $insert->bindValue(':testimony', $testimony, PDO::PARAM_STR);
                        $insert->bindValue(':user_id', $linkas, PDO::PARAM_INT);
                        $insert->execute();
                        if ($insert->rowCount() == 1):
                            //success message
                            //$_SESSION['msg'] = 'Thanks for the testimony';
                            header('Location: index.php');
                        else:
                            //fail message
                            echo 'Something is wrong, please resubmit';
                        endif;
                    endif;
                endif;
            endif;
        } catch (Exception $e) {
            echo 'Database error: ' . $e->getMessage() . ' in ' . $e->getFile() . ':' . $e->getLine();
        }
        ?>
        <section class="">
            <article>
                <form action="" method="post" id="testimony" accept-charset="utf-8">
                    <fieldset>
                        <legend>Your testimony</legend>
                        <label for="testimony"></label>
                        <textarea id="testimony" name="testimony" maxlength="300"><?php
        if (isset($_POST['testimony'])):
            echo htmlspecialchars($testimony);
        endif;
        ?></textarea>
                    </fieldset>
                    <input type="submit" name="testify" id="testify" value="Testify">
                </form>
            </article>
        </section>
    </body>
</html>

And this is the database connection string which I used to connect to the database and its located inside the db folder

<?php
//Db connection 1
$username ="XXXXX"; // censored for SO
$password = "XXXXX"; // censored for SO
//$database = "xzelanet_180days";
//$server="localhost";
$conn1 = new PDO('mysql:host=localhost;dbname=xzeere_30days; charset=utf8', $username, $password);
$conn1->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

After the form submission, the form refuses to insert into the database(the form displayed but does not submit[I think the problem should be inside the code processing the form])


#2

Are you running the same version of PHP on your localhost and live website?

Do you know whether the DB connexion has been made?

Have you tried echoing something within the area where you think the code is failing?


#3

XAMPP version is PHP 7.0.13 while live version is 5.6.33.

inside the textarea tag, am able to to echo out whatever is typed inside while it does not work inside the processing codes(i.e. IF($_SERVER{'REQUEST_METHOD'] == 'POST'))


#4

Try overriding the php.ini settings by inserting this script at the top of every page or change the PHP.ini settings.

<?php
if(TRUE)// toggle to false after debugging
{
  ini_set( 'display_errors', 'true');
  error_reporting(-1);
}

#5

Is it getting confused because you've got two elements with the same id of testimony on the page?

How far does it get through the processing code before it stops working, and how does it stop working - with an error, a blank screen, or appears to do what it should but there's nothing in the database? Or does it just never go into the processing code?


#6

But that should be JS worries and not PHP


#7

let me try that


#8

Is it something weirdly obscure with regard to case-sensitivity on filenames?

require_once 'db/DBConnect.php';

I'm not sure whether PHP would deal with this file if, for example, it gets uploaded as "dbconnect.php" from a non-case-sensitive system like Windows, up to a case-sensitive system like Unix or similar. Does "something" deal with that scenario? Used to catch me out sometimes when uploading images to a live web host.


#9

@programmer
This is confusing and will fail because of the header(...); statement :slight_smile:

Edited:

<?php
try {
    $linkas = 2;
    require_once 'db/DBConnect.php';
    $errors = [];
    // $good = true;
    $errors[] = 'It has to be more than 20 characters' . '<br>';
    $good = FALSE; // Assume the worst
    if($_SERVER['REQUEST_METHOD'] == 'POST' && !empty($_POST['testimony']) ):
        /*filter_input(INPUT_POST, 'testimony', FILTER_SANITIZE_STRING)*/
        $testimony = $_POST['testimony'];
        
        // echo $testimony;
        // if (strlen($testimony) < 20):
        $good = strlen($testimony) >= 20;
        if($good):
            //report error and do not go
            // $errors[] = 'It has to be more than 20 characters' . '<br>';
            // $good = false; ALREADY FALSE
        // else:
            // $good = true;
            echo $testimony;
            // if ($good): // NOT REQUIRED
            $insertTestimony  = 'INSERT INTO testimony(content, j_member_id) ';
            $insertTestimony .= 'VALUES (:testimony, :user_id)';
            $insert = $conn1->prepare($insertTestimony);
            $insert->bindValue(':testimony', $testimony, PDO::PARAM_STR);
            $insert->bindValue(':user_id', $linkas, PDO::PARAM_INT);
            $insert->execute();
            if ($insert->rowCount() == 1):
                //success message
                //$_SESSION['msg'] = 'Thanks for the testimony';
                /*
                  THIS WILL FAIL BECAUSE THERE PREVIOUS OUTPUT IS NOT ALLOWED
                  AND SHOULD BE AT THE TOP OF THE FILE BEFORE ANY HTML OUTPUT
                */
                header('Location: index.php');
            // else:
               // CAUGHT in the catch statement 
              // fail message
              // echo 'Something is wrong, please resubmit';
            endif;
            // endif; // NOT REQUIRED
        endif;
    endif;
    } catch (Exception $e) {
    echo 'Database error: ' . $e->getMessage() . ' in ' . $e->getFile() . ':' . $e->getLine();
    die; // No point in continuing
    }
?>

#10

You can expect inconsistencies.

Just a very quick, cursory scan of the code shows that headers are sent after there has bee output to the browser.
Error reporting, if enabled, will tell you that straight away.


#11

Oh thanks so much. It works now


I need an example of how to use php and ajax to insert data into the database
#12

For the benefit of other users please share your solution.


#13

I just figured all those extra echo() statements were trying to debug the underlying issue. After all, that would fail on the local server as well, surely?


#14

If error_reporting(0); was set locally there is a possible chance the script would not fail.

On the server side, I think because of header(...); the errors will occur because of either a possible space following:

<?php session_start();?>

OR

<!DOCTYPE html>

Only PHP script is allowed before calling header(...);


#15

I guess it doesn't matter, but this really bothers me

$testimony = /*filter_input(INPUT_POST, 'testimony', FILTER_SANITIZE_STRING)*/$_POST['testimony'];

I have never seen or coded a comment within an assignment statement. Apparently it works, but I still wouldn't feel comfortable doing that.


#16

You should be using a similar PHP version in your dev environment as your production one. PHP 5.6 and 7 are very different. The first step to eliminating differences between environments is to use the same version of php. Using a dev environment that contrasts so largely with production is a very poor choice and bad habit.


#17

The script is ok but must admit it is most peculiar because I never expected the trailing variable after the comments on the same line! In the rehashed version the comment was moved before the variable was given a value.

Before:

  $testimony = /*filter_input(INPUT_POST, 'testimony', FILTER_SANITIZE_STRING)*/$_POST['testimony'];
  echo $testimony;

After:

/*filter_input(INPUT_POST, 'testimony', FILTER_SANITIZE_STRING)*/
   $testimony = $_POST['testimony'];
   echo $testimony;


Rant:
I am a great believer in verbose script because it is so much easier to debug. Thankfully, gone are the days of trying to save bytes to improve performance. Processor speeds and available memory have both increased dramatically so there is no need to eliminate comments, linefeeds, tabs and spaces. The infinitesimal time saved by having unreadable script is virtually non-existentent. Verbose script drastically reduces time spent debugging which is where the majority of time is spent. Use your limited and precious time wisely because your personal time can never be recovered :slight_smile:


#18

Unfortunately shared hosting services are renowned for using outdated PHP versions.

Far better to take advantage of extreme debugging techniques that will work satisfactorily on both platforms... except for the hardcoded PHP7 declare(strict_types=1); statement :frowning:

Edit and off topic:
Just discovered it is not OK to have a k in the spelling of renowned:slight_smile:


#19

I would think that really depends on the host. I have a live shared host, but my hosting provider supports 7.2 as the latest version. I don't want to switch from 7.1 to 7.2 because apparently, __autoload has been removed and I am still using the older PHPMailer. But that's on my part, I'll have to take some time to fix it.

Getting back on track, I really disagree with the use of having form submissions where you feel like putting them. This is kind of the reason why most users tend to spout "not working", "didn't work", or "doesn't work" as the most reasonable explanation. But it is their own doing that causes these errors. If form processes are placed at the very top of the page, none of this would be happening. Just my 2 cents since I often see the same exact mistakes on nearly every single thread that pertains to spaghetti PHP.


#20

[off topic]
Maybe consider VPS because there are some good deals available at $5.00 per month with $100 free hosting redeemable after about six month. This amounts to about $30 for the first year and have still have $70 credit left over if I interpret the TAC correctly. CPU one gig with 20 gig SSD drives, what are you waiting for :slight_smile:

Edit:
Just noticed another Ad' and 25 gig SSD is available but the free credit is only for 60 days which I think equates to ten months at 5.00 per month. So it works out at $50 for the first year. Also offered is a money-back guarantee which I have not investigated.
[/off topic]