Everything was working fine until i decided to add a new product and nothing works , the picture is uploading to the folder but the problem is coming from the move_uploaded_file function , the thing is the function is working and moving pictures but the code is not moving to the next instruction does anyone have an idea about this error ?
<?php
if ($_POST) {
$productName = $_POST['productName'];
$quantity = $_POST['quantity'];
$rate = $_POST['rate'];
$brandName = $_POST['brandName'];
$categoryName = $_POST['categoryName'];
$genderName = $_POST['genderName'];
$sizeName = $_POST['sizeName'];
$productStatus = $_POST['productStatus'];
$type = explode('.', $_FILES['productImage']['name']);
$type = $type[count($type) - 1];
$url = '../assests/images/stock/' . uniqid(rand()) . '.' . $type;
if (in_array($type, ['gif', 'jpg', 'jpeg', 'png', 'JPG', 'GIF', 'JPEG', 'PNG'])) {
if (is_uploaded_file($_FILES['productImage']['tmp_name'])) {
if (move_uploaded_file($_FILES['productImage']['tmp_name'], $url)) {
$sql = "INSERT INTO product (product_name, product_image, brand_id, categories_id, quantity, price, active, status,gender_id,size_id,description,dateadded,discount)
VALUES ('$productName', '$url', '$brandName', '$categoryName', '$quantity', '$rate', '$productStatus', 1,'$genderName','$sizeName')";
if ($connect->query($sql) === true) {
echo "<SCRIPT type='text/javascript'> //not showing me this
alert('Product added !');
window.location.replace(\"http://localhost/stock/product.php\");
</SCRIPT>";
} else {
$valid['success'] = false;
$valid['messages'] = "Error while adding the members";
}
} else {
echo "lool";
}
}
}
$connect->close();
}
?>
I don't see the variable $connect declared anywhere in your code. It is possible that you have error reporting disabled and the script dies on
if ($connect->query($sql) === true) {
because $connect is undefined?
Related
I'm working on getting images from the database, which I've been saving as an url from the server it's been getting saved on.
There's this upload image section on the form, which is saving the images on a server and its url is getting saved in the database.
Here's the code:
$fileName = "";
$target_dir="/home/web/newsletter/uploads/";
$target_file_cv = $target_dir . basename($_FILES['fileToUpload']['name']);
if(!empty($_FILES['fileToUpload']['name']))
{
if (move_uploaded_file($_FILES['fileToUpload']['tmp_name'], $target_file_cv)) {
$fileName= $target_file_cv;
} else {
echo $twig->render("App/error.twig");
}
}
$conn = DB::databaseConnection();
$conn->beginTransaction();
$sqlInsert = "INSERT INTO dbo.form (photo) VALUES (:fileToUpload)";
$stmt = $conn->prepare($sqlInsert);
$stmt->bindParam(':fileToUpload', $fileName);
if ($stmt->execute()) {
$conn->commit();
return true;
} else {
return false;
}
?>
Here, I want to edit the file Name before it goes to the database. Like now it is saving as "/home/web/newsletter/uploads/pic.jpg" but I want it to be saved as "newsletter/uploads/pic.jpg".
I referred to a few questions here and got everything else working but just got stuck at hard coding the file's name here. Any help would be appreciated. TIA
$fileName = implode(array_slice(explode("/",$target_file_cv),3),"/");
Okay I got it:
Changed the code to:
$fileName = "";
$target_dir="/home/web/newsletter/uploads/";
$target_file_cv = $target_dir . basename($_FILES['fileToUpload']['name']);
if(!empty($_FILES['fileToUpload']['name']))
{
if (move_uploaded_file($_FILES['fileToUpload']['tmp_name'], $target_file_cv)) {
$fileName= "newsletter/uploads/" . $_FILES['fileToUpload']['name'];
} else {
echo $twig->render("App/error.twig");
}
}
$conn = DB::databaseConnection();
$conn->beginTransaction();
$sqlInsert = "INSERT INTO dbo.form (photo) VALUES (:fileToUpload)";
$stmt = $conn->prepare($sqlInsert);
$stmt->bindParam(':fileToUpload', $fileName);
if ($stmt->execute()) {
$conn->commit();
return true;
} else {
return false;
}
?>
I tried to upload video filenames and other variables to the database, but the insert statement won't work. Anyway the videofile-name and the thumbnail-filename are both uploaded to the right folders.
I've checked and there's nothing wrong with the sql statement. But why won't it work can anyone tell me?
PHP code
<?php
session_start();
if (isset($_POST['submit'])) {
$videoName = $_POST['videoName'];
$videoDesc = $_POST['description'];
$category = $_POST['category'];
$level = $_POST['level'];
$userId = $_SESSION['userId'];
$videoFile = $_FILES["videoFile"];
$videoFileName = $videoFile['name'];
$videoFileType = $videoFile['type'];
$videoFileTempName = $videoFile['tmp_name'];
$videoFileError = $videoFile['error'];
$videoFileExt = explode(".", $videoFileName);
$videoFileActualExt = strtolower(end($videoFileExt));
$videoAllowed = array("mp4", "mov", "avi");
$thumbFile = $_FILES["thumbnail"];
$thumbFileName = $thumbFile["name"];
$thumbFileType = $thumbFile["type"];
$thumbFileTempName = $thumbFile["tmp_name"];
$thumbFileError = $thumbFile["error"];
$thumbFileExt = explode(".", $thumbFileName);
$thumbFileActualExt = strtolower(end($thumbFileExt));
$thumbAllowed = array("jpg", "jpeg", "png");
if (in_array($videoFileActualExt, $videoAllowed)) {
if(in_array($thumbFileActualExt, $thumbAllowed)) {
if ($videoFileError === 0) {
if ($thumbFileError === 0) {
$videoFullName = $videoFile . "." . uniqid("", true) . "." . $videoFileActualExt;
$videoFileDestination = "../video/" . $videoFullName;
$thumbFullName = $thumbFile . "." . uniqid("", true) . "." . $thumbFileActualExt;
$thumbFileDestination = "../thumbnail/" . $thumbFullName;
include 'dbh.inc.php';
if(empty($videoName) or empty($videoDesc)) {
header("Location: ../uploadVideo.php?upload=empty");
exit();
} else {
move_uploaded_file($videoFileTempName, $videoFileDestination);
move_uploaded_file($thumbFileTempName, $thumbFileDestination);
$sql = "INSERT INTO video (filnavn, thumbnail, videoName, descript, idMusician, categoryName, idLevel) VALUES ('$videoFullName', '$thumbFullName', '$videoName', '$videoDesc', $userId, '$category', $level);";
mysqli_query($conn, $sql);
header("Location: ../uploadVideo.php?upload=success");
exit();
}
} else {
echo "You had a thumbnail error!";
exit();
}
} else {
echo "You had a video error!";
exit();
}
} else {
echo "You need to upload a proper thumbnail file type";
exit();
}
} else {
echo "You need to upload a proper video file type!";
exit();
}
} else {
}
You cannot insert or in this way in the if() condition, you must always use the logical operator as
if(empty($videoName) || empty($videoDesc))
Because of that your execution of code must have stopped at that point.
I have a simple form for submitting some data into the MySQL DB. On local machine works just fine, but inside a Wordpress page template doesn't work anymore, without getting me any error. The form is inside a page "sitename.com/upload" and i get redirected after submit to the same page (as shown in the link bar), but with 404 page content. I tried without get_header();and get_footer();tags because I thought it may conflict with some variables from wp, but I got the same result.
Here is the code:
<?php function renderForm($name, $price, $error)
{
// if there are any errors, display them
if ($error != '')
{
echo '<div style="padding:4px; border:1px solid red; color:red;">'.$error.'</div>';
}
?>
***** LONG HTML FORM IS HERE *****
<?php
}
// connect to the database
include('connect-db.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']))
{
// get form data, making sure it is valid
$name = mysqli_real_escape_string($connection, htmlspecialchars($_POST['name']));
$price = mysqli_real_escape_string($connection, htmlspecialchars($_POST['price']));
$shortdesc = mysqli_real_escape_string($connection, htmlspecialchars($_POST['shortdesc']));
$longdesc = mysqli_real_escape_string($connection, htmlspecialchars($_POST['longdesc']));
$current_version = mysqli_real_escape_string($connection, htmlspecialchars($_POST['current-version']));
$content_rating = $_POST['contentrating'];
if(isset($_POST['category'])) {
$category = implode(",", $_POST['category']);
} else {
$category = "";
}
if(isset($_POST['platform'])) {
$platform = implode(",", $_POST['platform']);
} else {
$platform = "";
}
if(isset($_POST['devices'])) {
$devices = implode(",", $_POST['devices']);
} else {
$devices = "";
}
if(isset($_POST['gamemodes'])) {
$gamemodes = implode(",", $_POST['gamemodes']);
} else {
$gamemodes = "";
}
//FILE UPLOAD
$images = array();
if(isset($_FILES['files'])){
$errors= array();
foreach($_FILES['files']['tmp_name'] as $key => $tmp_name ){
$file_name =$_FILES['files']['name'][$key];
$file_size =$_FILES['files']['size'][$key];
$file_tmp =$_FILES['files']['tmp_name'][$key];
$file_type=$_FILES['files']['type'][$key];
if($file_size > 2097152){
$errors[]='File size must be less than 2 MB';
}
$desired_dir="uploads/images";
if(empty($errors)==true){
if(is_dir($desired_dir)==false){
mkdir("$desired_dir", 0700); // Create directory if it does not exist
}
if(is_dir("$desired_dir/".$file_name)==true){
move_uploaded_file($file_tmp,"uploads/images/".$file_name);
}else{ //rename the file if another one exist
$file_name = time()."-".$file_name;
$new_dir="uploads/images/".$file_name;
rename($file_tmp,$new_dir) ;
}
$images[] = $file_name;
}else{
print_r($errors);
}
}
if(empty($error)){
$imglinks = implode(" | ", $images);
}
}
//FILE UPLOAD END
// check to make sure both fields are entered
if ($name == '' || $price == '')
{
// generate error message
$error = 'ERROR: Please fill in all required fields!';
// if either field is blank, display the form again
renderForm($name, $price, $error);
}
else
{
$sql = "INSERT INTO vr_submitted_apps ". "(name, price, shortdesc, longdesc, crtvers, rating, category, platform, devices, gamemodes, images, dtime) ". "VALUES('$name','$price','$shortdesc','$longdesc','$current_version','$content_rating','$category','$platform','$devices','$gamemodes', '$imglinks', NOW())";
// save the data to the database
mysqli_query( $connection, $sql )
or die(mysql_error());
$itemId = mysqli_insert_id($connection);
setcookie("last-inserted-id", $itemId, time() + (86400 * 3), "/"); // 86400 = 1 day
// once saved, redirect back to the view page
header("Location: uploader.html");
}
}
else
// if the form hasn't been submitted, display the form
{
renderForm('','','');
}
Problem solved: Wordpress has something important internal reserved for "name" parameter.
I have the bellow code which I was hoping to change/rename image name on upload to user id so I can avoid file overwrite and insert the name into database sadly after I added rename code the code is not able to upload image or update the database we out showing any error but if I remove the rename code everything was working.
Can one help me how to solve it or is there any better way I can do it?
<?php
$user_id = htmlentities($_SESSION['user']['id'], ENT_QUOTES, 'UTF-8');
$username = htmlentities($_SESSION['user']['username'], ENT_QUOTES, 'UTF-8');
require("connection.php");
if(#$_POST ['submit']) {
$file = $_FILES ['file'];
$name1 = $file ['name'];
$type = $file ['type'];
$size = $file ['size'];
$tmppath = $file ['tmp_name'];
if($type == 'jpeg' || $type == 'png' || $type == 'jpg') {
$name1 = $user_id.$type; // rename image
if($name1!="") {
if(move_uploaded_file ($tmppath, 'users/'.$name1)) {
$sql=("INSERT INTO USERS set photo='$name1' WHERE username='$username'");
mysql_query ($sql) or die ('could not updated:'.mysql_error());
echo ("Profile picture updated");
}
}
}
}
?>
You can try this, may be help you ...
<?php
$user_id = htmlentities($_SESSION['user']['id'], ENT_QUOTES, 'UTF-8');
$username = htmlentities($_SESSION['user']['username'], ENT_QUOTES, 'UTF-8');
require("connection.php");
if(#$_POST ['submit']) {
$file = $_FILES ['file'];
$name1 = time().$file ['name']; // rename image
$type = $file ['type'];
$size = $file ['size'];
$tmppath = $file ['tmp_name'];
if($type == 'image/jpeg' || $type == 'image/png' || $type == 'image/jpg') {
if($name1!="") {
if(move_uploaded_file ($tmppath, 'users/'.$name1)) {
$sql=("INSERT INTO USERS set photo='$name1' WHERE username='$username'");
mysql_query ($sql) or die ('could not updated:'.mysql_error());
echo ("Profile picture updated");
}
}
}
}}
?>
First of all change
$name1 = $user_id.$type;
to
$name1 = $user_id.".".$type;
And second of all clean up you sql.
Also. file_type is image/jpeg so that's why it doesn't work. It never goes past your if.
Create a switch to check the filetype or just take the last 3 characters of the file.
Try this to reorganise your $_FILES into an array you can understand and easily work with.
Shameless plug
https://gist.github.com/lukeoliff/5531772#file-quickrearrangefiles-php
<?php
function rearrangeFiles($arr) {
foreach($arr as $key => $all){
foreach($all as $i => $val){
$new[$i][$key] = $val;
}
}
return $new;
}
Used as such:
<?php
$user_id = htmlentities($_SESSION['user']['id'], ENT_QUOTES, 'UTF-8');
$username = htmlentities($_SESSION['user']['username'], ENT_QUOTES, 'UTF-8');
require("connection.php");
if(!empty($_POST) && !empty($_FILES)) {
$files = rearrangeFiles($_FILES)
foreach ($files as $key => $file) {
$name = $file['name'];
$type = $file['type'];
$size = $file['size'];
$tmppath = $file['tmp_name'];
if($type == 'jpeg' || $type == 'png' || $type == 'jpg') {
$name = time() . '_' . $user_id.'_'.$name.'.'.$type; // TIMESTAMP, USERID and FILENAME RENAME
if(!empty($name)) {
if(move_uploaded_file($tmppath, 'users/'.$name)) {
$sql = "INSERT INTO users (photo,username) values ('$name','$username')";
mysql_query($sql) or die('could not updated:'.mysql_error());
$successes[] = $file['name'] . " picture saved as " . $name;
}
}
}
}
if (!empty($successes)) {
echo implode('. ',$successes);
}
}
Further improved by inserting into database in a single query :) Also you really need to move from mysql_ functions to mysqli_ or PDO:: functions as per php.net http://www.php.net/manual/en/function.mysql-connect.php depreciating mysql_ functions soon.
you can use that one concept, but edit this as your requirement.
<?php
if ($_FILES['imagepath']['name'] != "")
{
$uploaddir = 'images/';
$uploadfile = $uploaddir . basename($_FILES['imagepath']['name']);
if (move_uploaded_file($_FILES['imagepath']['tmp_name'], $uploadfile))
{
$rename = $_FILES['imagepath']['name'];
$rename = rand(0,1500000000).$rename;
$filename = strtolower(($rename));
if (file_exists(($uploaddir.$_FILES['imagepath']['name'])))
rename(($uploaddir.$_FILES['imagepath']['name']), ($uploaddir.$filename));
echo $_FILES['imagepath']['name']." with name ".$filename." file uploaded successfully";
}
}
?>
i am having trouble trying to upload an image to a website, and update the database with the address of the image. All of the other fields are being correctly added to the database, except for the image address, and the image is not being saved in the images folder. I have absolutely no idea whats wrong, and when i try to upload an image it echoes there was a problem uploading your file. Thanks a lot for the help.
<?php
if($_REQUEST['submit'])
{
function isChecked($chkname,$value)
{
if(!empty($_POST[$chkname]))
{
foreach($_POST[$chkname] as $chkval)
{
if($chkval == $value)
{
return true;
}
}
}
return false;
}
$target = "~start/B7/images/";
$target = $target . basename( $_FILES['photo']['name']);
$age = $_POST["age"];
$brand = $_POST["brand"];
$model = $_POST["model"];
$price = $_POST["price"];
$vechicleType = $_POST["vechicleType"];
$fuelType = $_POST["fuelType"];
$transmition = $_POST["transmition"];
$doorsNumbers = $_POST["doorsNumbers"];
$mileage = $_POST["mileage"];
$pic = ($_FILES['photo']['name']);
//Connect to the server
$con = mysql_connect("*********", "*********", "*********")
or die('Could not connect:' . mysql_error());
// Select database
mysql_select_db("*********", $con)
or die('Could not select database');
// Select all the names from the database
$checkName = mysql_query("SELECT * FROM users");
while ($number = mysql_fetch_array($checkName))
{
$index = 0;
if (($number['user_name'] == $name) && ($number['password'] == $password)
|| isset($_SESSION['test']))
{
$index = 1;
$_SESSION['test']=$name;
$_SESSION['id']=$number['user_id'];
}
}
// Select all the names from the database
$checkName = mysql_query("SELECT * FROM used_cars");
if (!empty($model))
{
if(isChecked('extras', 'leather'))
$leather = "yes";
if(isChecked('extras', 'airCon'))
$airCon = "yes";
if(isChecked('extras', 'satNav'))
$satNav = "yes";
if(isChecked('extras', 'parkingSensors'))
$parking = "yes";
$insert1="INSERT INTO used_cars (manufacturer, model, price, image, vehicleType,
age, transmission, fuelType, doorsNumber, user_id, colour, mileage,
leatherSeat, navigatorSystem, parkingSensor, airConditioner) VALUES ('$brand', '$model', '$price', '$pic', '$vechicleType',
'$age', '$transmition', '$fuelType', '$doorsNumbers', '$user_id',
'$colour', '$mileage', '$leather', '$satNav', '$parking', '$airCon')";
if(move_uploaded_file($_FILES['photo']['tmp_name'], $target))
{
//Tells you if its all ok
echo "The file was uploaded";
}
else
{
//Gives an error if its not
echo "Sorry, there was a problem uploading your file.";
}
}
else
{
echo 'Please fill in all fields';
}
mysql_close($con);
}
?>
As explained further in the comments, your path should probably be images/