Upload database information with INSERT INTO - php

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!

Related

php chmod change an uploaded file permissions [chmod not working ]

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

Can't upload file using XAMPP

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());

can't download file from ftp with ftp_get (no error)

I'm trying to download file from ftp, but whatever i tried i couldn't download any file from ftp and it is not giving any error.
My code fetching file names from database and compares these file names with existing ftp file(names). If file name exist on ftp i want to download this file to my local-destination folder.
I can read ftp file names but i can't download them. Hope you can help me.
Here is my code
error_reporting(E_ALL);
$ftp_server = "xx.xx.y12.34"; //server
$bt = ftp_connect($ftp_server); // connect to ftp
$username = "myusername"; $pass = "mypass"; //username and password
$connection = ftp_login($bt, $username, $pass); // login ftp with username and password
ftp_pasv($bt, true);
if ((!$bt) || (!$connection)) {
echo "failed";
exit;
}else {
$path = "/1_Swatch Files/LG Swatches/";
$destination_folder = "/home/faruk/lasenza/media/color_samples/";
// mysql connection codes..
$results = $readConnection->fetchAll($query); // fetch file names from database
$contents_on_server = ftp_nlist($bt, $path);
foreach($results as $result){
$check_file_exist = $result["CLR_CODE"].".gif";
if(in_array($check_file_exist, $contents_on_server)) {
$server_file = $result["CLR_CODE"].".gif";
if (ftp_get($bt, $destination_folder , $server_file, FTP_BINARY)) {
echo 'Succeeded';
}else{
echo "There was a problem";
}
break;
}
}
}

How to avoid including login credentials on each php page, storing the credentials in a single page and adjusting code to match adjustments

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.

Creating a new page for each submission - PHP errors

Here is the site.
I have the submit page, and a form action to a page that queries the submission info into my database. I'll include that code below. What I want to do, is have it create an individual page for each submission. However, I'm getting tons of errors when I try to upload. It uploads but it definitely doesn't create new page. the I have a template form which I'll show you, but first, here's the upload page:
<?php
// For use in creating individual page
$tpl_file = "submission.php";
$tpl_path = "/~lyons/templates/";
$submissions_path = "/~lyons/submissions";
// For use in querying submitter name
$username = $_GET['username'];
session_start();
$_SESSION['username'] = $username;
//Database Information
$dbhost = "";
$dbname = "";
$dbuser = "";
$dbpass = "";
//Connect to database
mysql_connect ( $dbhost, $dbuser, $dbpass)or die("Could not connect: ".mysql_error());
mysql_select_db($dbname) or die(mysql_error());
$name = $_POST['name'];
$filename = $_POST['filename'];
$submitter = $username;
list($width, $height) = getimagesize("$filename");
$type = exif_imagetype($_POST['filename']);
$checkuser = mysql_query("SELECT filename FROM images WHERE filename='$filename'");
$filename_exist = mysql_num_rows($checkuser);
if($filename_exist > 0){
echo "I'm sorry but this image has already been submitted. Please feel free to try another.";
unset($filename);
include 'upload.php';
exit();
}
if (exif_imagetype($_POST['filename']) == IMAGETYPE_GIF) {
echo "Sorry, but we can't accept GIFs. Please feel free to try uploading another.";
unset($filename);
include 'upload.php';
exit();
}
$query = "INSERT INTO images (name, filename, submitter, width, height, type)
VALUES('$name', '$filename', '$submitter', '$width', '$height', $type)";
mysql_query($query) or die(mysql_error());
mysql_close();
echo "Thanks for your submission!<br/> Upload another <a href='/~lyons/upload.php'>here</a>!";
$placeholders = array("{name}", "{filename}", "{username}");
$tpl = file_get_contents($tpl_path.$tpl_file);
$new_member_file = str_replace($placeholders, $data, $tpl);
$php_file_name = $username.".php";
$fp = fopen($submissions_path.$php_file_name, "w");
fwrite($fp, $new_submission_file);
fclose($fp);
?>
And here's the template file (submission.php)
<html>
<title>{name}</title>
<head>
</head>
<body>
<h1>{name}</h1>
Posted by: {username}
<br/>
<img src="{filename}"/>
</body>
</html>
It looks like you might have a path issue. When you use the path "/~lyons" you may not be pointing to the directory you want. Try making the changes below:
// For use in creating individual page
$tpl_file = "submission.php";
//$tpl_path = "/~lyons/templates/";
$tpl_path = "templates/";
And then please post the new error message(s), if any.
To help you in debugging, try turning error reporting and error display on.
// add after <?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
Opening the file is probably failing, for better error control try this:
$fp = #fopen($submissions_path.$php_file_name, "w");
if (!$fp) {
die('Failed to open file! Reason: ' . $php_errormsg);
}
I think your paths are incorrect, most likely the following 2 lines need to be changed to use a full path.
// change
$tpl_path = "/~lyons/templates/";
$submissions_path = "/~lyons/submissions";
// to
$tpl_path = $_SERVER['DOCUMENT_ROOT'] . "/~lyons/templates/";
$submissions_path = $_SERVER['DOCUMENT_ROOT'] . "/~lyons/submissions";
When you go to open the file, it is trying to open /~lyons/templates/ which is a directory that does not exist, it is probably something like /home/lyons/public_html/templates/ or /home/something/public_html/~lyons/templates or /usr/local/apache2/htdocs/~lyons/templates etc. $_SERVER['DOCUMENT_ROOT'] should fill in the correct value, but in few cases you may need to manually set the correct path and prepend it to your $tpl_path and $submissions_path.
**save the "submission.php" in root folder**
`$tpl_file = "submission.php";`
**create "templates/`" folder in root folder**
`$tpl_path = "templates/";`

Categories