Uploading multiple images to MySql database - php

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.

Related

How to Prevent Form Resubmission when page is refreshed or back button is clicked

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.

MySQLi update not working, mutilple colums and two where clauses

So I have been debugging this for over 30 minutes and I still can't figure out what I'm doing wrong. I just started using MySQLi and thats one of the things that I keep messing up. I think it might have something to do with preg_replace I have only used this once before so i still am not very good with it.
<?php
ob_start();
session_start();
include("../include/config.php");
include("../include/functions.php");
if (isset($_SESSION['pv1_session']) && $_SESSION['pv1_session'] == true) {
if (isset($_POST['submit'])) {
$uid = idinfo($_SESSION['pv1_user_id'],"idu");
$id = mysqli_real_escape_string($mysql, $_POST['fid']);
$post_name = mysqli_real_escape_string($mysql, $_POST['name']);
$post_tags = mysqli_real_escape_string($mysql, $_POST['tags']);
$name = preg_replace("/[^\w a-zA-Zа-яА-Я0-9._-]/u", "_", $post_name);
$tags = preg_replace("/[^\w a-zA-Zа-яА-Я0-9._-]/u", "_", $post_tags);
$file = preg_replace("/[^\wa-zA-Zа-яА-Я0-9._-]/u", "_", $post_name);
$update = mysqli_query($mysql,"UPDATE files SET name='$name', filename='$file', tags='$tags' WHERE user_id='$uid' AND filehash='$id'");
if (!$update) {
echo "<p>Unable to update file.</p>";
exit;
} else {
echo "<p>Success: Your uploaded file has been updated!</p>";
$pro_url = $web['url'].'/account/manage_uploads.php';
header("Location: $pro_url");
}
}
} else {
echo "ERROR: Please log in first!";
}
?>
Use "prepared statements" (http://php.net/manual/en/mysqli.quickstart.prepared-statements.php)
This gives you two advantages:
it handles the escaping for you (and also does it right: you do the escaping BEFORE the preg_replace, and that could go very wrong)
it also provides you with very easy debug. You put the parameters into an array, and you can simple echo out (print_r) the parameters array and see what your preg_replace has done.

Saving image location to MySQL DB in PHP

Been exhausting myself again trying to see what I'm doing wrong. I'm trying to upload a photo to my page and save its location to the mysql using prepared statements. My code is as follows
<?php
// First we execute our common code to connection to the database and start the session
require("common.php");
// At the top of the page we check to see whether the email is logged in or not
if(empty($_SESSION['email']))
{
// If they are not, we redirect them to the login page.
header("Location: ../index.html");
die("Redirecting to FrontPage");
}
$email = $_SESSION['email']['email'];
//Profile Image upload script
if(isset($_FILES['profilepic']))
{
if((($_FILES["profilepic"]["type"]=="image/jpeg") || ($_FILES["profilepic"]["type"]=="image/png") || ($_FILES["profilepic"]["type"]=="image/gif")) && ($_FILES["profilepic"]["size"] < 1048576))
{
$chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
$rand_dir_name = substr(str_shuffle($chars), 0, 15);
mkdir("userdata/profile_pics/$rand_dir_name");
if(file_exists("userdata/profile_pics/$rand_dir_name/".$_FILES["profilepic"]["name"]))
{
echo $_FILES["profilepic"]["name"]."Already exists";
}
else
{
move_uploaded_file($_FILES["profilepic"]["tmp_name"], "userdata/profile_pics/$rand_dir_name/".$_FILES["profilepic"]["name"]);
$profile_pic_name = $_FILES["profilepic"]["name"];
$queryProfilePic = "UPDATE db SET profilePic=:profile_Pic WHERE email = :email";
$query_params = array(':profile_Pic' => $rand_dir_name/$profile_pic_name,':email' => $email);
$stmt = $db->prepare($queryProfilePic);
$result = $stmt->execute($query_params);
//header("Location: profile.php");
}
}
else
{
}
}
?>
The image is uploaded to the randomly generated folder on the server however when I try to save the location of the file to the db I get a big goose egg.
You cannot divide these values:
$rand_dir_name/$profile_pic_name
I assume you want to concatenate them:
$rand_dir_name . '/' . $profile_pic_name
or you can use
"$rand_dir_name/$profile_pic_name"

Unable to share PHP variable

I am having trouble sharing a variable value between my main body of code and as function.
For this example, I want to upload an image to the DB with a value which matches the ID of the Place being used.
I currently grab the ID of the place being used from the URL using $_REQUEST and am attempting to write that to a variable 'mid' which I then send to the createthumnail function (contained in functions2.php), but the 'mid' value will not transfer for some reason.
To recreate:
Go to: http://www.students.bl.rdi.co.uk/stu26984/index.php
Login with: Username: Test Password: test123
Go to My Places
Click on WalkaboutSF link
Attempt to upload a file via the 'Choose File' button
Below is the full text of functions2.php
<?php
function createThumbnail2($filename, $mid) {
include 'base.php';
require 'config.php';
if(preg_match('/[.](jpg)$/', $filename)) {
$im = imagecreatefromjpeg($path_to_image_directory . $filename);
} else if (preg_match('/[.](gif)$/', $filename)) {
$im = imagecreatefromgif($path_to_image_directory . $filename);
} else if (preg_match('/[.](png)$/', $filename)) {
$im = imagecreatefrompng($path_to_image_directory . $filename);
}
$ox = imagesx($im);
$oy = imagesy($im);
$nx = $final_width_of_image;
$ny = floor($oy * ($final_width_of_image / $ox));
$nm = imagecreatetruecolor($nx, $ny);
imagecopyresized($nm, $im, 0,0,0,0,$nx,$ny,$ox,$oy);
if(!file_exists($path_to_thumbs_directory)) {
if(!mkdir($path_to_thumbs_directory)) {
die("There was a problem. Please try again!");
}
}
imagejpeg($nm, $path_to_thumbs_directory . $filename);
// $cookieUserx=$_SESSION['Username'];
// $checkCustidx=mysql_query("SELECT custid AS id from customers WHERE custUsername='".$cookieUserx."';");
// $rx=mysql_fetch_array($checkCustidx);
// $custidx=$rx['id'];
// $updateimage = mysql_query("UPDATE photos SET name = '".$filename."';")or die ('SQL Error: ' . mysql_error());
$updateimage = mysql_query("INSERT INTO photos (NAME, markerid) VALUES('".$filename."', '".$mid."');")or die ('SQL Error: ' . mysql_error());
if($updateimage)
{
header("Location: /WalkaboutSF/viewplace.php?place_id=%20".$mid."");
}
else
{
echo "<h1>Error</h1>";
}
$tn = '<img src="' . $path_to_thumbs_directory . $filename . '" alt="image" />';
echo $tn;
}
?>
also here is the code that calls that, from:
http://www.students.bl.rdi.co.uk/stu26984/viewplace.php?place_id=%20133
<div id="insertphoto">
<?php
require 'config.php';
require 'functions2.php';
$place_id = $_REQUEST['place_id'];
$view_place2 = mysql_query("SELECT * FROM markers WHERE id = '$place_id'");
$place2 = mysql_fetch_array($view_place2);
$mid= $place2['id'];
echo $mid;
if(isset($_FILES['fupload'])) {
if(preg_match('/[.](jpg)|(gif)|(png)$/', $_FILES['fupload']['name'])) {
$filename = $_FILES['fupload']['name'];
$source = $_FILES['fupload']['tmp_name'];
$target = $path_to_image_directory . $filename;
move_uploaded_file($source, $target);
createThumbnail2($filename, $mid);
}
}
?>
<h2>Add Photo</h2>
<form enctype="multipart/form-data" action="<?php print $_SERVER['PHP_SELF'] ?>" method="post">
<input type="file" name="fupload" />
<input type="submit" value="Go!" />
</form>
</div>
There are a few things that could be going on. Firstly:
$place2 = mysql_fetch_array($view_place2);
$mid= $place2['id'];
echo $mid;
Are you certain that $mid is being set here? Is it possible that the query returned no rows?
If you're sure it has a value here, then check this:
function createThumbnail2($filename, $mid) {
include 'base.php';
require 'config.php';
Are you sure that base.php or config.php are not overwriting the value of $mid? Try changing the code to this:
function createThumbnail2($filename, $mid) {
echo "mid before includes = $mid<br />\n";
include 'base.php';
require 'config.php';
echo "mid after includes = $mid<br />\n";
That will show you if your includes are stomping on your local variables.
edit: I didn't want to sidetrack the question, but your code is open to SQL injection. I could easily wipe your database by calling viewplace.php with a bad value. At the very least, do this:
$place_id = mysql_real_escape_string($_REQUEST['place_id']);
Your insert statement has the same issue. Look into using mysqli or PDO with prepared statements.
edit 2: The reason your code is not working is because there are 2 different HTTP requests working here: one to show the initial page and one to handle the POST to the upload form.
The issue is with the second request (the POST). This code is to blame:
<form enctype="multipart/form-data" action="<?php print $_SERVER['PHP_SELF'] ?>" method="post">
This is NOT passing the ID in $_REQUEST['place_id']. Just add this line below that one:
<input type="hidden" name="place_id" value=<?php echo HtmlspecialChars($_REQUEST['place_id']); ?>" />
This will pass the place_id to the second request, when the form is submitted.

Why do I get this error when trying to upload an image?

When I go to myserver index and upload and image from there using the interface, it works fine. But as soon as I try to enter the path myself, like:
http://myserver/upload.php?image['name']=F:\Bilder\6.jpg
it gives me an error that all fields are required. But I have to upload images like this, because I plan to implement it in an app that I'm making. Thing is, that I'm not that well acquainted with php.
here is the upload.php
<?php
session_start();
require("includes/conn.php");
function is_valid_type($file)
{
$valid_types = array("image/jpg", "image/jpeg", "image/bmp", "image/gif", "image/png");
if (in_array($file['type'], $valid_types))
return 1;
return 0;
}
function showContents($array)
{
echo "<pre>";
print_r($array);
echo "</pre>";
}
$TARGET_PATH = "images/";
$image = $_FILES['image'];
$image['name'] = mysql_real_escape_string($image['name']);
$TARGET_PATH .= $image['name'];
if ( $image['name'] == "" )
{
$_SESSION['error'] = "All fields are required";
header("Location: index.php");
exit;
}
if (!is_valid_type($image))
{
$_SESSION['error'] = "You must upload a jpeg, gif, or bmp";
header("Location: index.php");
exit;
}
if (file_exists($TARGET_PATH))
{
$_SESSION['error'] = "A file with that name already exists";
header("Location: index.php");
exit;
}
if (move_uploaded_file($image['tmp_name'], $TARGET_PATH))
{
$sql = "insert into Avatar (filename) values ('" . $image['name'] . "')";
$result = mysql_query($sql) or die ("Could not insert data into DB: " . mysql_error());
exit;
}
else
{
header("Location: index.php");
exit;
}
?>
and the index.php
<?php
if (isset($_SESSION['error']))
{
echo "<span id=\"error\"><p>" . $_SESSION['error'] . "</p></span>";
unset($_SESSION['error']);
}
?>
<form action="upload.php" method="post" enctype="multipart/form-data">
<p>
<label>Avatar</label>
<input type="file" name="image" /><br />
<input type="hidden" name="MAX_FILE_SIZE" value="100000" />
<input type="submit" id="submit" value="Upload" />
</p>
the problem lies in
if ( $image['name'] == "" )
$image has no value there.
You are doing a get request so if you would like to know what the image variable is you should use
$_GET['image']
Another thing is that you are doing $image = $_FILES['image'];
$_FILES will only be available from a post request.
Uploading files can not be done in the way you are doing now by a parameter from a GET request.
If you need to POST stuff to a web form (as opposed to GETting, which is what you're doing here), you can't just specify the data to be POSTed as part of the URL.
Have a look at those HTTP methods (GET and POST) to understand the difference.
In your app, what you need to do is POST stuff to the URL. Depending on which tools you use to program, you should look into how to send data via POST.
Also, try to see if an implementation of curl (or libcurl) is available to your development platform.
That simply wont work since you cannot upload an image by sending $_GET[] variables through the url.
As you can see in the upload.php page you got, the file is retrieved in the php page through a $_FILES['image'].
If you change that to $_GET['image'] and retry to post the link with the get variable you suggest, you probably will be able to see the path to your file but it will only be as a string type and not an actual uploaded file object.

Categories