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.
Related
I'm encountering an issue I've never come across before. I have some images uploaded as JPG or PNG with a duplicate of the image in WebP format, eg in this file naming convension:
https://example.com/uploads/memory-day.png >
https://example.com/uploads/memory-day.png.webp
If I delete a file through PHP using the unlink() function like normal, it works fine for everything else until I delete the PNG duplicate image. When I do that, the WebP file is also deleted and I can't see how it's happening -- is it a weird issue in the unlink() function with a file having a double extension? I can't seem to replicate it unless it's there's a WebP file involved.
For clarity, here's the PHP code that deletes the files (and yeah, I know it needs to be a prepare statement, I haven't updated it yet):
if(isset($_POST['delete'])) {
$countG = 0;
$err = 0;
foreach($_POST['delFile'] as $actionID) {
$action_id = $conn->real_escape_string($actionID);
$query = $conn->query("SELECT `filename`, `dir` FROM `fileuploads` WHERE `id` = '$action_id'");
$delF = $query->fetch_assoc();
$filenameDel = StripSlashes($delF['filename']);
$filenameDir = StripSlashes($delF['dir']);
if(file_exists($_SERVER['DOCUMENT_ROOT'] . $filenameDir . "/" . $filenameDel)){
if(unlink($_SERVER['DOCUMENT_ROOT'] . $filenameDir . "/" . $filenameDel)) {
if(file_exists($_SERVER['DOCUMENT_ROOT'] . $filenameDir . "/auto_thumbs/" . $filenameDel)) {
unlink($_SERVER['DOCUMENT_ROOT'] . $filenameDir . "/auto_thumbs/" . $filenameDel);
}
$delquery = $conn->query("DELETE FROM `fileuploads` WHERE `id` = '$action_id'");
$countG++;
} else {
$err++;
}
} else {
$err++;
if(!file_exists($_SERVER['DOCUMENT_ROOT'] . $filenameDir . "/" . $filenameDel)) {
//Remove from db if file is not there physically
$delquery = $conn->query("DELETE FROM `fileuploads` WHERE `id` = '$action_id'");
}
}
}
if($countG > 0) {
$green = 1;
$message1 = "$countG File(s) Deleted!";
}
if($err > 0) {
$red = 1;
$message2 = "Error deleting $err files!";
error_log(print_r(error_get_last(), TRUE));
}
}
On desktop, the upload works correctly, but when I try to upload from a mobile device, it says that the extension is outside the array, and print returns octet-stream, any thoughts? I can't see what could be wrong. I have tried many audio extensions, checked MIME and tested with a few smartphones, no success.
if (isset($_POST['submit_atrack'])) {
$fileinfo=PATHINFO($_FILES["audio"]["name"]);
$newFilename=$fileinfo['filename'] . uniqid($usr_idLogged) . "." . $fileinfo['extension'];
move_uploaded_file($_FILES["audio"]["tmp_name"],"atracks/" . $newFilename);
$location = 'atracks/' . $newFilename;
$formatos = array('audio/mpeg', 'audio/ogg', 'audio/mp3', 'audio/*', 'audio/wav');
$tamanho_max = 500000000; //500 mb
if (empty($_FILES['audio']['name']))
{
$upload_empty = urlencode("empty");
header("Location:playlist?newtrack=".$upload_empty . "&playlist=" . $selectedPlaylist);
exit;
}
else if (!in_array($_FILES['audio']['type'], $formatos))
{
$upload_incorrectformat = urlencode("incorrectext");
header("Location:playlist?newtrack=".$upload_incorrectformat . "&playlist=" . $selectedPlaylist);
exit;
}
else if (in_array($_FILES['audio']['type'], $formatos))
{
if($_FILES['audio']['size'] >= $tamanho_max)
{
$upload_maxsize = urlencode("maxsizereached");
header("Location:playlist?newtrack=".$upload_maxsize . "&playlist=" . $selectedPlaylist);
exit;
}
else
{
$atitle = mysqli_real_escape_string($connection, $_POST['atitle']);
$atag = mysqli_real_escape_string($connection, $_POST['atag']);
$atagcolor = mysqli_real_escape_string($connection, $_POST['atagcolor']);
mysqli_query($connection,"INSERT INTO tbl_users_atrack (atrack_title, atrack_path, atrack_tag, atrack_tagColor, atrack_playlistId) VALUES ('$atitle', '$location', '$atag', '$atagcolor', '$selectedPlaylist')");
$upload_success = urlencode("success");
header("Location:playlist?newtrack=" . $upload_success . "&playlist=" . $selectedPlaylist);
exit;
}
}
}
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
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"];
<?
I have a PHP form, i'm trying to send an image from it as an attachment. I already fixed few things in my code.
I'm not sure if it will send the image (because I had some problems with it)
The problem is that nothing is even shown in the page (when I the script below is ran) when I open it on the server as index.php not even the button
Here is the code:
<?php
include_once("functions.php");
// Process
$action = isset($_POST["action"]) ? $_POST["action"] : "";
if (empty($action))
{
// Send back the contact form HTML
$output = "<form action='#' style='display:none'>
<input type='file' id='image' name='image' maxlength=50>";
}
require("class.phpmailer.php");
$Email_to = "someone#gmail.com"; // the one that recieves the email
$email_from = "someone#someone.net";
$dir = "uploads/$filename";
chmod("uploads",0777);
function uploadImage($image)
{
if ((($_FILES["image"]["type"] == "image/gif")
|| ($_FILES["image"]["type"] == "image/jpeg")
|| ($_FILES["image"]["type"] == "image/pjpeg")
|| ($_FILES["image"]["type"] == "image/jpg")
|| ($_FILES["image"]["type"] == "image/png"))
&& ($_FILES["image"]["size"] < 2097152)
&& (strlen($_FILES["image"]["name"]) < 51))
{
if ($_FILES["image"]["error"] > 0)
{
echo "Return Code: " . $_FILES["image"]["error"];
}
else
{
echo "Upload: " . $_FILES["image"]["name"] . "<br />";
echo "Type: " . $_FILES["image"]["type"] . "<br />";
echo "Size: " . ($_FILES["image"]["size"] / 1024) . " Kb<br />";
echo "Temp file: " . $_FILES["image"]["tmp_name"] . "<br />";
if (file_exists("images/" . $_FILES["image"]["name"]))
{
echo $_FILES["image"]["name"] . " already exists. ";
}
else
{
move_uploaded_file($_FILES["image"]["tmp_name"],
"images/" . $_FILES["image"]["name"]);
}
}
}
else
{
echo "Invalid file";
}
$filename = $_FILES["image"]["type"];
$dir = "uploads/$filename";
chmod("uploads",0777);
$success = copy($_FILES[images][tmp_name], $dir);
if ($success)
{
echo " Files Uploaded Successfully<BR>";
SendIt();
}
}//end of upload func'
function SendIt() {
//
global $attachments,$Email_to,$Email_msg,$email_subject,$email_from;
$mail = new PHPMailer();
$mail->IsSMTP();// send via SMTP
$mail->Host = "localhost"; // SMTP servers
$mail->SMTPAuth = false; // turn on/off SMTP authentication
$mail->From = $email_from;
$mail->AddAddress($Email_to);
$mail->AddReplyTo($email_from);
$mail->WordWrap = 50;// set word wrap
//now Attach all files submitted
$mail->AddAttachment("uploads"."/".$_FILES["image"]["type"]);
$mail->IsHTML(false);// send as HTML
}
?>
Thank you in advance!
For problem 1:
Try to send a mail with that class without any variables put into it. So just make some procedural code sending a mail to your own address and see if it arrives.
For problem 2:
You are putting some text into $output but you are never outputting $output.