File upload script not work

Discuss coding issues, and scripts related to PHP and MySQL.
mluci12
Posts: 39

File upload script not work

Hello
I have this file upload script and Mysql& PHP insert in database.Why don't work file upload?

Code: Select all

<?php require('includes/config.php');
$target_dir = "images/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
//if logged in redirect to members page
if( $user->is_logged_in() ){ header('Location: memberpage.php'); }

//if form has been submitted process it
if(isset($_POST['submit'])){
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
    if($check !== false) {
        echo "File is an image - " . $check["mime"] . ".";
        $uploadOk = 1;
    } else {
        echo "File is not an image.";
        $uploadOk = 0;
    }
}
{
	//very basic validation
	if(strlen($_POST['username']) < 3){
		$error[] = 'Username is too short.';
	} else {
		$stmt = $db->prepare('SELECT username FROM members WHERE username = :username');
		$stmt->execute(array(':username' => $_POST['username']));
		$row = $stmt->fetch(PDO::FETCH_ASSOC);

		if(!empty($row['username'])){
			$error[] = 'Username provided is already in use.';
		}

	}


	if(strlen($_POST['password']) < 3){
		$error[] = 'Password is too short.';
	}
	if(strlen($_POST['broker']) < 3){
		$error[] = 'Code is too short';
	}
	

	if(strlen($_POST['passwordConfirm']) < 3){
		$error[] = 'Confirm password is too short.';
	}

	if($_POST['password'] != $_POST['passwordConfirm']){
		$error[] = 'Passwords do not match.';
	}

	//email validation
	if(!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)){
	    $error[] = 'Please enter a valid email address';
	} else {
		$stmt = $db->prepare('SELECT email FROM members WHERE email = :email');
		$stmt->execute(array(':email' => $_POST['email']));
		$row = $stmt->fetch(PDO::FETCH_ASSOC);

		if(!empty($row['email'])){
			$error[] = 'Email provided is already in use.';
		}

	}
	$imagename=$_FILES["myimage"]["name"]; 

//Get the content of the image and then add slashes to it 



	//if no errors have been created carry on
	if(!isset($error)){

		//hash the password
		$hashedpassword = $user->password_hash($_POST['password'], PASSWORD_BCRYPT);

		//create the activasion code
		$activasion = md5(uniqid(rand(),true));

		try {

			//insert into database with a prepared statement
			$stmt = $db->prepare('INSERT INTO members (username,password,email,active,cod) VALUES (:username, :password, :email, :active, :broker)');
			$stmt->execute(array(
				':username' => $_POST['username'],
				':password' => $hashedpassword,
				':email' => $_POST['email'],
				':broker' => $_POST['broker'],
				
				':active' => $activasion
			));
			$nr=0;
			$id = $db->lastInsertId('memberID');
			//send email
			$to = $_POST['email'];
			$subject = "Registration Confirmation";
			$body = "<p>Thank you for registering at Reconnect app</p>
			<p>To activate your account, please click on this link: <a href='".DIR."activate.php?x=$id&y=$activasion'>".DIR."activate.php?x=$id&y=$activasion</a></p>
			<p>Regards madustech.com</p>";

			$mail = new Mail();
			$mail->setFrom(SITEEMAIL);
			$mail->addAddress($to);
			$mail->subject($subject);
			$mail->body($body);
			

			$mail->send();

			//redirect to index page
			header('Location: index.php?action=joined');
			exit;

		//else catch the exception and show the error.
		} catch(PDOException $e) {
		    $error[] = $e->getMessage();
		}

	}

}

//define page title
$title = 'Demo';

//include header template
require('layout/header.php');
?>


<div class="form">

 <div ><img src="background.jpg" id="bg" alt=""/></div><br>

	
			<form role="form" method="post" action="" autocomplete="off"  class="login-form">
				<!-- <h2>Please Sign Up</h2> -->
				<p class="message">Already a member? <a href='login.php'>Login</a></p><br></br>	
			

				<?php
				//check for any errors
				if(isset($error)){
					foreach($error as $error){
						echo '<p class="bg-danger">'.$error.'</p>';
					}
				}

				//if action is joined show sucess
				if(isset($_GET['action']) && $_GET['action'] == 'joined'){
					echo "<h2 class='bg-success'>Registration successful, please check your email to activate your account.</h2>";
				}
				?>


	
