Refresh a php page

Solved
Anonymous user -  
 Anonymous user -
Hello,

I want to understand how to refresh a page after submitting a <form type="post">
yes, I know the method:

header('Location: admin.php');

or
header("Refresh: 0;url=admin.php");


However, in my case, it doesn't correspond to what I want.
Let me explain with code:

admin.php:
 <?php if (!isset($_POST['mdp']) OR $_POST['mdp'] != "CHOCOLAT") { ?> <div class="Authentification master"> <form class="slave" action="admin.php" method="post"> <p> <label for="mdp">Admin Password</label><br> <input type="password" name="mdp" /> <input type="submit" value="Valider" /> </p> </form> [...] 


admin.php has 2 forms:
- the authentication
- the document upload

When I authenticate on admin.php, I can then upload my documents.

 if ($fileSize > 100000) { $fileNameNew = uniqid('', true). "." . $fileActualExt; $fileDestination = 'uploads/'. $fileNameNew; move_uploaded_file($fileTmpName, $fileDestination); $sql = "INSERT INTO OC (PicturePath, PictureName, titre, instruction) VALUES ('$fileDestination', '$fileName', '$fileTitle', '$instruction')"; if ($conn->query($sql) === TRUE) { header("Refresh: 0;url=admin.php"); } else { echo "Error: " . $sql . "<br>" . $conn->error; } }else { echo "Your file is too big !! -> " . $fileSize . " > 100000"; } 


As you can understand, once the upload is complete, the page refreshes.
But then I have to re-enter my password .... for each new file ... it's annoying after a while.

NEVERTHELESS:
When I manually refresh this page with the browser button, it works correctly.
My image is added to the collection, and no second authentication is needed.

Do you have a method?

I tried changing my form to GET and using
header('Location: admin.php?mdp=CHOCOLAT');

but it's the same problem strangely.
And then GET .... is not great in terms of discretion.

Once again, thank you for your help.

Configuration: Linux / Firefox 69.0

3 réponses

jordane45 Posted messages 30426 Registration date   Status Modérateur Last intervention   4 830
 
Hello,

To start... I invite you to read and apply the content of this link
https://forums.commentcamarche.net/forum/affich-37584947-php-gestion-des-erreurs-debogage-et-ecriture-du-code

Then... come back to us with your COMPLETE code.
Because right now... with just a few pieces... it's hard to say what's wrong.
(but only come back after applying the advice given in the link I just provided... otherwise, it's not worth it!)

--
Sincerely,
Jordane
0
Anonymous user
 
Unfortunately Jordane, I could drown my code under the debugs (which I commonly do anyway) but I doubt that even one of them would be useful here...
Indeed, this is not a bug... my code works very well.

But even after numerous searches on the internet and dedicated forums, I can't find a solution that fits my needs.

(I assure you that the step "asking my question on CCM" comes only after "debugs," then "internet search," then "asking a friend." I've been starting with PHP for 3 days, but I have 5 years of coding experience behind me.)
0
jordane45 Posted messages 30426 Registration date   Status Modérateur Last intervention   4 830 > Anonymous user
 
Have you at least read the content of the link???
It's not only about debugging... but also about properly retrieving variables... enabling PHP errors... breaking down the code...
But apparently, you haven't read it...
Try again... you'll see that it helps a lot...
Then show us your complete and modified code...
0
Anonymous user
 
yes yes I assure you I've read it.

Displaying variables is debugging in my eyes if it's not meant to remain.
And I've already enabled the display of PHP errors just as I have for SQL, by the way.

I believe my code is quite readable, but if that's not the case, I am open to advice or criticism.

But maybe you want me to leave my debug information when I post on the forum??
I generally remove everything out of fear of bloating the code and drowning you in what isn't essential.
0
Anonymous user
 
For your information -

After logging in for the first time and using the upload form (admin.php line 49)
I refresh the same page BUT do not want to fall back onto the authentication form again (admin.php line 30).
It works when I click refresh via my browser, but not when I request it (collector.php line 35) with
header('Location: admin.php');
or
header("Refresh: 0;url=admin.php");


admin.php:

 <!doctype html> <html> <head> <meta charset="utf-8"> <title>OC | Admin panel</title> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"> <link rel="stylesheet" href="css/master.css"> <title>website | Admin</title> </head> <body> <?php try { $bdd = new PDO('mysql:host=localhost;dbname=OpinionCollector;charset=utf8', 'root', ''); } catch(Exception $e) { die('Error: '.$e->getMessage()); } ?> <?php if (!isset($_POST['mdp']) OR $_POST['mdp'] != "666-999") { ?> <div class="nav-bar"> <h1>title</h1> <a href="index.php">BACK</a> </div> <div class="Authentication master"> <form class="slave" action="admin.php" method="post"> <p> <label for="mdp">Admin Password</label><br> <input type="password" name="mdp" /> <input type="submit" value="Validate" /> </p> </form> </div> <?php } else { ?> <div class="nav-bar"> <h1>title</h1> <a href="index.php">BACK</a> </div> <div class="container-fluid Administration"> <div class="row"> <div class="col-lg-6 split master"> <div class="slave"> <form class="slave" action="back/collector.php" method="post" enctype="multipart/form-data"> <input type="file" name="fileUpload" required><br> <input type="text" name="title" placeholder="give a title" required><br> <input type="text" name="instruction" placeholder="give some instructions" required><br> <button type="submit" name="submit">UPLOAD</button> </form> </div> </div> <div class="col-lg-6 split"> <div class="row"> <div class="col-lg-12 pictureCol"> <div class="row"> <?php $reponse = $bdd->query('SELECT PicturePath, titre, NbrLikes, NbrDislikes FROM OC ORDER BY ID DESC LIMIT 0, 50'); while ($donnees = $reponse->fetch()) { ?> <div class="slave picture" style="background-image: url( <?php echo( htmlspecialchars($donnees['PicturePath']) ) ?> )"> <div class="stats"> <div class="row"> <div class="col-lg-12 master"> <h2 class="slave"> <?php echo( htmlspecialchars($donnees['titre'])) ?> </h2> </div> </div> <div class="row"> <div class="col-md-6"> <img src="media/details/like.png" title="like"> <h2 class="count"> <?php echo( htmlspecialchars($donnees['NbrLikes']) ) ?> </h2> </div> <div class="col-md-6"> <img src="media/details/dislike.png" title="dislike"> <h2 class="count"> <?php echo( htmlspecialchars($donnees['NbrDislikes']) ) ?> </h2> </div> </div> <div class="row"> <div class="col-lg-12"> <button type="button">comment(s)</button> </div> </div> <div class="row"> <div class="col-lg-12"> <a> <img src="media/details/cross.png" title="delete this picture ?" class="button"> </a> </div> </div> </div> </div> <?php } $reponse->closeCursor(); ?> </div> </div> </div> </div> </div> </div> <?php } ?> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script> </body> </html> 


Collector.php (called by the upload form)

 <?php $conn = new mysqli("localhost", "root", "", "OpinionCollector"); if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } if (isset($_POST['submit'])) { $file = $_FILES['fileUpload']; $fileTmpName = $_FILES['fileUpload']['tmp_name']; $fileSize = $_FILES['fileUpload']['size']; $fileError = $_FILES['fileUpload']['error']; $fileType = $_FILES['fileUpload']['type']; $allowed = array('jpg', 'png', 'jpeg', 'pdf'); $fileName = $_FILES['fileUpload']['name']; $fileTitle = $_POST['title']; $instruction = $_POST['instruction']; $fileExt = explode('.', $fileName); $fileActualExt = mb_strtolower(end($fileExt)); if (in_array($fileActualExt, $allowed)) { if ($fileError === 0) { if ($fileSize > 100000) { $fileNameNew = uniqid('', true). "." . $fileActualExt; $filePath = 'uploads/'. $fileNameNew; $fileDestination = '../uploads/'. $fileNameNew; move_uploaded_file($fileTmpName, $fileDestination); $sql = "INSERT INTO OC (PicturePath, PictureName, titre, instruction) VALUES ('$filePath', '$fileName', '$fileTitle', '$instruction')"; if ($conn->query($sql) === TRUE) { header("Refresh: 0;url=../admin.php"); } else { echo "Error: " . $sql . "<br>" . $conn->error; } }else { echo "Your file is too big !! -> " . $fileSize . " > 100000"; } }else { echo "There is an error uploading your file !!"; } }else { echo "you cannot upload files of [ " . $fileExt . " ] type !!"; } } $conn->close(); ?> 


I hope this will be clearer now.
Sorry for the spelling and if you feel that I am abusing the forum.
0
Anonymous user
 
Is it necessary to create a cookie to keep my session active?
I would like to avoid this technique, unless it's impossible without it...
0
yg_be Posted messages 23437 Registration date   Status Contributeur Last intervention   1 588 > Anonymous user
 
Hello, what other technique seems preferable to you, and why?
0
tihuboueux
 
Good evening,
no, there are session variables for that. I don’t see the connection between browser cookies and a PHP session, which by definition exists only on the PHP side.
As for the title of your question/topic, I have been pondering it, but I don’t understand what you mean by refreshing a PHP page. What gets updated is the HTML display; PHP runs before the page exists (preprocessor, as the name of the language suggests), so there’s nothing to refresh on that side: the program is executed, retrieving data from the database to feed it to the HTML or vice versa.
However, the opposite is true and very common, and also very useful: not calling the server (like PHP and the database) so that the pages take less time to load and display something. This can be done with AJAX, so the principle is to cache (metadata) the results of likely queries on the database to provide them without having to re-execute the PHP and SQL script; this way the HTML page can be updated without the few milliseconds needed for the queries and to provide them.

So no, do not attempt to refresh PHP; PHP is simply executed (rather interpreted) on the server side to provide content for the HTML page and to automate certain tasks, especially those related to a relational database management system.
0
Anonymous user > tihuboueux
 
My apologies Tihuboueux, it's true that upon reflection it doesn't make much sense to refresh PHP.
I let myself get caught up in the fact that the pages to refresh are in the format [file.php] ...
Can you tell me more about session variables?

Is it a boolean that switches from 0 to 1 during the first authentication and allows bypassing the next ones?

I will also look into it on my side.
Thank you for your insights.
0
tihuboueux
 
Better than me, there are plenty of online resources for you to learn and find what you need when you need it.
Of course, you have to dig deeper; Rome wasn't built in a day, and neither is an experienced developer.
Searching for "PHP session variables" gives me a lot of answers, here is one among others (note the session_start() 'see link' which indicates the creation or renewal of a session).


https://www.php.net/manual/en/reserved.variables.session.php
0
jordane45 Posted messages 30426 Registration date   Status Modérateur Last intervention   4 830
 

Yes, yes, I assure you that I have read it.

Displaying variables is debugging in my eyes if it's not meant to remain.

Sometimes I wonder if people know how to read....

I'm not talking to you about debugging... nor about displaying your variables.... I'm talking about PROPERLY RETRIEVING VARIABLES BEFORE USING THEM....

The link also explains where to write your code... in particular... placing the maximum of PHP OUTSIDE of HTML to make it easier to read and facilitate its evolution and maintenance...

Anyway...

In the strange aspects of your code... for example, we can see that you use mysqli on one side ... and PDO on the other.... to which I would ask... WHY?

Then

After authenticating for the first time and using the upload form (admin.php line 49)
I refresh the same page BUT do not want to return to the authentication form (admin.php line 30).

Normal.. since your authentication form reacts based on POST variables...
However.. when you do your redirection via the header... the PHP variables are not retransmitted...
As tihuboueux says... you need to use session variables...

Here is what your code should look like.. (if you had read the links I gave you...)

File cnxBdd.php
 <?php //database connection AND activation of PDO errors try{ $bdd =new PDO('mysql:host=localhost; dbname=OpinionCollector; charset=utf8', 'root', ''); // Activation of PDO errors $bdd->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // default fetch mode: FETCH_ASSOC / FETCH_OBJ / FETCH_BOTH $bdd->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC); } catch(PDOException $e) { die('Error: ' . $e->getMessage()); } ?> 


File Admin.php
 <?php //Starting sessions session_start(); //displaying PHP errors error_reporting(E_ALL); ini_set('display_errors', TRUE); ini_set('display_startup_errors', TRUE); //database connection require_once "cnxBdd.php"; //PROPER retrieval of variables BEFORE using them! $isLoged = !empty($_SESSION['isLogued']) ? $_SESSION['isLogued'] : NULL; $mdp = !empty($_POST['mdp']) ? $_POST['mdp'] : NULL; //checking the connection if(!$isLoged && $mdp){ $isLoged = $mdp == "666-999" ? true : false; $_SESSION['isLogued'] = $isLoged //executing the request $sql = 'SELECT PicturePath, titre, NbrLikes, NbrDislikes FROM OC ORDER BY ID DESC LIMIT 0, 50'; try{ $reponse = $bdd->query($sql); }catch(Exception $e){ echo "Error in the request: ".$sql; die($e->getMessage()); } }else{ unset($_SESSION['isLogued']); } ?> <!doctype html> <html> <head> <meta charset="utf-8"> <title>OC | Admin panel</title> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"> <link rel="stylesheet" href="css/master.css"> <title>website | Admin</title> </head> <body> <div class="nav-bar"> <h1>title</h1> <a href="index.php">BACK</a> </div> <?php if (!$isLoged){ ?> <div class="Authentication master"> <form class="slave" action="admin.php" method="post"> <p> <label for="mdp">Admin Password</label><br> <input type="password" name="mdp" /> <input type="submit" value="Validate" /> </p> </form> </div> <?php } else { ?> <div class="container-fluid Administration"> <div class="row"> <div class="col-lg-6 split master"> <div class="slave"> <form class="slave" action="back/collector.php" method="post" enctype="multipart/form-data"> <input type="file" name="fileUpload" required><br> <input type="text" name="title" placeholder="give a title" required><br> <input type="text" name="instruction" placeholder="give some instructions" required><br> <button type="submit" name="submit">UPLOAD</button> </form> </div> </div> <div class="col-lg-6 split"> <div class="row"> <div class="col-lg-12 pictureCol"> <div class="row"> <?php while ($donnees = $reponse->fetch()) { ?> <div class="slave picture" style="background-image: url( <?php echo( htmlspecialchars($donnees['PicturePath']) ) ?> )"> <div class="stats"> <div class="row"> <div class="col-lg-12 master"> <h2 class="slave"> <?php echo( htmlspecialchars($donnees['titre'])) ?> </h2> </div> </div> <div class="row"> <div class="col-md-6"> <img src="media/details/like.png" title="like"> <h2 class="count"> <?php echo( htmlspecialchars($donnees['NbrLikes']) ) ?> </h2> </div> <div class="col-md-6"> <img src="media/details/dislike.png" title="dislike"> <h2 class="count"> <?php echo( htmlspecialchars($donnees['NbrDislikes']) ) ?> </h2> </div> </div> <div class="row"> <div class="col-lg-12"> <button type="button">comment(s)</button> </div> </div> <div class="row"> <div class="col-lg-12"> <a> <img src="media/details/cross.png" title="delete this picture ?" class="button"> </a> </div> </div> </div> </div> <?php } $reponse->closeCursor(); ?> </div> </div> </div> </div> </div> </div> <?php } ?> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script> </body> </html> 


Collector.php
 <?php //Starting sessions (so they continue to live between each page...) session_start(); //displaying PHP errors error_reporting(E_ALL); ini_set('display_errors', TRUE); ini_set('display_startup_errors', TRUE); //database connection require_once "cnxBdd.php"; //Proper retrieval of variables BEFORE using them... $file = !empty($_FILES['fileUpload']) ? $_FILES['fileUpload'] : NULL; $fileTitle = !empty($_POST['title']) ? $_POST['title'] : NULL; $instruction = !empty($_POST['instruction']) ? $_POST['instruction'] : NULL; if (isset($_POST['submit']) && $file) { $fileTmpName = $file['tmp_name']; $fileSize = $file['size']; $fileError = $file['error']; $fileType = $file['type']; $allowed = array('jpg', 'png', 'jpeg', 'pdf'); $fileName = $file['name']; $fileExt = explode('.', $fileName); $fileActualExt = mb_strtolower(end($fileExt)); if (in_array($fileActualExt, $allowed)) { if ($fileError === 0) { if ($fileSize > 100000) { $fileNameNew = uniqid('', true). "." . $fileActualExt; $filePath = 'uploads/'. $fileNameNew; $fileDestination = '../uploads/'. $fileNameNew; if(move_uploaded_file($fileTmpName, $fileDestination)){ $sql = "INSERT INTO OC (PicturePath, PictureName, titre, instruction) VALUES (:filePath, :fileName, :fileTitle, :instruction)"; $datas = array(':filePath'=>$filePath, ':fileName'=>$fileName, ':fileTitle'=>$fileTitle, ':instruction'=>$instruction); //Executing the request try{ $requete = $bdd -> prepare($sql) ; $res = $requete->execute($datas) ; if($res){ header("Refresh: 0;url=../admin.php"); exit();//always put an exit after a redirect } }catch(Exception $e){ // in case of an error: echo " Error! ".$e->getMessage(); echo " The data: " ; print_r($datas); } }else{ echo " Error while moving the file!"; } }else { echo "Your file is too big!! -> " . $fileSize . " > 100000"; } }else { echo "There is an error uploading your file!!"; } }else { echo "you cannot upload files of [ " . $fileExt . " ] type!!"; } } ?> 


--
Best regards,
Jordane
0
Anonymous user
 
Hello Jordane,

thank you very much for your more than complete response, it saves me a lot of time.
And sorry for the delayed response.

I found some careless mistakes in it that I corrected.
such as:
missing semicolon in (admin.php line 21)
$_SESSION['isLogued'] = $isLogued


typos instead of (admin.php line 15, 21, 33)
$isLoged = !empty($_SESSION['isLogued']) ? $_SESSION['isLogued'] : NULL;


otherwise the code works, no more redirection on authentication after uploading an image.
however, a new problem has appeared...

my admin.php page offers an upload form and displays the already uploaded images.
when I upload a new image, I am correctly redirected to the same page (as expected without having to log in again) but no images are displayed anymore.
instead, I get this error:
Uncaught Error: Call to a member function fetch() on null in /opt/lampp/htdocs/projet/admin.php:89 Stack trace: #0 {main} thrown in /opt/lampp/htdocs/projet/admin.php on line 89

which corresponds to this line (admin.php line 89):
while ($donnees = $reponse->fetch())


I will look for how to resolve it, but I remain attentive if you think you know why.
0
jordane45 Posted messages 30426 Registration date   Status Modérateur Last intervention   4 830
 
however, a new problem has arisen ..

So
1 - Mark the current discussion as RESOLVED
2 - Open a new discussion for this new issue.

Thank you
0
Anonymous user
 
I thought this problem was related to this post, so it was better to leave it in the same thread.

But I understand, the aim of this forum is mainly to catalog a specific problem with a solution.
So we shouldn't mix multiple issues to make it easier for others to find the solution.
0
jordane45 Posted messages 30426 Registration date   Status Modérateur Last intervention   4 830 > Anonymous user
 
```php prepare($sql) ; $requete->execute(); $response = $requete->fetchAll(); // Storing the result in an array. }catch(Exception $e){ // In case of error : echo " Error !" . $e->getMessage(); echo " The data : " ; print_r($datas); } } ?> OC | Admin panel website | Admin





```
0
Anonymous user
 
Hello Jordane45,

For some reason I don't know, your last reply didn't trigger any notifications on my side.
So I followed your advice by creating a new post for my new issue, not realizing you were offering a solution here... so sorry for the "duplicate."

That said, the solution you're proposing brings me back to my first problem... I am currently testing modifications to fix that, as it is true that the code provided here seems more optimized and readable than the solution I retrieved from my previous duplicate post.
Unfortunately, without addressing my initial problem again, I can't ensure that the second one is resolved.

I will keep you updated here if I find a solution.
Have a nice day.

EDIT: I just understood your modifications; indeed, both problems are resolved regarding the image upload without changing your code. I ran my tests by refreshing the page without uploading (that's why I thought I was experiencing the first issue again). It was also something I wanted, but it turns out it’s not essential after all.
0