Related
I have a page that connects to a MySQL database via PHP. On this page the data is fetched to load an image and its related details. This page all work OK when the page is loaded.
I also have a module included on this page where users can create a board (which will hold images) along a certain theme.
On other pages this board module works OK, but on a page where a $_GET request happens, which is needed to identify a user's username or an image filename (depending on the page), the board module doesn't work correctly. When you create a new board it fails and I get a PHP error saying Undefined variable: filename in with reference to the line of code ':filename' => $filename in the execute function below.
When this boards module is used to create a new board name I have some JavaScript fetch() code on the page that prevents a hard refresh. I'm not sure if this is causing the problem (although this JS is also used on the pages that don't have a problem, i.e. no $_GET request). On pages where this is no $_GET request everything works as expected.
Note: in the code below $connection is the database connection from a db.php file
PHP on pageload that loads the image and related data
isset($_GET['filename']) ? $filename = $_GET['filename'] : header("Location: login.php");
$image_stmt = $connection->prepare("SELECT * FROM `lj_imageposts` WHERE `filename` = :filename");
$image_stmt -> execute([
':filename' => $filename // variable that returns the error
]);
$image_row = $image_stmt->fetch();
// if the GET url parameter doesn't exist/changed
if ($image_row == 0) { header ("Location: index.php"); exit; }
$db_userid = htmlspecialchars($image_row['user_id']);
$db_image_id = htmlspecialchars($image_row['image_id']);
$db_image_title = htmlspecialchars($image_row['image_title']);
$db_image_filename = htmlspecialchars($image_row['filename']);
$db_image_ext = htmlspecialchars($image_row['file_extension']);
$db_username = htmlspecialchars($image_row['username']);
?>
---- HTML OUTPUT THAT INCORPORATES THE ABOVE VARIABLES
PHP for the boards module
if (isset($_POST['submit-board-name'])) {
$create_board_name = $_POST['create-board-name'];
if(strlen(trim($create_board_name)) < 10) {
$error[] = "Board name must be at least 10 characters long";
}
if(strlen(trim($create_board_name)) > 150) {
$error[] = "Board name can be at less than 150 characters long";
}
if(!isset($error)) {
try {
$createBoardSQL = "INSERT INTO lj_boards (board_name, user_id) VALUES (:board_name, :user_id )";
$bstmt = $connection->prepare($createBoardSQL);
$bstmt->execute([
':board_name' => $create_board_name,
':user_id' => $db_id
]);
} catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
}
} else {
// give values an empty string to avoid an error being thrown before form submission if empty
$create_board_name = "";
}
This first line is unnecessarily cryptic, making the mistake harder to spot (and harder to fix):
isset($_GET['filename']) ? $filename = $_GET['filename'] : header("Location: login.php");
It's pretending to be an expression, but it's actually an if statement in disguise - it consists of nothing but side effects. Let's write it out more clearly:
if ( isset($_GET['filename']) ) {
$filename = $_GET['filename'];
}
else {
header("Location: login.php");
}
Now we can look more clearly at what each branch does:
The if branch sets a variable. If the code takes that branch, everything should be fine.
The else branch sets a header to be included when PHP sends the response. It doesn't do anything else, and it doesn't set the variable, so if this path is taken, you'll have a problem later.
What you probably intended to happen was for the else branch to set that header and then immediately stop processing. For that you need an exit; statement (also known as die;
if ( isset($_GET['filename']) ) {
$filename = $_GET['filename'];
}
else {
header("Location: login.php");
exit;
}
I am trying to upload multiple images for a product for an eCommerce website. The idea is to save the service name in the services table while the images are saved in the service_images table, but whenever I run the php file, it uploads the service to the services table but only uploads one image to the service_images table instead of all the images. How can I get it to upload one service in the services table and also multiple images of that one service in the service_images table?
Below is my code:
add-service.inc.php
<?php
if (isset($_POST['add-service'])) {
require 'config.php';
$shop_name = mysqli_real_escape_string($conn, $_POST['shop_name']);
$service_cat = mysqli_real_escape_string($conn, $_POST['service_cat']);
$service_name = mysqli_real_escape_string($conn, $_POST['service_name']);
$service_desc = mysqli_real_escape_string($conn, $_POST['service_desc']);
$service_price = mysqli_real_escape_string($conn, $_POST['service_price']);
$service_type = mysqli_real_escape_string($conn, $_POST['service_type']);
$service_images = $_FILES['service_images'];
if (empty($shop_name) || empty($service_cat) || empty($service_name) || empty($service_desc) || empty($service_price) || empty($service_type)) {
header('Location: ../services.php?error=emptyFields');
exit();
} elseif (!preg_match('/^[a-zA-Z0-9]*$/', $shop_name) && !preg_match('/^[a-zA-Z0-9\s]*$/', $service_name) && !preg_match('/^[a-zA-Z0-9\s \. \-]*$/', $service_desc) && !preg_match('/^[0-9\.]*$/', $service_price) && !preg_match('/^[a-zA-Z0-9\s \.]*$/', $service_type)) {
header('Location: ../services.php?error=invalidInputs');
exit();
} elseif (!preg_match('/^[a-zA-Z0-9]*$/', $shop_name)) {
header('Location: ../services.php?error=invalidShopName');
exit();
} elseif (!preg_match('/^[a-zA-Z0-9\s]*$/', $service_name)) {
header('Location: ../services.php?error=invalidserviceName');
exit();
} elseif (!preg_match('/^[a-zA-Z0-9\s \. \-]*$/', $service_desc)) {
header('Location: ../services.php?error=invalidDescription');
exit();
} elseif (!preg_match('/^[0-9\.]*$/', $service_price)) {
header('Location: ../services.php?error=invalidPrice');
exit();
} elseif (!preg_match('/^[a-zA-Z0-9\s \.]*$/', $service_type)) {
header('Location: ../services.php?error=invalidStyle');
exit();
} else {
foreach ($_FILES["service_images"]["tmp_name"] as $key => $tmp_name) {
$file_name = $_FILES["service_images"]["name"][$key];
$file_type = $_FILES["service_images"]["type"][$key];
$file_tempName = $_FILES["service_images"]["tmp_name"][$key];
$file_error = $_FILES["service_images"]["error"][$key];
$file_size = $_FILES["service_images"]["size"][$key];
$a = count($_FILES['service_images']['name']);
for ($i = 0; $i < $a; $i++) {
$fileExt = explode('.', $file_name);
$fileActualExt = strtolower(end($fileExt));
$allowed = array('jpg', 'png', 'jpeg');
if (in_array($fileActualExt, $allowed)) {
if ($file_error === 0) {
if ($file_size <= 15000000) {
$newFileName = preg_replace('/\s+/', '', $service_name) . $i . '.' . $fileActualExt;
echo $newFileName . "<br>";
$fileDestination = '../../services/' . $newFileName;
$sql_images = "INSERT INTO service_images (shop_name, service_name) VALUES ('$shop_name', '$service_name')";
$result = mysqli_query($conn, $sql_images);
$sql = "INSERT INTO services (shop_name, service_cat, service_name, service_desc, service_price, service_type) VALUES (?,?,?,?,?,?)";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql)) {
header("Location: ../services.php?error=SaveError");
exit();
} else {
mysqli_stmt_bind_param($stmt, 'ssssss', $shop_name, $service_cat, $service_name, $service_desc, $service_price, $service_type);
mysqli_stmt_execute($stmt);
// move_uploaded_file($file_tempName = $_FILES["service_images"]["tmp_name"][$i], $fileDestination);
header("Location: ../services.php?success");
exit();
}
} else {
header('Location: ../services.php?error=invalidSize');
exit();
}
} else {
header('Location: ../services.php?error=invalidImage');
exit();
}
} else {
header('Location: ../services.php?error=invalidImageType');
exit();
}
}
}
}
}
form
<form action="../admin/includes/add-service.inc.php" method="post" enctype="multipart/form-data">
<input type="text" name="shop_name" id="shopName" class="form-input" placeholder="Shop Name">
<select name="service_cat" id="serviceCat" class="form-input">
<option> -- select category -- </option>
<?php
$sql = "SELECT * FROM service_category";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
?>
<option value="<?php echo $row['service_cat'] ?>"><?php echo $row['service_cat'] ?></option>
<?php
}
}
?>
</select>
<input type="text" name="service_name" id="serviceName" class="form-input" placeholder="Service Name">
<textarea name="service_desc" id="service_desc" cols="1" rows="5" placeholder="Description" class="form-input"></textarea>
<input type="text" name="service_price" id="servicePrice" class="form-input" placeholder="Service Price">
<input type="text" name="service_type" id="serviceType" class="form-input" placeholder="Service Type">
<hr>
<label for="serviceImages">*Select all pictures for your service</label>
<input type="file" name="service_images[]" id="serviceImages" class="form-input" multiple>
<button type="submit" class="btn-add" name="add-service">Add Service</button>
</form>
First of all, you have the same loop twice. First as foreach and then as for. Since you need numeric keys from this weird array type of $_FILES, then your best approach is to use for loop only.
These double loops are already so messy, that could cause unexpected issues, if one of the files has a problem for example.
But, your main issue is, that you are basically checking only one image and then uploading it. If the validation process or success goes trough, it has exit(); at the end. It kills not only the loop, but the entire script. You are not allowing the second image loop to continue, as first one kills it.. either on success or error.
Solution would be to wait for the loops to finish (adding code after the loops brackets) and putting the success related code there. If an error is detected inside the loops, then the script never gets that far.
I have no idea, how you are actually linking the images to service, but I tried to clean up your code and make the order correct. I also did my best at explaining why and where. Hopefully, you understand the problem better from this or even better, find better options to optimise your code:
// TESTING: Lets see what is inside post values:
echo '<b>$_POST values</b><pre>'; print_r($_POST); echo '</pre>';
// TESTING: Lets see what is inside the files values:
echo '<b>$_FILES values</b><pre>'; print_r($_FILES); echo '</pre>';
// Above is for testing only..
// Probably better place to load important configs:
require 'config.php';
// Since these are the conditions for uploads, then they are global:
// no need for them to be inside the loop:
$allowed = array('jpg', 'png', 'jpeg');
// Maximum allowed filesize:
$max_allowed_file_size = 15000000; // which is 15mb
// We detect the submit buttons trigger name:
if (isset($_POST['add-service'])) {
// Do the escape thingy:
// NOTE: You should be using some mysqli class for database handling:
$shop_name = mysqli_real_escape_string($conn, $_POST['shop_name']);
$service_cat = mysqli_real_escape_string($conn, $_POST['service_cat']);
$service_name = mysqli_real_escape_string($conn, $_POST['service_name']);
$service_desc = mysqli_real_escape_string($conn, $_POST['service_desc']);
$service_price = mysqli_real_escape_string($conn, $_POST['service_price']);
$service_type = mysqli_real_escape_string($conn, $_POST['service_type']);
$service_images = $_FILES['service_images'];
// Lets deal with the errors before going forward with the rest of the script:
// You don't need elseif here, because your callback is to redirect and exit anyways..
if (empty($shop_name) || empty($service_cat) || empty($service_name) || empty($service_desc) || empty($service_price) || empty($service_type)) {
header('Location: ../services.php?error=emptyFields');
exit();
}
if (!preg_match('/^[a-zA-Z0-9]*$/', $shop_name) && !preg_match('/^[a-zA-Z0-9\s]*$/', $service_name) && !preg_match('/^[a-zA-Z0-9\s \. \-]*$/', $service_desc) && !preg_match('/^[0-9\.]*$/', $service_price) && !preg_match('/^[a-zA-Z0-9\s \.]*$/', $service_type)) {
header('Location: ../services.php?error=invalidInputs');
exit();
}
if (!preg_match('/^[a-zA-Z0-9]*$/', $shop_name)) {
header('Location: ../services.php?error=invalidShopName');
exit();
}
if (!preg_match('/^[a-zA-Z0-9\s]*$/', $service_name)) {
header('Location: ../services.php?error=invalidserviceName');
exit();
}
if (!preg_match('/^[a-zA-Z0-9\s \. \-]*$/', $service_desc)) {
header('Location: ../services.php?error=invalidDescription');
exit();
}
if (!preg_match('/^[0-9\.]*$/', $service_price)) {
header('Location: ../services.php?error=invalidPrice');
exit();
}
if (!preg_match('/^[a-zA-Z0-9\s \.]*$/', $service_type)) {
header('Location: ../services.php?error=invalidStyle');
exit();
}
// Nothing happened above, so that means the form validation should be fine and we can go forward with the images:
// So as in your script, we count the images:
$a = count($_FILES['service_images']['name']);
// Now we do a "numeric loop", not an array loop, which is foreach:
for ($i = 0; $i < $a; $i++) {
// Since we have the key as numeric now, we can do what you did before, but without the foreach loop:
$file_name = $_FILES['service_images']['name'][$i];
$file_type = $_FILES['service_images']['type'][$i];
$file_tempName = $_FILES['service_images']['tmp_name'][$i];
$file_error = $_FILES['service_images']['error'][$i];
$file_size = $_FILES['service_images']['size'][$i];
// Get the file extension:
// NOTE: This is not good, as you should really check the mime type of the file, not the extension.
$fileActualExt = strtolower(end(explode('.', $file_name)));
// TESTING: We check print out the data to make sure, that all looks fine:
echo 'File with the key: ' . $i .' -- $file_name: ' . $file_name . '; $file_type: ' . $file_type . '; $file_tempName: ' . $file_tempName . '; $file_error: ' . $file_error . '; $file_size: ' . $file_size . '<br>';
// Instead of making the code ugly, lets deal with errors, by killing the script before
// NOTE: This is not good approach, you should be using Exceptions:
// https://www.php.net/manual/en/language.exceptions.php
// Check if the file extension is NOT in the allowed array
if (!in_array($fileActualExt, $allowed)) {
// Redirect:
header('Location: ../services.php?error=invalidImageType');
// Kill the script:
exit('invalidImageType');
}
// Check if the file had an error:
if ($file_error) {
// Redirect:
header('Location: ../services.php?error=invalidImage');
// Kill the script:
exit('invalidImage');
}
// Check if the image bytes are BIGGER > then max allowed file size variable:
if ($file_size > $max_allowed_file_size) {
// Redirect:
header('Location: ../services.php?error=invalidSize');
// Kill the script:
exit();
}
// At this stage, hopefully, there has not been any errors above and we can deal with file freely:
// Make new file name:
$newFileName = preg_replace('/\s+/', '', $service_name) . $i . '.' . $fileActualExt;
// echo $newFileName . "<br>";
// Set the new destination:
$fileDestination = '../../services/' . $newFileName;
// Lets move the file already.
// NOTE: Make sure that you have some bash code from server side, that deletes outdated / old temp files, so they dont take space:
move_uploaded_file($file_tempName = $_FILES["service_images"]["tmp_name"][$i], $fileDestination);
// Insert the image to database:
// NOTE: Im not sure about your specific code, but just this is there location for that:
$sql_images = "INSERT INTO service_images (shop_name, service_name) VALUES ('$shop_name', '$service_name')";
$result = mysqli_query($conn, $sql_images);
// PROBLEM: This is where you originally had the success message redirect and exit.
// This means, you KILL the script and there for the loop.
// But you have to understand, that you have two images or more, so the loop has to continue freely,
// and you can do this sort of stuff at after the loop!
//
// header("Location: ../services.php?success");
// exit();
}
// If nothing happened above, then the image uploads went trough nicely and we can deal with success messages or adding the service itself:
// I have not used mysqli stmpt before, so I have no idea what is going on in this area..:
// .. but this the locatin to deal with the services as this is the parent and the children are above.
$sql = "INSERT INTO services (shop_name, service_cat, service_name, service_desc, service_price, service_type) VALUES (?,?,?,?,?,?)";
$stmt = mysqli_stmt_init($conn);
// I don't think you need this at all, but whatever:
// Shouldnt this be above
if (!mysqli_stmt_prepare($stmt, $sql)) {
// Redirect:
header("Location: ../services.php?error=SaveError");
// Kill the script:
exit();
}
// This is adding the service I assume, it has to be outside the loop, as single submit = single service. But images are multiple.
mysqli_stmt_bind_param($stmt, 'ssssss', $shop_name, $service_cat, $service_name, $service_desc, $service_price, $service_type);
mysqli_stmt_execute($stmt);
// This is where you can have the success redirect and exit, as this is after the loop:
header("Location: ../services.php?success");
exit();
}
NOTES:
You should be using Exceptions for your error handling.
Learn the difference between foreach and for loops.
File extensions can be tricked, check out the file mime type instead
Allowed file types array inside the loop is not very smart, as you will use it it more than once in all the loop cycles. Best to keep it at the top of the script, so its easier to setup in the future. Same goes for the filesize variable.
It would make alot more sense to detect the file types, sizes via javascript before they even get to your server. This way you save temp file folder space issues and bandwidth basically.
I don't understand where you actually use $result from the mysql. Or where do you link the images from service_images table to the actual service.
Use <input type="file" name="service_images[]" multiple accept=".jpg, .png, .jpeg"> (the multiple accept=".jpg, .png, .jpeg") in the form to not allow the user to pick any other extensions. You can also use "images" value for all images.
On my form , i allow users to upload files to the database and i send them to another page, which is submission_successful.php, that says "Thank You for Submitting". But i noticed that when i hit the back button on the submission successful php file, it goes back to the form and the same information is there and allows another submission. What i want to do is kill the code, upon hitting back button, or clear everything that was inputted by the user. I found a couple of answers around like using cache control but, some were vague and others didn't work for me. And plus i don't want the user going back to the upload page when they're on the success page. So thats why i will create 2 buttons for "logout" or "go back to upload page" and if they hit back button, it will crash. I want to show the Confirm Form Resubmission page. In other post they are trying to actually prevent the "Confirm Form Resubmission" but i would like to have it for security. Here is my code
developerUpload.php
<?php
session_start();
if(array_key_exists("invalid", $_GET)){
echo '<br><h3 style="color:red;">File(s) were already submitted! Please re-name file or select a different file...</h3>';
}
if(isset($_COOKIE['username'])){
if($_SERVER['REQUEST_METHOD'] =="POST"){
$price = addslashes(trim($_POST['price']));
$description = addslashes(trim($_POST['description']));
if(!empty($price) && !empty($description)){
$userid = $_SESSION['id'];
$username = $_SESSION['username'];
echo '<br>'.$userid;
$pack_id = rand();
//Check file 1
if($_FILES['file1']['error'] !== UPLOAD_ERR_OK){
$file1 = null;
}else{
$target1 = "devFiles/";
$target_file1 = addslashes(trim($target1 . basename($_FILES["file1"]["name"])));
$file1 = addslashes(trim($_FILES['file1']['tmp_name']));
}
//Check file 2
if($_FILES['file2']['error'] !== UPLOAD_ERR_OK){
$file2 = null;
}else{
$target2 = "devFiles/";
$target_file2 = addslashes(trim($target2 . basename($_FILES["file2"]["name"])));
$file2 = addslashes(trim($_FILES['file2']['tmp_name']));
}
//Check file 3
if($_FILES['file3']['error'] !== UPLOAD_ERR_OK){
$file3 = null;
}else{
$target3 = "devFiles/";
$target_file3 = addslashes(trim($target3 . basename($_FILES["file3"]["name"])));
$file3 = addslashes(trim($_FILES['file3']['tmp_name']));
}
//Check file 4
if($_FILES['file4']['error'] !== UPLOAD_ERR_OK){
$file4 = null;
}else{
$target4 = "devFiles/";
$target_file4 = addslashes(trim($target4 . basename($_FILES["file4"]["name"])));
$file4 = addslashes(trim($_FILES['file4']['tmp_name']));
}
//Check file 5
if($_FILES['file5']['error'] !== UPLOAD_ERR_OK){
$file5 = null;
}else{
$target5 = "devFiles/";
$target_file5 = addslashes(trim($target5 . basename($_FILES["file5"]["name"])));
$file5 = addslashes(trim($_FILES['file5']['tmp_name']));
}
//Check video
if($_FILES['video']['error'] !== UPLOAD_ERR_OK){
$video = null;
$videoName = null;
}else{
$target = "devFiles/";
$target_file = addslashes(trim($target . basename($_FILES["video"]["name"])));
$video = addslashes(trim($_FILES['video']['tmp_name']));
$videoName = addslashes(trim($_FILES['video']['name']));
}
if(file_exists($target_file1)
or file_exists($target_file2)
or file_exists($target_file3)
or file_exists($target_file4)
or file_exists($target_file5)
or file_exists($target_file)){
header("Location: developerUpload.php?invalid");
exit;
}
if(move_uploaded_file($_FILES["file1"]["tmp_name"], $target_file1)
&& move_uploaded_file($_FILES["file2"]["tmp_name"], $target_file2)
&& move_uploaded_file($_FILES["file3"]["tmp_name"], $target_file3)
&& move_uploaded_file($_FILES["file4"]["tmp_name"], $target_file4)
&& move_uploaded_file($_FILES["file5"]["tmp_name"], $target_file5)
&& move_uploaded_file($_FILES["video"]["tmp_name"], $target_file)){
try{
// new php data object
$handler = new PDO('mysql:host=127.0.0.1;dbname=magicsever', 'root', '');
//ATTR_ERRMODE set to exception
$handler->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}catch(PDOException $e){
die("There was an error connecting to the database");
}
header("Location: submission_successful.php?");
die();
}
}else{
echo '<br><h1 style="color:red;">VALUES MISSING!</h1>';
}
}
}else {
header("Location: developerLogin.php");
}
?>
submission_successful.php
<?php
session_start();
if(array_key_exists("invalid", $_GET)){
header("Location: developerUpload.php?invalid");
}
if(isset($_COOKIE['username'])){
echo '<br><h1 style="color:red; text_align:center;">Thank You for Submitting!</h1>';
}else{
header("Location: developerLogin.php");
}
?>
I was searching around for days and finally found something. IF you use a HTML command it will remove any input the user put when the user goes back. Because my problem was when the user goes back after be redirected, their information was still there but if you use
<form method="post" enctype="multipart/form-data" autocomplete="off">
it removes everything so it kinda helps. The user will still be allowed to go back but at least now they can't resubmit the data.
Not sure whether you can check if a value exists twice in the database (thus preventing multiple submissions), but you could block users from submitting the form too frequently. Create a timestamp that gets saved upon first submission, and if the second resubmission's timestamp is not too far(big) from the first one, you could try sth like (you are submitting too frequently), or you could use ajax, or this https://es.m.wikipedia.org/wiki/Post/Redirect/Get
Use a session variable like this
$_SESSION["post_id"] = "";
if($_POST) {
if($_POST["post_id"] != $_SESSION["post_id"]) {
$_SESSION["post_id"] = $_POST["post_id"];
// do database submission here
}
}
This sets a session variable and if they resubmit the form it won't post the data twice.
I'm having trouble with a PHP script which apparently is getting errors from one single line. The top line in this bit of code is apparently causing quite a bit of trouble:
if (move_uploaded_file($_FILES["image"]["tmp_name"], "./upload/".$imageName)) {
mysql_query("INSERT " .$pages. " SET inmenu='$inmenu', pagid='$pagid', title='$titlename', content='$contentname', image='$image', youtube='$youtube'")
or die(mysql_error());
header("Location: index.php");
}
The errors I'm getting for the top line of code:
Warning: Unexpected character in input: ' in cms/new.php on line 131
Warning: session_start() [function.session-start]: Cannot send session cache limiter - headers already sent (output started at cms/new.php:131) in cms/new.php on line 85
First I thought CHmodding the upload folder to 777 would solve this error, but apparently it doesn't. I really don't know what to do anymore. Is there anyone who can help?
The complete block of code that includes the little snippet above:
<?php
}
session_start();
if(!isset($_SESSION['username'])){
header("location:login.php");
}
include("config.php");
// check if the form has been submitted. If it has, start to process the form and save it to the database
if (isset($_POST['submit']))
{
//set root
$root = getcwd ();
// get form data, making sure it is valid
$inmenu = mysql_real_escape_string(htmlspecialchars($_POST['inmenu']));
$pagid = strtolower(str_replace(" ", "-", mysql_real_escape_string(htmlspecialchars($_POST['pagid']))));
$titlename = mysql_real_escape_string(htmlspecialchars($_POST['title']));
$contentname = mysql_real_escape_string(htmlspecialchars($_POST['contentedit']));
$youtube = mysql_real_escape_string(htmlspecialchars($_POST['youtube']));
// check to make sure both fields are entered
if ($titlename == '' || $pagid == '')
{
// generate error message
$error = 'ERROR: Please fill in all required fields!';
// if either field is blank, display the form again
renderForm($pagid, $titlename, $contentname, $error);
}
else
{
if(file_exists($root."/upload/".$_FILES["image"]["name"]))
{
$filename = explode(".",$_FILES['image']['name']);
$randomnumber = rand(0, 10000);
$imageName = $filename[0].$randomnumber.".".$filename[1];
}
else
{
$imageName = $_FILES['image']['name'];
}
$image = mysql_real_escape_string(htmlspecialchars("/upload/".$imageName));
if (move_uploaded_file($_FILES["image"]["tmp_name"], "./upload/".$imageName)) {
// save the data to the database
mysql_query("INSERT " .$pages. " SET inmenu='$inmenu', pagid='$pagid', title='$titlename', content='$contentname', image='$image', youtube='$youtube'")
or die(mysql_error());
// once saved, redirect back to the view page
header("Location: index.php");
}
else {
// save the data to the database
mysql_query("INSERT " .$pages. " SET inmenu='$inmenu', pagid='$pagid', title='$titlename', content='$contentname', youtube='$youtube'")
or die(mysql_error());
// once saved, redirect back to the view page
header("Location: index.php");
}
}
}
else
// if the form hasn't been submitted, display the form
{
renderForm('','','');
}
?>
When using double quotes you can just insert PHP variables so
Try this:
if (move_uploaded_file($_FILES["image"]["tmp_name"], "./upload/".$imageName)) {
$query = "INSERT " . $pages . SET inmenu=$inmenu, pagid=$pagid, title=$titlename, contenct=$contentname, image=$image, youtube=$youtube";
mysql_query($query) or die(mysql_error());
header("Location: index.php");
}
Another way (if you'd like) would be this:
if (move_uploaded_file($_FILES["image"]["tmp_name"], "./upload/".$imageName)) {
mysql_query("INSERT " .$pages. " SET inmenu='".$inmenu."', pagid='".$pagid."', title='".$titlename."', content='".$contentname."', image='".$image."', youtube='".$youtube."'")
or die(mysql_error());
header("Location: index.php");
}
I'm having issues to send an occuring error to another page.
I have already created the page the error will be sent to, and I've tried a header function. But that doesn't seem to work. Here is the php code that I am using for the page.
<?php
if(isset($_POST['username'], $_POST['password'])){
//login the user here
$connect = mysql_connect("","","")or die(mysql_error());
mysql_select_db("")or die(mysql_error());
$errors = array();
$username = strip_tags(mysql_real_escape_string($_POST['username']));
$password = strip_tags(mysql_real_escape_string($_POST['password']));
if (empty($Regi_Username) || empty($Regi_password)) {
$errors[] = 'All fields are requerid';
} else {
if (strlen($Regi_Username) > 25) {
$errors[] = 'Username is to long';
}
if (strlen($password) > 25) {
$errors[] = 'Password is to long';
}
}
$password = md5($_POST['password']);
$loginquery = "SELECT * FROM regi WHERE username='$username' and password='$password'" or die(mysql_error());
$result = mysql_query($loginquery);
$count = mysql_num_rows($result);
mysql_close();
if($count==1){
$seconds = 2000 + time();
setcookie(loggedin, date("F jS - g:i a"), $seconds);
header("location:member.php");
} else {
echo 'Wrong username and password please try agian.';
}
}
?>
Pass the GET variable in your URL like..
header('Location:page.php?err=1');
exit;
On the other page use this
if(isset($_GET['err'] && $_GET['err'] == 1) {
echo 'Error Occured';
}
Here is a session based approach. This is the best way to pass messages from one page to another as they are stored in the user's session (a piece of data related to each user and stored in the server side) and not in the browser (like cookies or URL GET parameters, which can be easily corrupted), so it is really quite harder to manipulate the messages from 3rd parties.
Page process.php:
<?php
// Very top of your page
session_start();
$_SESSION['errors'] = array();
// Do stuff now...
// ...
// Hey it's a X error!
$_SESSION['errors']['X'] = 'Message for X error';
// Continue doing stuff...
// ...
// OMG! It's a Y error now!
$_SESSION['errors']['Y'] = 'Message for Y error';
// Keep doing stuff till you're done...
// All right, process is finished. Any Errors?
if (count($_SESSION['errors']) > 0) {
// It seems there's been any errors
// time to redirect to error-displaying page
header('Location: error-page.php');
exit;
}
Page error-page.php:
<?php
// Very top of your page
session_start();
// Let's check if there is any error stored in the session.
// In the case no errors found, it is better to redirect to another page...
// ...why anybody would end in this page if no errors were thrown?
if (!isset($_SESSION['errors']) || !is_array($_SESSION['errors']) || empty($_SESSION['errors'])) {
header('Location: home.php');
exit;
}
// If we reach this point it means there's at least an error
foreach ($_SESSION['errors'] as $errorCode => $errorMessage) {
// Here we can display the errors...
echo '<p>Error ', $errorCode, ': ', $errorMessage, '</p>', PHP_EOL;
}
// You can also do stuff only if a certain error is received
if (array_key_exists('X', $_SESSION['errors'])) {
// Error `X` was thrown
echo '<p>Oh no! It seems you suffered a X error!!</p>', PHP_EOL;
echo 'Click here to go back home.', PHP_EOL;
}
// At the end you should to remove errors from the session
$_SESSION['errors'] = array();
// or
unset($_SESSION['errors']);
You could use Alien's method, but it'd better if you use Session:
// Assume you init the session already; Use json_encode since you use array for $errors
$_SESSION['errors_msg'] = json_encode($errors);
header("location:member.php");
// Remember to exit here after we call header-redirect
exit;
Besides, there are a lot of problems is your currently code:
Use salt for hashing password
Use mysqli over mysql
Filtering input, escaping output
.. Read other recommendations here in this topic ..
Please read http://www.phptherightway.com/. There is a lot of right recommendation (of course not all) for PHP.