I have to create a CMS for a webstore for a webscript unit i'm taking. I have to upload a photo of the product but i keep getting and error when i try to upload. I search it a lot and tried a lot of things, i changed the folder to read & write, i did the 'chmod -R 777...', nothing. I'm starting to think the problem is with my code. I appreciate all help, thanks!
I always this error: Warning: File upload error - unable to create a temporary file in Unknown on line 0
<?php
$dbhost = '127.0.0.1';
$dbuser = 'root';
$dbpass = '';
$dbname = 'ezcart';
$conn = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
if ($conn->connect_error) {
die("Could not connect to the database: " . $conn->connect_error);
}
$name = $_FILES['photo']['name'];
$size = $_FILES['photo']['size'];
$type = $_FILES['photo']['type'];
$tmp_name = $_FILES['photo']['tmp_name'];
if (isset($name)) {
if(($type == 'image/jpeg' || $type == 'image/jpg' || $type = 'image/png') && ($size <= 3145728)) {
$path = 'prod_photos/';
if (move_uploaded_file($tmp_name, $path.$name)) {
$sql = "INSERT INTO product (prodCat, prodDes, prodNam, prodPho, prodPri, prodSto, prodSup) VALUES ('$_POST[prodCat]', '$_POST[prodDes]', '$_POST[prodNam]', '$name', '$_POST[prodPri]', '$_POST[prodSto]', '$_POST[prodSup]')";
if ($conn->query($sql) === TRUE) {
echo '<span>Product added sucessfully.</span>';
}
}
}
else {
echo '<span>Please choose a valid photo.</span>';
}
}
$conn->close();
?>
You should check your php.ini and look for the 'upload_tmp_dir' option.
After that, check the permission of your tmp dir, and try to chmod it again.
If you want to know what upload_tmp_dir your server is using, you can simply use this:
die(ini_get('upload_tmp_dir') ? ini_get('upload_tmp_dir') : sys_get_temp_dir());
Related
I am coding a site that users can upload images to view in a carousel and i made it to uploading a file
but i can't open it so first i thought the file was corrupt but when i open the properties i found out that the file was not corrupt by his Size so i used :-
chmod($path, octdec(0755));
but the file still not opening
the hole code :-
<?
$account = 'account';
$price = '10.5';
require_once 'Config.php';
$dbCon = "mysql:host=$host;dbname=$db_name";
$conn = new PDO($dbCon, $username, $password);
$msg ='';
$name = $_POST['name'];
echo $name;
if(isset($_POST['upload'])){
$image = $_FILES['image']['name'];
$path = 'upload/' .$image;
$query = $conn->prepare("INSERT INTO special (imageurl) VALUES ('$path')");
$query->execute();
if($query){
move_uploaded_file($_FILES['image']['tmp_name'],$path);
chmod($path, octdec(0755));
echo $path;
$msg = "Done";
}else{
$msg = "Error Some thing went Wrong!";
}
}
?>
BTW : i'm using Appserv 8.6.0 running on PHP 5.6.30
I am adding data from a file to my database. Currently the location of the files are limited to only those inside directory D:/. I want to be able to support adding files from multiple directories.
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "stdprt";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$filename = "d:/" . $_POST['fname'];
$handle = fopen($filename, "r");
while (($data = fgetcsv($handle)) !== FALSE) {
$num = count($data);
$row;
$sql = "INSERT into marks(regno,semister,subcode,subname,internals,externals,credits)values('$data[0]','$data[1]','$data[2]','$data[3]','$data[4]','$data[5]','$data[6]')";
//echo "INSERT into marks(regno,semister,subcode,subname,internals,externals,credits)values('$data[0]','$data[1]','$data[2]','$data[3]','$data[4]','$data[5]','$data[6]')";
if ($conn->query($sql) === TRUE) {
// echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
echo "<br>";
}
?>
<h2>Uploaded Successfully....</h2>
back
If you are wanting to choose a file in another drive you can modify this line in your code and change the directory at the start.
$filename="d:/".$_POST['fname'];
So for example if you wanted to change the directory to drive F it would be like so:
$filename="f:/".$_POST['fname'];
If you wanted to enable the ability to specify a custom directory in your request then you could pass it through the same way you are passing fname. Say for example you passed your custom directory along in a key named cust_dir you could add it as the directory like so.
if($_POST['cust_dir']{
$filename=$_POST['cust_dir'].$_POST['fname'];
} else {
$filename="d:/".$_POST['fname'];
}
The code above would use a custom directory path that you passed in the $_POST variable if you passed one. If you do not pass cust_dir then it will default to directory d:/.
this is my image upload code, it works fine but i have a problem putting the path in my database with the function "INSERT INTO", it doesn't work.
My image goes to the folder but the column 'Image' of the table 'pages' in my database is blank, no path uploaded.
Any advice?
<?php
# FileName="Connection_php_mysql.htm"
# Type="MYSQL"
# HTTP="true"
$hostname_localhost = "localhost";
$database_localhost = "database";
$username_localhost = "root";
$password_localhost = "";
$localhost = new mysqli($hostname_localhost, $username_localhost, $password_localhost);
if ($localhost->connect_error) {
die('Connect Error (' . $localhost->connect_errno . ') '. $localhost->connect_error);
}
?>
<?php
if(isset($_FILES['UploadFileField'])){
// Creates the Variables needed to upload the file
$UploadName = $_FILES['UploadFileField']['name'];
$UploadName = mt_rand(100000, 999999).$UploadName;
$UploadTmp = $_FILES['UploadFileField']['tmp_name'];
$UploadType = $_FILES['UploadFileField']['type'];
$FileSize = $_FILES['UploadFileField']['size'];
// Removes Unwanted Spaces and characters from the files names of the files being uploaded
$UploadName = preg_replace("#[^a-z0-9.]#i", "", $UploadName);
// Upload File Size Limit
if(($FileSize > 250000)){
die("Error - File to Big");
}
// Checks a File has been Selected and Uploads them into a Directory on your Server
if(!$UploadTmp){
die("No File Selected, Please Upload Again");
}else{
$move=move_uploaded_file($UploadTmp, 'images/'.$UploadName);
mysqli_query($localhost,"INSERT INTO pages (Image)
VALUES (/pages/images/.$UploadName)");
mysqli_close($localhost);
}
if($move) {
echo("file ".$UploadName." has been uploaded!");
echo("<br>/pages/images/".$UploadName);
}else {
exit("unable to upload the file" .$UploadName);
}
}
?>
Thank you!
I have been working on uploading picture to a folder and saving the file name and some meta info to a MySQL database. I got everything working on PHP but nothing changes on my database. I don't know what is wrong.
<?php
$servername = "localhost";
$username = "root";
$password = "pass";
$dbname = "poster";
$uploadOk = "0";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
if (isset($_POST['btn-upload'])) {
$owner = $_POST['userid'];
$file = rand(1000,100000)."-".$_FILES['file']['name'];
$file_loc = $_FILES['file']['tmp_name'];
$file_size = $_FILES['file']['size'];
$file_type = $_FILES['file']['type'];
$folder = "profile/";
if (!empty ($owner)) {
$uploadOk = 1;
} else {
echo "Are you sure you are not in the wrong place?";
$uploadOk = 0;
}
$new_size = $file_size/1024;
// new file size in KB
// make file name in lower case
$new_file_name = strtolower($file);
// make file name in lower case
$final_file=str_replace(' ','-',$new_file_name);
if ($file_type != 'jpg' ) {
$uploadOk = 1;
} else {
echo "Only jpg file type allowed.";
$uploadOk = 0;
}
}
if ($file_size > '5000') {
$uploadOk = 1;
} else {
echo "Your image file must be less than 5Mb";
$uploadOK = 0;
}
if (move_uploaded_file($file_loc,$folder.$final_file) && $uploadOk == 1) {
$sql = "UPDATE post SET `file`='$final_file', `type` = '$file_type' WHERE `userid`='$owner'";
if ($conn->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}
}
$conn->close();
?>
Html Result
Record updated successfully
Database
|userid | file|type|
| 1 | foo | foo|
It said record updated successfully but nothing gets updated in my database. What did I do wrong here?
p.s.
Yes I do know that I should be using PDO by now, but I just need to finish this as my first PHP project.
Thank you in advance.
You are jumping between procedural style and object oriented style with your queries; this may be part of your problem.
Try changing your connection to this:
$conn = new mysqli($servername, $username, $password, $dbname);
Incidentally, since you mention it, you don't necessarily have to use PDO for prepared statements. As you like mysqli, you can do it with these. You are already halfway there. After you've done the above, just do this:
$sql = $conn->prepare("UPDATE post SET `file`= ?, `type` = ? WHERE userid= ? ");
$sql->bind_param("ssi", $file, $file_type, $owner);
$sql->execute();
$sql->close();
The ssi above just refers to "string string integer" (or whatever file types you are using, assuming the first two are varchars, and the third is an INT). Basically you are setting the parameters for each file to go into your query; you don't need to remember whether to quote or not quote the variable depending on type, as you've defined it in the bind_param() below.
It's fairly self-explanatory, and not hard to learn. Like I said, you are halfway there.
I think you have just made a error in either you database design or the way you record the new upload.
UPDATE post SET `file`='$final_file', `type` = '$file_type' WHERE `userid`='$owner'";
This will amend an already created row. So you will only ever have one row per user, and therefore when the user uploads a second file it will over write the previous data.
Assuming the userid column is not defines as auto increment you should in fact be creating a new row for each file a user uploads with an INSERT query rather than an UPDATE like so
INSERT INTO post (userid,file,type)
VALUES ('$owner', '$final_file', '$file_type')
Now you will get a new row for this user for each file they upload.
I have the following code to do a simple image upload and store a few data, however I want to remove the section(s) of the code that have the direct database username password and host, with a simple include("config.php") in the heading. So what I am asking apart from the include("config.php") line how would I make adjustments to the code example:$conn = $db->prepare($query); an so on
<?php
include("config.php");
define('UPLOAD_PATH', $_SERVER['DOCUMENT_ROOT'] . 'photohandling/uploads/');
define('DISPLAY_PATH', '/photohandling/uploads/');
define('MAX_FILE_SIZE', 2000000);
$permitted = array('image/jpeg', 'image/pjpeg', 'image/png', 'image/gif','image/tiff');
$dames2=time();
$db_host = 'localhost';
$db_user = 'root';
$db_pass = 'password';
$db_name = 'test';
if (!empty($_POST)){
$fileName = $_FILES['userfile']['name'];
$tmpName = $_FILES['userfile']['tmp_name'];
$fileSize = $_FILES['userfile']['size'];
$fileType = $_FILES['userfile']['type'];
$fname=$_POST['fname'];
$lname=$_POST['lname'];
$age=$_POST['age'];
$acquirer_bin=$_POST['acquirer_bin'];
$terminal_id=$_POST['terminal_id'];
$trace_id=$_POST['trace_id'];
// get the file extension
$ext = substr(strrchr($fileName, "."), 1);
// generate the random file name
$randName = md5(rand() * time());
// image name with extension
$myfile = $acquirer_bin.$trace_id.$dames2.$randName . '.' . $ext;
// save image path
$path = UPLOAD_PATH . $myfile;
if (in_array($fileType, $permitted) && $fileSize > 0 && $fileSize <= MAX_FILE_SIZE) {
//store image to the upload directory
$result = move_uploaded_file($tmpName, $path);
if (!$result) {
echo "Error uploading image file";
exit;
} else {
$db = new mysqli("localhost", "root", "hynes21", "test");
if (mysqli_connect_errno()) {
printf("Connect failed: %s<br/>", mysqli_connect_error());
}
$query =
"INSERT INTO tester(fname,lname,age, acquirer_bin, terminal_id, trace_id,photo_name, size, type, file_path) VALUES(?,?,?,?,?,?,?,?,?,?)";
$conn = $db->prepare($query);
if ($conn == TRUE) {
$conn->bind_param("ssiisisiss",$fname,$lname,$age,$acquirer_bin,$terminal_id,$trace_id, $myfile, $fileSize, $fileType, $path);
if (!$conn->execute()) {
echo 'error insert';
} else {
echo 'Success!<br/>';
echo '<img src="' . DISPLAY_PATH . $myfile . '"/>';
}
} else {
die("Error preparing Statement");
}
}
} else {
echo 'error upload file';
}
} else {
echo 'error';
}
?>
You really shouldn't define database credentials in code. A solid why to do this is to use a configuration file. PHP provides a built in function called parse_ini_file that is perfect for retrieving data from config files (in a certain format ofc).
Here is an example of a ini file that can be parsed by parse_ini_file [docs]
[db]
host = localhost
user = root
pass = password
database = test
As you can see the format of the file is very similar to the php.ini file.
Keep this db.ini file in a place that is not accessible by the web server but can be read by PHP.
Here is a function that can utilize the data in the ini file and create a new mysqli object for you.
// somefile.php
function new_db() {
$info = parse_ini_file('db.ini', true);
return new mysqli($info['db']['host'],
$info['db']['user'],
$info['db']['pass'],
$info['db']['database']);
}
To use your new_db function.
require_once 'somefile.php';
$db = new_db();
$stmt = $db->prepare($query);
// ...
If I understand correctly, you want to use the values defined in config.php. If so, this is all you need to do:
config.php
define(DB_HOST, 'localhost');
define(DB_USER, 'root');
define(DB_PASS, 'hynes21');
define(DB_NAME, 'test');
php file from where config.php is included
Option 1:
$db_host = DB_HOST;
$db_user = DB_USER;
$db_pass = DB_PASS;
$db_name = DB_NAME;
$db = new mysqli($db_host, $db_user, $db_pass, $db_name);
Option 2:
$db = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
And yeah, a heap of ppl will tell you to use PDO instead of mysqli. Indeed you should, but that's doesn't give you an answer to your question :)
Let's say in your config.php file you have this:
$dbHost = 'localhost';
$dbUser = 'root';
$dbPass = 'hynes21';
$dbName = 'test';
Then in your code above you would replace this line:
$db = new mysqli("localhost", "root", "hynes21", "test");
with this:
$db = new mysqli($dbHost, $dbUser, $dbPass, $dbName);
and the rest of your code should just work, thanks to variable scoping.
You could also put the db connection in the config.php file as well, which would allow you to destroy the stored connection info variables so they wouldn't be hanging around anywhere for accidental output:
$dbHost = 'localhost';
$dbUser = 'root';
$dbPass = 'hynes21';
$dbName = 'test';
$db = new mysqli($dbHost, $dbUser, $dbPass, $dbName);
unset($dbHost);
unset($dbUser);
unset($dbPass);
unset($dbName);
This would mean every page load would have the overhead of calling mysqli(), even if that page didn't use the database. But if you have a data driven site then virtually every page will want to call mysqli() anyway so that's not such a big deal.
Later on you may want to look in to using a database wrapper so you don't have to store your DB connection in a locally scoped variable, but this approach will work just fine for simple applications.