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.
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'm currently working on a registration system and ran into some problem.
I'll start with pasting a simplified version of the code before:
session_start();
if (isset($_SESSION['logged_in'])) {
header('Location: #notLoggedIn');
exit;
} else {
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if //if field is empty {
//display error
} else if //check if any unallowed characters {
//display another error
} else {
//give the checked input a string/variable, ex: $name= ($_POST["name"]);
}
// Like 4-5 other checks running in the same way as above
}
$query = $pdo->prepare('INSERT INTO table (a, b, c, d, e) VALUES (?,?,?,?,?)');
$query->bindValue(1, $1);
$query->bindValue(2, $2);
$query->bindValue(3, $3);
$query->bindValue(4, $4);
$query->bindValue(5, $5);
$query->execute();
header('Location: index.php');
exit;
}
The problem is the fact that it runs everything at once and just redirects me to index.php.
How do I make sure it first of all checks if the form has been submitted before running.
After that I want it to check for any errors in ALL fields. If there are errors, stop.
But if there are no errors, just continue on and upload to my database.
I do think that I'm on a goodway, but currently pretty stuck, any help or push in the correct direction would be awesome!
Thank you!
Your question isn't exactly clear, nor is your code which is also incomplete (where is the form?).
You seem to be at an early stage of learning the form handling, and likely would benefit from further reading and testing before you ask specific questions.
Here are some starters:
http://en.wikipedia.org/wiki/Post/Redirect/Get
What's the best method for sanitizing user input with PHP?
The definitive guide to form-based website authentication
I'll give some info anyway, as have some free time.
For example, your first if checks if session IS set, if TRUE redirect to notLoggedIn. Are you sure this is intentional? Either they're logged in, echo message to suit, or not and so show the reg page (most sites show a login and reg on the same page, for convenience for all scenarios).
As this is a registration form, surely you meant if IS logged in then redirect to YouAreAlreadyLoggedIn?
In fact, I'd just exit a message "You are already logged in" then stop the script.
The problem is the fact that it runs everything at once and just redirects me to index.php.
That's because it has no other option, as at the end of your script after XYZ it redirects to index.php.
If you do not want it to do this then change it. Either don't redirect, handle the entire process more constructively, or exit at some point you need it to (like form errors).
How do I make sure it first of all checks if the form has been submitted before running.
I don't see a form, so don't know exactly what you are doing to advise.
Ideally you'd use the PRG (Post Redirect Get).
http://en.wikipedia.org/wiki/Post/Redirect/Get
Your Script
I've edited your script to make this an answer to the question, and tidied it up a little.
e.g. in your script, specifically at the top, you don't need the else as there's an exit() in the if. When the if returns true, the script will stop, otherwise (with or without an else) it will continue.
The code:
session_start();
if (isset($_SESSION['logged_in']))
{
exit('You are already logged in');
}
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
if ( strlen($POST['field_name']) < 4 )
{
exit('Minimum 4 chars required');
}
elseif ( strlen($POST['field_name']) > 20 )
{
exit('Max of 20 chars allowed');
}
elseif ( preg_match("/^[A-z0-9]+$/", $POST['field_name']) != 1 )
{
exit('Invalid chars - allowed A-z and 0-9 only');
}
else
{
// Not sure what you want here
// If all ok (no errors above)
// then sanatise the data and insert into DB
}
}
As for entering into the DB, you need much more checking and handling of the entire process before you just allow the DB stuff to run.
Not sure why you redirect to index.php. You'd then need to handle form submission results in index.php to tell user you are registered.
On the form page, tell them the errors they have in the fields, or echo out the success message and what happens next (i.e. go to your account page, or (hopefully) confirm the email you sent before logging in).
As for the validation checks in the POSTed form data, it's entirely up to you what you need. But I've given you some very basic to go on. Make sure your max set in the form matches the database column allowance, or if (eg) DB varchar is set to 15 and you allow users to enter 20, the data they enter will be truncated, and they'll register, but never be able to login (or some other data will be broken, their name/username etc).
got bored. this is not for internet points.
<?php
// create table user (userid int auto_increment primary key, username varchar(60), password varchar(60));
// alter table user add constraint uc_user_username unique (username);
var_dump($_POST);
$user = isset($_POST['username']) ? trim($_POST['username']) : '';
$pass = isset($_POST['password']) ? trim($_POST['password']) : '';
$pass2 = isset($_POST['confirm']) ? trim($_POST['password2']) : '';
$action = isset($_POST['action_type']) ? $_POST['action_type'] : '';
if (empty($_POST)) {
// nothing posted
}
else {
if (empty($user)) {
error('you did not provide a username');
}
elseif (empty($pass)) {
error('you did not provide a password');
}
else {
$mysqli = mysqli_connect('localhost','root','','test')
or die('Error ' . mysqli_error($link));
if ($action=='new_user') {
$userdata = get_user_info($mysqli,$user);
if ($userdata) {
error('user already exists');
}
else {
$validpass = validate_password($pass);
if ($validpass && $pass==$pass2){
if (make_new_user($mysqli,$user,$pass)) {
print "<br/>new user created<br/><br/>";
}
}
else error('passwords did not match');
}
}
elseif ($action=='login_user') {
$verified = verify_credentials($mysqli,$user,$pass);
if ($verified) {
print "<br/>user logged in<br/><br/>";
}
}
elseif ($action=='update_pass') {
$verified = verify_credentials($mysqli,$user,$pass);
$validpass = validate_password($pass);
if ($verified && $validpass && $pass!=$pass2) {
if (update_password($mysqli,$user,$pass,$pass2)) {
print "<br/>new user created<br/><br/>";
}
}
else error('cannot update to same password');
}
$mysqli->close();
}
}
function error($message) {
print "<br/>$message<br/><br/>";
}
function update_password($mysqli,$user,$pass,$pass2) {
$hash = password_hash($pass, PASSWORD_BCRYPT);
$stmt = $mysqli->prepare('update user set password = ? where username = ?');
$stmt->bind_param('ss',$user,$hash);
$stmt->execute();
$msql_error = $mysqli->error;
$updated = !(empty($msql_error));
error($msql_error); // for debugging only
return $updated;
}
function make_new_user($mysqli,$user,$pass) {
$userid = false;
$hash = password_hash($pass, PASSWORD_BCRYPT);
$stmt = $mysqli->prepare('insert into user (username,password) values (?,?)');
$stmt->bind_param('ss',$user,$hash);
$stmt->execute();
$msql_error = $mysqli->error;
if (empty($msql_error)) {
$userid = $mysqli->insert_id;
}
else error($msql_error); // for debugging only
return $userid;
}
// really, this should be done with javascript instantaneously
function validate_password($pass) {
$error = false;
if (strlen($pass) < 8) {
error('please enter a password with at least 8 characters');
}
elseif (!preg_match('`[A-Z]`', $pass)) {
error('please enter at least 1 capital letter');
}
else $error = true;
return $error;
}
function verify_credentials($mysqli,$user,$pass) {
$row = get_user_info($mysqli,$user);
$verified = false;
if ($row) {
if (password_verify($pass, $row['pass'])) {
$verified = true;
}
}
else error('username and password did not match');
return $verified;
}
function get_user_info($mysqli,$user) {
$row = array();
$stmt = $mysqli->prepare('select userid, username, password
from user
where username = ?');
$stmt->bind_param('s',$user);
$stmt->execute();
$stmt->bind_result($row['userid'],$row['user'],$row['pass']);
if (!$stmt->fetch()) $row = false;
$stmt->close();
return $row;
}
?>
<body>
<form action='?' method='post'>
<table id='input_table'>
<tr><td><span>username </span></td><td><input id='username' name='username' type='text' value='<?php echo $user ?>'></td></tr>
<tr><td><span>password </span></td><td><input id='password' name='password' type='text' value='<?php echo $pass ?>'></td></tr>
<tr><td><span>password2</span></td><td><input id='password2' name='password2' type='text' value='<?php echo $pass2 ?>'></td></tr>
<tr><td> </td><td> </td></tr>
<tr><td colspan=2>this just picks the action for testing... you wouldn't keep it around</td></tr>
<tr><td><input type='radio' name='action_type' value='new_user' <?php echo $action=='new_user'?'checked':'' ?>>New User</td></tr>
<tr><td><input type='radio' name='action_type' value='login_user' <?php echo $action=='login_user'?'checked':'' ?>>Logging In</td></tr>
<tr><td><input type='radio' name='action_type' value='update_pass' <?php echo $action=='update_pass'?'checked':'' ?>>New Password</td></tr>
<tr><td> </td><td> </td></tr>
<tr><td colspan=2><input id='submit' name='submit' type='submit'/></td></tr>
</form>
</body>
// error = 0 means no error found you can continue to upload...
if ($_FILES['file']['error'] == 0) {
}
Here are all of the errors explained: http://php.net/manual/en/features.file-upload.errors.php
UPLOAD_ERR_OK Value: 0; There is no error, the file uploaded with success.
UPLOAD_ERR_INI_SIZE Value: 1; The uploaded file exceeds the
upload_max_filesize directive in php.ini.
UPLOAD_ERR_FORM_SIZE Value: 2; The uploaded file exceeds the
MAX_FILE_SIZE directive that was specified in the HTML form.
UPLOAD_ERR_PARTIAL Value: 3; The uploaded file was only partially uploaded.
UPLOAD_ERR_NO_FILE Value: 4; No file was uploaded.
UPLOAD_ERR_NO_TMP_DIR Value: 6; Missing a temporary folder. Introduced in PHP 5.0.3.
UPLOAD_ERR_CANT_WRITE Value: 7; Failed to write file to disk. Introduced in PHP 5.1.0.
UPLOAD_ERR_EXTENSION Value: 8; A PHP extension stopped the file
upload. PHP does not provide a way to ascertain which extension caused
the file upload to stop; examining the list of loaded extensions with
phpinfo() may help. Introduced in PHP 5.2.0.
To validate input fields
if(empty($_POST['name'])&&empty($_POST['password'])){
//fields empty show error here
}else if (is_numeric($username[0])){
echo 'First character must be a letter';
}
else if (!preg_match('/^[a-zA-Z0-9]+$/', $username)) {
echo 'Only letters and numbers are allowed';
}else if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo 'Invalid email address.';
}else if(!preg_match("/^[\pL\s,.'-]+$/u", $name)) {
echo 'Invalid name.';
}
I'm working on a Captcha class and i'm almost done, there is one thing that doesn't work
In the file where I put the form, I start with this line:
include 'captcha.php';
$captcha = Captcha::tryCaptcha(2,4,'#000', '#ffffff');
and this is the captch construct:
static $do_generate = TRUE;
function __construct($aantal_letters = 2, $aantal_cijfers = 4, $voorgrond = '#000000', $achtergond = '#ffffff') {
session_start();
if (self::$do_generate == TRUE) {
$letters = substr(str_shuffle('ABCDEGHJKLMNPQRSTUVWXYZ'),0 ,$aantal_letters);
$cijfers = substr(str_shuffle('23456789'),0 ,$aantal_cijfers);
$imgbreed = 18 * ($aantal_letters + $aantal_cijfers);
$_SESSION['imgbreed'] = $imgbreed;
$_SESSION['captcha'] = $letters . $cijfers;
$_SESSION['voorgrond'] = $this->hex2rgb($voorgrond);
$_SESSION['achtergond'] = $this->hex2rgb($achtergond);
}
}
so in other words I put my stuff in a session if the static var $do_generate == TRUE
So when I post the form, the captcha is getting checked by a procesor.php
like this:
if (Captcha::captcha_uitkomst() == TRUE) {
echo "Great";
} else {
echo "Wrong";
}
And this is the captcha function that checks the etered captcha code:
static function captcha_uitkomst() {
if (strcmp($_SESSION['captcha'], strtoupper(str_replace(' ', '', $_POST['captcha-invoer']))) == 0) {
return TRUE;
} else {
echo "test";
self::$do_generate = FALSE;
return FALSE;
}
}
If I enter a correct captcha code, it's all good, that works I get the echo great.
If wrong I get the echo Wrong,
Perfect, but.... when I go back to form (hit backspace one history back) to enter a correct captcha, it regenerates a new captcha.
In the class: captcha_uitkomst you see that I made the self::do_generate FALSE
And the echo 'TEST' works when it's false, (just for checking)
What am I doing wrong
When you hit "back", the page is reloaded. You get a new CAPTCHA.
The premise of your question is fundamentally flawed, as you have just randomly assumed that this shouldn't happen, whereas in reality this is entirely by design.
It wouldn't be a very effective CAPTCHA if you could repeatedly get it wrong then go back and try again; any bot could just start brute forcing it and learning from the experience.
I am making a login system and I have a form with some validation.
However my form seems to be failing to pass the validation even though the data input should pass easily.
See:
http://marmiteontoast.co.uk/fyp/login-register/index.php
When you input a username, it should be over 3 characters. But even if you enter one really long you get the error message: The username is less than 3 characters.
EDIT: There was an issue in my copying from formatting that caused a missing }. I've corrected this. It wasn't the issue.
This is the if statement for the username pass. So it seems like it is not getting past the first test:
if (isset($_POST['username'])){
$username = mysql_real_escape_string(trim($_POST['username']));
$_SESSION['status']['register']['username'] = $username;
if(strlen($username) > 3){
if(strlen($username) < 31){
if(user_exists($username) === true){
$_SESSION['status']['register']['error'][] = 'That username is already taken. Sorry, please try again with a different username.';
}else{
// passed
}
} else {
$_SESSION['status']['register']['error'][] = 'The username is greater than 30 characters.';
}
} else {
$_SESSION['status']['register']['error'][] = 'The username is less than 3 characters.';
}
} else {
$_SESSION['status']['register']['error'][] = 'The username is not entered.';
}
And this is the HTML for the username:
<form method="post" action="register.php">
<div class="username">
<label class="control-label" for="inputUser">Username</label>
<input type="text" id="inputUser" name="username" placeholder="Username" value="<?php echo $usern_value; ?>" />
</div>
You can see the site here: http://marmiteontoast.co.uk/fyp/login-register/index.php
Session
The index page does use sessions.
It starts with this:
<?php
session_start();
?>
And kills the session at the end of the file:
<?php
unset($_SESSION['status']);
?>
But in the file it starts new sessions which store the inputs. This is so if you make a mistake, it still holds your info so you can adjust it rather than having the fill in the form again. Here is an example of where it grabs the username and saves it, then outputs it.
<?php
if(isset($_SESSION['status']['register']['username'])){
$usern_value = $_SESSION['status']['register']['username'];
} else {
$usern_value = "";
}
?>
value="<?php echo $usern_value; ?>" />
This is the user-exists function:
function user_exists($username){
$sql = "SELECT `id` FROM `users` WHERE `username` = '".$username."'";
$query = mysql_query($sql);
$result = mysql_num_rows($query);
if($result == 1){
// username does already exist
return true;
}else{
// username doesn't exist in the database
return false;
}
}
Ah, I can see the problem from your website link. When the error pops up ("The username is less than 3 characters."), try refreshing your browser. I expected to receive a browser warning that says the data would be resubmitted to the server — because you are in a post form — but I did not.
So, what does this mean? It means that immediately after validation failure, you are redirecting back to the same screen, and — unless you are using a session to preserve this information — your $_POST data will be lost. Commonly in the case of validation failure with this sort of form, you must prevent that redirect and render inside the post operation, which keeps the user's input available to you. The redirect should only occur if the form input was successful (i.e. it saves to the data and/or sends an email).
Edit: I should have seen the $_SESSION in the original post. OK, so the strategy is to write things to the session, redirect regardless of validation outcome, and to save error messages to the session. I wonder whether you are not resetting the session errors array when you're posting the form? Immediately after your first if, try adding this:
if (isset($_POST['username'])){
$_SESSION['status']['register']['error'] = array(); // New line
Unless you have something to make the session forget your errors, they will be stored until you delete your browser's cookie.
You have missed a closing brace } on this line:
if(user_exists($username) === true){
} else{// **missed the closing brace before the else**
// passed
}
Why is your logic so complex?
if (strlen($username) < 3) {
// too short
} elseif (strlen($username) > 31) {
// too long
} elseif (true === user_exists($username)) {
// already registered
} else {
// passed
}
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");
}