I'm new to PHP and I'm learning from Headfirst PHP and MySQL book.
I've made a HTML form so the user can upload a file (in this case an image file).
Here is the code:
<?php
define('GW_UPLOADPATH', 'guitar/images/');
if(isset($_POST['submit'])) {
$name = $_POST['name'];
$score = $_POST['score'];
$screenshot = $_FILES['screenshot']['name'];
if(!empty($name) && !empty($score) && !empty($screenshot)) {
$target = GW_UPLOADPATH . $screenshot;
if(move_uploaded_file($_FILES['screenshot']['tmp_name'], $target)) {
$dbc = mysqli_connect('localhost', 'root', '', 'guitar')
or die('Error connecting to MySQL server');
$query = "INSERT INTO guitarwars VALUES (0, '$name', '$score', NOW(), '$screenshot')";
$result = mysqli_query($dbc, $query) or die('Error querying database.');
echo '<p>Thanks for adding your new high score!</p>';
echo '<p><strong>Name:</strong> ' . $name . '<br />';
echo '<strong>Score:</strong> ' . $score . '</p>';
echo '<img src="' . GW_UPLOADPATH . $screenshot . '" alt="Score image" /></p>';
echo '<p><< Back to high scores</p>';
$name = "";
$score = "";
$screenshot = "";
mysqli_close($dbc);
}else{
echo '<p class="error">Sorry, there was a problem uploading your screen shot image.</p>';
}
}else{
echo '<p class="error">Please enter all of the information to add ' .
'your high score.</p>';
}
}
?>
When I put the index.php & images folder in the root folder of server everything is ok.
But when I create a directory (in this case: guitar folder) in htdocs folder (server root folder) and put project files in that directory the problem shows up.
Problem is that when user upload image file it does NOT go to images folder and this error shows up:
Warning: move_uploaded_file(guitar/images/jacobsscore.gif): failed to open stream: No such file or directory in C:\xampp\htdocs\guitar\addscore.php on line 35
Warning: move_uploaded_file(): Unable to move 'C:\xampp\tmp\phpE3BE.tmp' to 'guitar/images/jacobsscore.gif' in C:\xampp\htdocs\guitar\addscore.php on line 35
Related
I am trying to upload a simple image file to my project using php and html but when I submit the form, either the _FILE method is empty or the _POST method is empty. My code never makes it passed the if statement checking that all fields are not empty, as I get the error: "All fields are mandatory, please fill all the fields."
Here is my CRUD.php file up until the error message:
// Include and initialize database class
require_once(ROOT_DIR . '/Classes/database.class.php');
$imageDB = new DB();
$tblName = 'image';
// The folder where the images will be stored
$uploadDir = CONTENT_PATH . '/';
// Allow file formats
$allowTypes = array('jpg', 'png', 'jpeg', 'gif');
// Set default redirect url
$redirectURL = PUBLIC_PATH . '/manageUploads.php';
$statusMsg = '';
$sessData = array();
$statusType = 'danger';
// Check if user has uploaded new image
if (isset($_POST['imgSubmit'])) {
//Set redirect url
$redirectURL = PUBLIC_PATH . '/addEdit.php';
//Get submitted data and clean it from injections
$id = $_POST['id'];
$image = $_FILES['image'];
echo $image['name'];
//Store title variable without any html or php tags and trims whitespace from beginning and end
$title = strip_tags(trim($_POST['title']));
// Validate user tags are separated by comma or space and contain only alphanumeric or space/comma input
$regex = '/^[ ,]*[a-zA-Z0-9]+(?:[ ,]+[a-zA-Z0-9]+){0,5}[ ,]*$/';
if (preg_match($regex, $_POST['tags']) == 0) {
exit('Tags are not valid!');
}
// Makes all tags lower case
$tag_input = strtolower($_POST['tags']);
// Clean up multiple commas or whitespaces
$clean_tag_input = preg_replace('/[\s,]+/', ' ', $tag_input);
// Replaces spaces with commas
$comma_tags = str_replace(' ', ',', $clean_tag_input);
// Submitted user data
$imgData = array('title' => $title,'tags' => $comma_tags);
// Store submitted data into session
$sessData['postData'] = $imgData;
$sessData['postData']['id'] = $id;
// ID query string
$idStr = !empty($id)?'?id='.$id:'';
// If the data is not empty
if ((!empty($image['name']) && !empty($title) && !empty($comma_tags)) || (!empty($id) && !empty($title) && !empty($comma_tags))) {
echo $title;
if(!empty($image)) {
$filename = basename($image['name']);
// Get file extension in lower case
$fileType = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
echo $fileType;
// Generate a unique name for the image to prevent throwing exists error
$unique_image_name = rand(10000, 990000) . '_' . time() . '.' . $fileType;
// The path of the new uploaded image
$targetFilePath = $uploadDir . $unique_image_name;
echo $targetFilePath;
if (in_array($fileType, $allowTypes)) {
// Check to make sure the image is valid
if (!empty($image['tmp_name']) && getimagesize($image['tmp_name'])) {
if (file_exists($unique_image_name)) {
$statusMsg = 'Image already exists, please choose another or rename that image.';
} else if ($image['size'] > 500000) {
$statusMsg = 'Image file size too large, please choose an image less than 500kb.';
} else {
// Everything checks out now we can move the uploaded image
if (move_uploaded_file($image['tmp_name'], $targetFilePath)){
$imgData['filename'] = $unique_image_name;
$imgData['username'] = $_SESSION['username'];
} else {
$statusMsg = 'Sorry, there was an error uploading your file.';
}
}
}
} else {
$statusMsg = 'Image file is empty or corrupt.';
}
} else {
$statusMsg = 'Sorry, only JPG, JPEG, PNG && GIF files are allowed to be uploaded.';
}
} else {
$statusMsg = 'Sorry something went wrong.';
}
if (!empty($id)) {
// Previous filename
$conditions['where'] = array('id' => $_GET['imageID'],);
$conditions['return_type'] = 'single';
$prevData = $imageDB->getRows('image', $conditions);
// Update data
$condition = array('id' => $id);
$update = $imageDB->update($tblName, $imgData, $condition);
if($update) {
//Remove old file from server
if (!empty($imgData['filename'])) {
#unlink($uploadDir . $prevData['filename']);
}
$statusType = 'success';
$statusMsg = 'Image data has been updated successfully.';
$sessData['postData'] = '';
$redirectURL = PUBLIC_PATH . '/manageUploads.php';
} else {
$statusMsg = 'Some problem occurred, please try again.';
//Set redirect url
$redirectURL .= $idStr;
}
} elseif (!empty($imgData['filename'])) {
// Insert data
$insert = $imageDB->insert($tblName, $imgData);
if ($insert) {
$statusType = 'success';
$statusMsg = 'Image has been uploaded successfully.';
$sessData['postData'] = '';
$redirectURL = PUBLIC_PATH . '/manageUploads.php';
} else {
$statusMsg = 'Some problem occurred, please try again.';
}
} else {
$statusMsg = 'All fields are mandatory, please fill all the fields.';
}
And here is my addEdit.php file with the form:
require_once(ROOT_DIR . '/Templates/header.php');
$postData = $imgData = array();
$newViewkey = uniqid();
// Get image data
if (!empty($_GET['imageID'])) {
//include and initialize DB class
require_once(ROOT_DIR . '/Classes/database.class.php');
$addEditDB = new DB();
$conditions['where'] = array('id' => $_GET['imageID'],);
$conditions['return_type'] = 'single';
$imgData = $addEditDB->getRows('image', $conditions);
}
// Pre-filled data
$imgData = !empty($postData)?$postData:$imgData;
// Define action
$actionLabel = !empty($_GET['imageID'])?'Edit':'Add';
head('Upload Image', $_SESSION['username'])
?>
<!-- Display status message -->
<?php if(!empty($statusMsg)){ ?>
<div class="message">
<?php echo $statusMsg; ?>
</div>
<?php } ?>
<div class="upload-form">
<h1>Upload Image</h1>
<form action="<?php echo IMAGE_UTIL_PATH;?>/crud.php" method="POST" enctype="multipart/form-data">
<label for="title">Title</label>
<input
type="text" name="title" id="title"
placeholder="Type image title here."
value="<?php echo !empty($imgData['title'])?$imgData['title']:''; ?>" required>
<?php if (!empty($imgData['tags'])) {
$tagsSpaces = preg_replace('/,/', ', ', trim($imgData['tags']));
} ?>
<label for="tags">Tags</label>
<textarea name="tags" id="tags" placeholder="Enter at least 1 tag describing the image separated by a space ' ' or a ','." required><?php echo !empty($imgData['tags'])?$tagsSpaces:''; ?></textarea>
<input type="file" name="image" id="image" value="<?php echo !empty($imgData['filename'])?$imgData['filename']:''; ?>" required>
<input type="hidden" name="id" value="<?php echo !empty($imgData['id'])?$imgData['id']:''; ?>">
<input type="hidden" name="modified" value="<?php echo !empty($imgData['id'])?date('Y/m/d h:m:s'):''; ?>">
<input type="hidden" name="viewkey" value="<?php echo !empty($imgData['viewkey'])?$imgData['viewkey']:$newViewkey;?>">
<?php if (!empty($imgData['filename'])) { ?>
<div>
<img src="<?php echo !empty($imgData['filename'])?$imgData['filename']:'';?>" height=75 width=auto >
</div>
<?php } ?>
<input type="submit" value="Upload" name="imgSubmit">
</form>
<div class="message">
Back to Manage Uploads
</div>
</div>
<?php require_once(ROOT_DIR . '/Templates/footer.php')?>
And finally here is my config.php file with all the path definitions:
/*
Set include path to include files outside root directory
*/
set_include_path(get_include_path() . PATH_SEPARATOR . 'C:\xampp\htdocs\Shape_Search\resources');
/*
Error reporting
*/
ini_set("display_errors", "true");
error_reporting(E_ALL|E_STRICT);
/*
Create constants for heavily used paths relative to config file location
*/
defined('ROOT_DIR')
or define('ROOT_DIR', dirname(__FILE__));
defined('SRC_DIR')
or define('SRC_DIR', dirname(dirname(__FILE__)) . '\src');
defined('PUBLIC_PATH')
or define('PUBLIC_PATH', realpath($_SERVER['HTTP_HOST']) . '/Shape_Search/public_html');
defined('CONTENT_PATH')
or define('CONTENT_PATH', realpath($_SERVER['HTTP_HOST']) . '/Shape_Search/public_html/img/content');
defined('LAYOUT_PATH')
or define('LAYOUT_PATH', realpath($_SERVER['HTTP_HOST']) . '/Shape_Search/public_html/img/layout');
defined('CSS_PATH')
or define('CSS_PATH', realpath($_SERVER['HTTP_HOST']) . '/Shape_Search/public_html/css');
defined('JS_PATH')
or define('JS_PATH', realpath($_SERVER['HTTP_HOST']) . '/Shape_Search/public_html/js');
defined('LIBRARY_PATH')
or define('LIBRARY_PATH', realpath($_SERVER['HTTP_HOST']) . '/Shape_Search/resources/Library');
defined('CLASSES_PATH')
or define('CLASSES_PATH', realpath(dirname(__FILE__)) . '/Classes');
defined('TEMPLATES_PATH')
or define('TEMPLATES_PATH', realpath(dirname(__FILE__)) . "\Templates");
defined('IMAGE_UTIL_PATH')
or define('IMAGE_UTIL_PATH', realpath($_SERVER['HTTP_HOST']) . '/Shape_Search/src/ImageUtilities');
defined('RATING_UTIL_PATH')
or define('RATING_UTIL_PATH', realpath($_SERVER['HTTP_HOST']) . '/Shape_Search/src/RatingUtilities');
defined('USER_UTIL_PATH')
or define('USER_UTIL_PATH', realpath($_SERVER['HTTP_HOST']) . '/Shape_Search/src/UserUtilities');
?>
And here is my php error log:
[10-Feb-2022 13:52:06 Europe/Berlin] PHP Warning: move_uploaded_file(/Shape_Search/public_html/img/content/973439_1644497526.jpg): Failed to open stream: No such file or directory in C:\xampp\htdocs\Shape_Search\src\ImageUtilities\crud.php on line 116
[10-Feb-2022 13:52:06 Europe/Berlin] PHP Warning: move_uploaded_file(): Unable to move "C:\xampp\tmp\phpCCA.tmp" to "/Shape_Search/public_html/img/content/973439_1644497526.jpg" in C:\xampp\htdocs\Shape_Search\src\ImageUtilities\crud.php on line 116
It was an issue of directory vs. path.
// The folder where the images will be stored
$uploadDir = CONTENT_PATH . '/';
Should be corrected to:
// The folder where the images will be stored
$uploadDir = CONTENT_DIR . '/';
Where the global variables CONTENT_PATH and CONTENT_DIR are:
defined('CONTENT_PATH')
or define('CONTENT_PATH', realpath($_SERVER['HTTP_HOST']) . '/Shape_Search/public_html/img/content');
defined('CONTENT_DIR')
or define('CONTENT_DIR', dirname(dirname(__FILE__)) . '/public_html/img/content');
For some reason the image type displays as "application/png" in IE 7 and Edge but "image/png" in Chrome and Firefox. I've tried several different images, jpegs do the same thing. Is this normal? Should I include an or statement to account for the "application/png"? Or am I doing something wrong?
if ((($screenshot_type == 'image/gif') || ($screenshot_type == 'image/jpeg') ||
($screenshot_type == 'image/pjpeg') || ($screenshot_type == 'image/png')) &&
(($screenshot_size > 0) && ($screenshot_size <= GW_MAXFILESIZE))) {
if ($_FILES['screenshot']['error'] == 0) {
// Move the file to the targe upload folder
$target = GW_UPLOADPATH . $screenshot;
if (move_uploaded_file($_FILES['screenshot']['tmp_name'], $target)) {
// Connect to the database
$dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME)
or die('Unable to connect to databse');
// Write the data to the database
$query = "INSERT INTO guitarwars VALUES (0, NOW(), '$name', '$score', '$screenshot')";
mysqli_query($dbc, $query)
or die('Unable to complete query');
// Confirm success with the user
echo '<p>Thanks for adding your new high score!</p>';
echo '<p><strong>Name:</strong> ' . $name . '<br>';
echo '<strong>Score:</strong> ' . $score . '</p>';
echo '<img src="' . GW_UPLOADPATH . $screenshot . '" alt="Score image" /></p>';
echo '<p><< Back to high scores</p>';
// Clear the score data to clear the form
$name = "";
$score = "";
$screenshot = "";
mysqli_close($dbc);
}
else {
echo '<p class="error">Sorry, there was a problem uploading your screen shot image.</p>';
}
}
}
else {
echo '<p class="error">The screen shot must be a GIF, JPEG, or PNG image file no ' .
'greater than ' . (GW_MAXFILESIZE / 1024) . ' KB in size.<br>' . $screenshot_size . '<br>' . $screenshot_type . '</p>';
}
Different browsers and operating systems supply different mime-types. You should perhaps instead just use http://php.net/getimagesize on the uploaded file, and switch on $getimagesizeresult[2] with cases for IMG_PNG, IMG_JPG, IMG_GIF and apply an appropriate mime type on your own.
I am encountering the following error message saying:
Warning: move_uploaded_file(uploads/computer-science1.jpg): failed to open stream: No such file or directory....
while trying to move a file to a directory. above code provided.
I have also enabled the uploaded file in FileZilla to be writable and executable, is there another way of solving particular problem?
Thank you.
<?php
$upload_url = "uploads/" . $_FILES["myfile"]["name"];
$filename = $_FILES["myfile"]["name"];
move_uploaded_file($_FILES["myfile"]["tmp_name"], $upload_url);
$conn = mysqli_connect("yourhost", "username", "password", "databasename");
$sql = "INSERT INTO images (image_url, image_title) VALUES ('$upload_url','$filename') ";
$imageresults = mysqli_query( $conn,$sql );
$sql = "SELECT image_url, image_title from images";
if ($imageresults = mysqli_query( $conn, $sql )) {
while ( $currentimage = mysqli_fetch_assoc($imageresults ) ) {
echo "<div><img src= '" . $currentimage['image_url'] . "'
width='200' height='200'/><br/>" .
$currentimage['image_title'] . "</div>";
}
}
} catch( Exception $e ) {
echo $e->getMessage();
}
Your PHP script must be in a directory which contains a sub-directory, uploads/, which is writeable.
It seems as if you are attempting to move the file from its temporary location to a folder (uploads/) that either doesn't exist or that the script is unable to write to.
When you've got this message :
Warning: move_uploaded_file(uploads/computer-science1.jpg): failed to
open stream: No such file or directory....
It means that the location of the file or the location of the destination directory is not good. Maybe you can check your link path of "uploads/computer-science1.jpg"
You can use a test to check it :
if(move_uploaded_file($yourFile, $yourlocation)) {
echo 'Good ! ';
} else {
exit('Error !');
}
In this php code I want to customize the image upload destination. with this php file, I have directory called uploads. I want to add all my uploaded images to this directory and store path in db. how can I do this?
<?php
// Assigning value about your server to variables for database connection
$hostname_connect= "localhost";
$database_connect= "image_upload";
$username_connect= "root";
$password_connect= "";
$connect_solning = mysql_connect($hostname_connect, $username_connect, $password_connect) or trigger_error(mysql_error(),E_USER_ERROR);
#mysql_select_db($database_connect) or die (mysql_error());
if($_POST) {
// $_FILES["file"]["error"] is HTTP File Upload variables $_FILES["file"] "file" is the name of input field you have in form tag.
if ($_FILES["file"]["error"] > 0) {
// if there is error in file uploading
echo "Return Code: " . $_FILES["file"]["error"] . "<br />";
} else {
// check if file already exit in "images" folder.
if (file_exists("images/" . $_FILES["file"]["name"])) {
echo $_FILES["file"]["name"] . " already exists. ";
} else {
//move_uploaded_file function will upload your image. if you want to resize image before uploading see this link http://b2atutorials.blogspot.com/2013/06/how-to-upload-and-resize-image-for.html
if(move_uploaded_file($_FILES["file"]["tmp_name"],"images/" . $_FILES["file"]["name"])) {
// If file has uploaded successfully, store its name in data base
$query_image = "insert into acc_images (image, status, acc_id) values ('".$_FILES['file']['name']."', 'display','')";
if(mysql_query($query_image)) {
echo "Stored in: " . "images/" . $_FILES["file"]["name"];
} else {
echo 'File name not stored in database';
}
}
}
}
}
?>
currently when I run the upload
I am getting warnings
Warning: move_uploaded_file(images/1409261668002.png): failed to open stream: No such file or directory in D:\xampp\htdocs\image-upload\index.php on line 29
Warning: move_uploaded_file(): Unable to move 'D:\xampp\tmp\php1C1F.tmp' to 'images/1409261668002.png' in D:\xampp\htdocs\image-upload\index.php on line 29
You must specify a correct path, the 'images/1409261668002.png' path doesn't exist if you dont create them and don't specify them.
if(move_uploaded_file($_FILES["file"]["tmp_name"],"images/" . $_FILES["file"]["name"]))) { .... }
You must specify the absolute path
You can use below code:
$image=basename($_FILES['file']['name']);
$image=str_replace(' ','|',$image);
$tmppath="images/".$image;
if(move_uploaded_file($_FILES['file']['tmp_name'],$tmppath))
{...}
Let me know if you have any query/concern regarding this.
Unable to create the download link. I am fetching the path saved from database and then try to make a link for it to download, but nothing happens.
Below is my code:
$query_print="SELECT vitae_pi FROM pi WHERE username='t124'";
$query_print_run=mysqli_query($conn,$query_print);
$query_print_recordset=mysqli_fetch_assoc($query_print_run);
$query_print_path=$query_print_recordset['vitae_pi'];
echo ' this is file path '.$query_print_path;
Here I am simply trying to create the download link for user t124, instead of using the current user for testing purposes?
This is hyperlink code:
<?php echo "<a href='".$query_print_path."'>".DOWNLOAD."</a>"; ?>
Any suggestions?
This my move file function:
protected function moveFile($file)
{
$filename = isset($this->newName) ? $this->newName : $file['name'];
//echo $filename;
$success = move_uploaded_file($file['tmp_name'], $this->destination . $filename);
if ($success) {
$result = $file['name'] . ' was uploaded successfully';
if (!is_null($this->newName)) {
$_SESSION['current_filename']=$this->newName;
echo $_SESSION['current_filename'];
$result .= ', and was renamed ' . $this->newName;
}
else{
$_SESSION['current_filename']=$file['name'];
echo $_SESSION['current_filename'];
}
//$result .= '.';
//echo $this->newName;
$this->messages[] = $result;
} else {
$this->messages[] = 'Could not upload ' . $file['name'];
}
}
Updating the table with file path:
$file_path_variable1= $destination1.$_SESSION['current_filename'];
echo '$file_path_variable1 : '.$file_path_variable1;
$query1="UPDATE proposal SET whitepaper_prop='$file_path_variable1' WHERE userName_prop='$currentuser'";
$result_query1=mysqli_query($conn,$query1);
....................
SOLUTION CODE IS:
Solution code is :
$query_print="SELECT vitae_pi FROM pi WHERE username='t115'";
$query_print_run=mysqli_query($conn,$query_print);
$query_print_recordset=mysqli_fetch_assoc($query_print_run);
$query_print_path=$query_print_recordset['vitae_pi'];
$dir= 'uploaded/';
$path=opendir($dir);
<?php
}while($query_pi_array=mysqli_fetch_assoc($query_pi_result));?>
<div>
<?php while($file=readdir($path)){
if($file != "." || $file !=".."){
if($file==$query_print_path){ ?>
Proposal Whitepaper
What does this display ?
<?php echo "<a href='".$query_print_path."'>".DOWNLOAD."</a>"; ?>
DOWNLOAD should be part of the PHP string, if not, it will be considered as a constant :
<?php echo "<a href='".$query_print_path."'>DOWNLOAD</a>"; ?>
Also, use double quotes for HTML attributes :
<?php echo "DOWNLOAD"; ?>
And the optimized way (to avoid useless string parsing) :
<?php echo 'DOWNLOAD'; ?>