<br></br>				
					<input type="number" name="username" id="username"  placeholder="Phone" value="<?php if(isset($error)){ echo $_POST['username']; } ?>" tabindex="1">
				
			
				
					<input type="email" name="email" id="email"  placeholder="Email" value="<?php if(isset($error)){ echo $_POST['email']; } ?>" tabindex="2">
				
					
							<input type="password" name="password" id="password"  placeholder="Password" tabindex="3">
					
					
						
							<input type="password" name="passwordConfirm" id="passwordConfirm"  placeholder="Confirm Password" tabindex="4">
						
								<input type="text" name="broker" id="broker"  placeholder="Your code" tabindex="4">
								

			<input type="file" name="fileToUpload" id="fileToUpload">

				<div >
					<div ><button type="submit" name="submit" value="Register" tabindex="5">Register</button></div>
				</div>
			</form>
	

</div>

	<script>
var usrname = document.getElementById('username');

//if #countryCode exiss, register change event
var ccode = document.getElementById('countryCode');
if(ccode){
  ccode.addEventListener('change', function(e){
    //adds the value of selected option in #usrname
    usrname.value = e.target.value;
  });
}
</script>

 <script src='http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script>

        <script src="js/index.js"></script>

<?php
//include header template
require('layout/footer.php');
?>

Admin Posts: 805
Hi,
That script cannot upload file because it not has the move_uploaded_file() function, that moves the file to the specified folder.
So, you need to add this code in your script, where you want the upload to be performed.

Code: Select all

if(move_uploaded_file($_FILES['fileToUpload']['tmp_name'], $target_file)) echo 'The file '. basename( $_FILES['fileToUpload']['name']). ' has been uploaded.';
else echo 'Sorry, there was an error uploading your file.';

mluci12 Posts: 39
How can i insert in database the name of file?
i have the insert here:

Code: Select all

$stmt = $db->prepare('INSERT INTO members (username,password,email,active,cod) VALUES (:username, :password, :email, :active, :broker)');
         $stmt->execute(array(
            ':username' => $_POST['username'],
            ':password' => $hashedpassword,
            ':email' => $_POST['email'],
            ':broker' => $_POST['broker'],
            
            ':active' => $activasion
         ));

Admin Posts: 805
First, in the mysql table create a column for the file name; for example "filename". Then, you can use this code:

Code: Select all

$stmt = $db->prepare('INSERT INTO members (username,password,email,filename,active,cod) VALUES (:username, :password, :email, :filename, :active, :broker)');
$stmt->execute(array(
':username' => $_POST['username'],
':password' => $hashedpassword,
':email' => $_POST['email'],
':filename' => basename($_FILES['fileToUpload']['name']),
':broker' => $_POST['broker'],
':active' => $activasion
));

mluci12 Posts: 39
don t work.Have you any other ideea?

Admin Posts: 805
Maybe the ":" in the array keys is wrong.
Try this, make sure you have the "filename" column in the "members" table; and check for $db /$stmt error.

Code: Select all

$stmt = $db->prepare('INSERT INTO members (username,password,email,filename,active,cod) VALUES (:username, :password, :email, :filename, :active, :broker)');
if(false===$stmt) echo 'prepare() failed: ' . htmlspecialchars($mysqli->error);
else {
  $rc = $stmt->execute(array(
    'username' => $_POST['username'],
    'password' => $hashedpassword,
    'email' => $_POST['email'],
    'filename' => basename($_FILES['fileToUpload']['name']),
    'active' => $activasion,
    'broker' => $_POST['broker']
  ));
  if(false===$rc) echo 'execute() failed: ' . htmlspecialchars($stmt->error);
}
- Not have orher ideea.

Similar Topics