I'm working on a website that takes a user uploaded video and puts the name, size, type, path, and tmp_name into a MySQL database. The upload.php file is below,
<?php
$is_form_submitted = (isset($_POST['submit']))?true:false;
if($is_form_submitted)
{
//defines variables
$name=$_FILES['file']['name'];
$type=$_FILES['file']['type'];
$size=$_FILES['file']['size'];
$tmp_name=$_FILES['file']['tmp_name'];
$target_path="videos/";
$allowedTypes = array("video/wmv","video/avi",
"video/mpeg","video/mpg","video/mp4");
$is_valid_type = (in_array($_FILES['file']['type'], $allowedTypes))?true:false;
if ( $is_valid_type&& ($_FILES["file"]["size"] < 20000000000))
{
if ($_FILES["file"]["error"] > 0)
{
echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
}
else
{
echo "Upload: " . $_FILES["file"]["name"] . "<br>";
echo "Type: " . $_FILES["file"]["type"] . "<br>";
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br>";
mysql_query("INSERT INTO vids(name, type, size, tmp_name, target_path)
VALUES('$name', '$type', '$size', '$tmp_name', '$target_path')");
if (file_exists("images/" . $_FILES["file"]["name"]))
{
echo $_FILES["file"]["name"] . " already exists. ";
}
else
{
move_uploaded_file($_FILES["file"]["tmp_name"],
"videos/" . $_FILES["file"]["name"]);
echo "Stored in: " . "videos/" . $_FILES["file"]["name"];
}
}
}
else
{
echo "Invalid file";
}
}
?>
And everything uploads properly but when I go and try to fetch the name and path of the video, it says that the video player has found no videos that are supported, so how would I fetch a random video from the database and put it as the source of the video player?
(the video file is playable in the player, so it is not the video's fault)
Here is the php code within the document code
<?php
$vid_url = "videos/";
$result = mysql_query("SELECT * FROM `vids` WHERE 1");
while($row = mysql_fetch_assoc($result))
{
echo
<div name="video">
<video width="100%" height="100%" controls>
<source src=".$vid_url.$row."type="video/mp4">
Error: Video Not working
</object>
</video>
</div>';
}
?>
And where I am storing the videos is a directory called videos
I figured it out in case anyone wants to reference this
<?php
//Connects to database
$host="################"; // Host name
$username="##########"; // Mysql username
$password="###########"; // Mysql password
$db_name="#######"; // Database name
$tbl_name="####"; // Table name
// Connect to server and select databse.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
//Tells variable video where to get the name from
$vid_url = "videos/";
$result = mysql_query("SELECT * FROM vids ORDER BY RAND() LIMIT 1");
$row = mysql_fetch_assoc($result);
$video = $vid_url.$row["name"];
<?
Related
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 know this is a long shot to ask but is their anyone that can show me how to upload an image to folder and image name to database? I have looked and everything I find is mysql. Mysql doesn't work for me I get many errors. Here is a code that I have but it will not work for me
<?php
$hostname_connect= "localhost";
$username_connect="torcdesi_barron7";
$password_connect= "Tazmania9292";
$database_connect="torcdesi_shirt";
// Create connection
$connect_solning = mysqli_connect($hostname_connect, $username_connect, $password_connect, $database_connect) or trigger_error(mysqli_error(),E_USER_ERROR);
mysqli_select_db($connect_solning ,$database_connect) or die (mysqli_error($connect_solning));
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"] . "/>";
}
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(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 shirt_table (image) values ('".$_FILES['file']['name']."', 'display','')";
if(mysqli_query($query_image))
{
echo "Stored in: " . "images/" . $_FILES["file"]["name"];
}
else
{
echo 'File name not stored in database';
}
}
}
}
}
?>
You have invalid query, you should use:
INSERT INTO table (field1, field2, field3) VALUES (value1, value2, value3)
You use instead:
INSERT INTO table (field1) VALUES (value1, value2, value3)
And empty quotes '' is a value too
I have a script in php that is used to upload files to a server. It was working first but i dont know why its not working again. It shows no error but the file is not still uploaded to the directory that i assigned to hold all uploaded files. Here is the part that takes care of the upload:
<?php
if ($_FILES["file"]["error"] > 0)
{
echo "Error: " . $_FILES["file"]["error"] . "<br />";
}
else
{
echo "Uploaded: " . basename($_FILES["file"]["name"]) . "<br />";
echo "Type: " . $_FILES["file"]["type"] . "<br />";
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";
//by default the size of the file is in bytes so u need to divide by 1024 in order to bring it to KB
echo "Temporarily stored in: " . $_FILES["file"]["tmp_name"] . "<br />";
$target="/file/" . basename($_FILES["file"]["name"]) . "<br />";
}
if(move_uploaded_file($_FILES["file"]["tmp_name"], $target))
{
echo "<h2>" . "The file has been stored on the server" . "<br />" . "<h2 />";
echo "New storage location is : " . '<a href="/public/files/" >' . $target . '</a>';
?>
<html>
<body>
<div align="right"><a href="/public/files/" >Uploaded files</a></div>
<br />
</body>
</html>
<?php
}
else
{
echo "<h2>" . "Error while saving the file to the server." . "<br />" . "File wont be found in the uploaded files directory" . "<br />" . "<h2 />";
echo "The error says: " . $_FILE["file"]["error"] . " What do we do now?" ;
echo"<pre>".print_r($_FILES,true)."</pre>";
?>
<?
/file/ is a directory in the root of your server's filesystem, which almost certainly doesn't exist. move_uploaded_file() works at the filesystem level and has absolutely NO awareness of your site's URI structure. You probably want something more like:
move_uploaded_file(...,. $_SERVER['DOCUMENT_ROOT'] . '/file/');
^^^^^^^^^^^^^^^^^^^^^^^^^^^---- add this
so that the file gets moved to a /file subdir of your site's root directory.
<?php
$file= $_FILES["file"]["name"];//file selected in form
echo "Upload: " . $_FILES["file"]["name"] . "<br>";
echo "Type: " . $_FILES["file"]["type"] . "<br>";
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br>";
move_uploaded_file($_FILES["file"]["tmp_name"],
"c:/EasyPHP-12.1/www/new website/upload/" . $_FILES["file"]["name"]);
echo "Stored in: " . "c:/EasyPHP-12.1/www/new website/upload/" . $_FILES["file"]["name"];
if(($_FILES['file']['size'] >0))
{echo 'imagetrue';$con=mysql_connect('localhost','abc','YES') or die ("con");;
$db=mysql_select_db("website",$con) or die ("db");
$query=mysql_query("insert into website.picture (imagew) values ('$file')") or die('query'); //storing in db}
//echo $_FILES['file']['error'] ;
$query2= mysql_query("select * from website.picture");
$res=mysql_fetch_array($query2);
foreach($res as $row){
$str = "c:/EasyPHP-12.1/www/new website/upload/ ".$row['imagew'];
echo '<img src="'.$str.'" alt="no">' ;}
?>
i am using this script to store image and then displaying it on webpage but it is not working it only displays empty thumbnails...
I'd be very suspect about using absolute paths like c:/EasyPHP-12.1/www/new website/upload/
I'f you're then accessing the page from http://127.0.0.1/new-website (which I presume you are - or something similar) then having windows system pathnames could be a problem - do browsers even read the local filesystem like that ?
Also, it makes it very un-portable for when you move it to another server.
I'd suggest $str = 'upload/'.$row['imagew']; So it's relative to the document hosted in (I presume) 127.0.0.1/new website/image-viewer.php (or whatever you called it)
Check the return value of move_uploaded_file() - if it's false then it has failed. If that's failing try using the relative path :
move_uploaded_file($_FILES["file"]["tmp_name"], "upload/" . $_FILES["file"]["name"]);
This again presumes your script is sitting in 127.0.0.1/new-website
EDIT - NOTE ::: Is your form using enctype="multipart/form-data" ? If it's not then the images never get to the server !
I have this script for uploading a image and content from a form, it works in one project but not the other. I have spent a good few hours trying to debug it, I am hoping someone could point out the issue I might be having. Where there are comments is where I have tried to debug. The first error I got was the "echo invalid file" at the beginning of the last comment. With these specific areas commented out the upload name and type that I am supposed to be grabbing from the form is not being echoed, I am thinking this is where the error is occurring, but can't quite seem to find it. Thanks.
<?php
include("../includes/connect.php");
/*
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/pjpeg"))
&& ($_FILES["file"]["size"] < 2000000))
{
*/
if ($_FILES["file"]["error"] > 0)
{
echo "Return Code: " . $_FILES["file"]["error"] . "<br />";
}
else
{
echo "Upload: " . $_FILES["file"]["name"] . "<br />";
echo "Type: " . $_FILES["file"]["type"] . "<br />";
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";
echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br />";
/* GRAB FORM DATA */
$title = $_POST['title'];
$date = $_POST['date'];
$content = $_POST['content'];
$imageName1 = $_FILES["file"]["name"];
echo $title;
echo "<br/>";
echo $date;
echo "<br/>";
echo $content;
echo "<br/>";
echo $imageName1;
$sql = "INSERT INTO blog (title,date,content,image)VALUES(
\"$title\",
\"$date\",
\"$content\",
\"$imageName1\"
)";
$results = mysql_query($sql)or die(mysql_error());
echo "<br/>";
if (file_exists("../images/blog/" . $_FILES["file"]["name"]))
{
echo $_FILES["file"]["name"] . " already exists. ";
}
else
{
move_uploaded_file($_FILES["file"]["tmp_name"],
"../images/blog/" . $_FILES["file"]["name"]);
echo "Stored in: " . "../images/blog/" . $_FILES["file"]["name"];
}
}
/*
}
else
{
echo "Invalid file" . "<br/>";
echo "Type: " . $_FILES["file"]["type"] . "<br />";
}
*/
//lets create a thumbnail of this uploaded image.
/*
$fileName = $_FILES["file"]["name"];
createThumb($fileName,310,"../images/blog/thumbs/");
function createThumb($thisFileName, $thisThumbWidth, $thisThumbDest){
$thisOriginalFilePath = "../images/blog/". $thisFileName;
list($width, $height) = getimagesize($thisOriginalFilePath);
$imgRatio =$width/$height;
$thisThumbHeight = $thisThumbWidth/$imgRatio;
$thumb = imagecreatetruecolor($thisThumbWidth,$thisThumbHeight);
$source = imagecreatefromjpeg($thisOriginalFilePath);
imagecopyresampled($thumb, $source, 0, 0, 0, 0, $thisThumbWidth,$thisThumbHeight, $width, $height);
$newFileName = $thisThumbDest.$thisFileName;
imagejpeg($thumb,$newFileName, 80);
echo "<p><img src=\"$newFileName\" /></p>";
//header("location: http://www.google.ca");
}
*/
?>
Perhaps you forgot to add enctype="multipart/form-data" method="post" to your HTML form, or have no <input type="file" name="file" id="file" value=""/> in your HTML.
Here's some problems with your script:
The 'error' value in the $_FILES array is not just a boolean, it will tell you if an upload succeeded, or why it failed. The error codes are defined here.
The 'type' value is supplied by the remote client. It's NOT determined by the web server or PHP. As such, doing mime-type verification based on that value is a major hole: it's trivial to forge the supplied type value. Best to use a server-side method, like fileinfo, to determine the actual mime type.
You blindly insert the form data into your insertion query, which leaves you wide open to SQL injection attacks. At least pass the data through mysql_real_escape_string() before building your query, or better yet, use PDO and parameterized queries
You're storing the files with the original client-provided name. You at least check if the filename's already in use, preventing upload collisions/overwriting, but there's also the case where the client's operating system/file system allows characters in filenames that the server's OS/FS do not, which could lead to subtle file "vanished" bugs, or overwriting entirely different files because the invalid characters were filtered out or translated to something else. Since you're using a database to store information about the upload, you can store the original filename in that table, and use the table's primary key (an auto_increment int, right?) as the filename.
Not really a problem, but in terms of efficiency, there's no need to use getimagesize() in your thumb creation function. GD has imagesx() and imagesy() which get the pixel size from a GD image handle. getimagesize() is independent of GD, so you're opening and parsing the source image twice. Again, it's not really a problem, but on a busy site, opening the image only once could be a decent cpu time and memory usage savings.
The error was in the html form file, I had added a name="something" beside the method="post" and enctype="multi/form-data" obviously this was not liked. Thanks RC for pointing me in the right direction. I am not quite sure why I did this.
$_FILES["file"]["error"] is not just a flag.
It has error codes.
Explained in the manual