PHP - Uploading Media File Script Giving Me Headache... Help!!!
Hi phpfreaks, please I have being working on a media site for few months now and I have designed everything that needs to be designed but A♏ having problems with my uploading code its not storing the file size in the database, I have tried and tried and all what have being doing seem to be taking me away from the right way with my little understanding of php. Here is the code that is giving me headache
, <?php //include("includes/sess.php"); ?> <?php $upload="active"; include("includes/mheader.php"); ?> <?php if(isset($_POST['Upload'])) { ////////////////////////////////// //$id=$_POST['id']; $picture=$_POST['picture']; $artiste=$_POST['artiste']; $title=$_POST['title']; $genre=$_POST['genre']; $uname=$_POST['uname']; if($title=="") { $message="unknown Title"; header("location:upload.php?message=$message"); exit(); } if($genre=="") { $message="unknown Type"; header("location:upload.php?message=$message"); exit(); } /*if($nfile=="") { $message="file not found"; header("location:upload.php?message=$message"); exit(); } */ if($uname=="") { $message="error you"; header("location:upload.php?message=$message"); exit(); } if($artiste=="") { $message="Artiste ?"; header("location:upload.php?message=$message"); exit(); } header("location:upload.php?message=$message"); ////////////////////////////////// $size=$_FILES["picture"]["size"]; $file_size1 = $size/1024 ; $file_size = $file_size1/1000 ; function UploadOne($fname) { $uploaddir = 'music/NaijaMp3_'; if (is_uploaded_file($fname['tmp_name'])) { $filname = basename($fname['name']); $uploadfile = $uploaddir . basename($fname['name']); if (move_uploaded_file ($fname['tmp_name'], $uploadfile)) $res = "File " . $filname . " was successfully uploaded and stored.<br>"; else $res = "Could not move ".$fname['tmp_name']." to ".$uploadfile."<br>"; } else $res = "File ".$fname['name']." failed to upload."; return ($res); } ?> <?php if ($_FILES['picture']['name'] != "") { $res = UploadOne($_FILES['picture']); $filname = $_FILES['picture']['name']; $filname=addslashes($filname); ///////////////////////////////////////////////////////////// $alt_file_name = "NaijaMp3_" .$filname ; $date_created=date("Y-m-d h:i:A"); include("includes/db_connect.php"); $sql="INSERT INTO upmp3(uname,file_name,alt_file_name,file_size,artiste,title,genre,date_created) VALUES('$uname','$filname','$alt_file_name','$file_size','$artiste','$title','$genre','$date_created')"; mysql_query($sql) or die (mysql_error()); $message="Upload Sucessful"; ///////////////////////////////////////////////////////////// echo ($res); } } ?> <div class="main_but"> </div> </div> <!-- Navigation begins here --> <!-- Header section ends here --></div> <div class="login"> </div> <div id="feature"> <blockquote/> <div align="center"><em><strong>UPLOAD FILE </strong></em></div> <form action="upload.php" method="post" enctype="multipart/form-data" name="form1" id="form1"> <p> <br /> </p> <p>{Note: All * fields are Mandatory} </p> <p> <label> <input name="picture" type="file" id="picture" /> </label> </p> <p>File Type <label> <select name="type" id="type"> <option value="mp3">mp3</option> </select> </label> </p> <p>Artiste*<span class="style1"><sub>(e.g Alashine)</sub></span> <label> <input name="artiste" type="text" id="artiste" /> </label> Title <label> <input name="title" type="text" id="title" /><span class="style1"> </label> <p>Genre <label><input name="genre" type="text" id="genre" />(Genre e.g Hiphop, RnB, Reggae . . .)</span></label> <input type='hidden' name='id' value='<?php echo"$id" ?>' id='id'/> <input type='hidden' name='uname' value='<?php echo"$uname" ?>' id='uname'/> <label></label> </p> </p> <p> <label> <input name="Upload" type="submit" id="Upload" value="Upload Mp3" /> </label> </p> </form> </div> </div> <?php include("includes/footer.php"); ?> </div> Thanks for your help in anticipation Similar TutorialsHey all So have been working on a file upload script, it was uploading the file but also adding the path name instead of NULL to mysql when no image was to upload, that is now fixed however now it won't upload the actual image to the directory. I tried undoing the mysql changes but it still won't upload the image to the directory. Am testing on my own computer using xampp so no file permission issues, plus it was working before. Any help much appreciated. Thanks <?php $product_code = mysqli_real_escape_string($conn, $_POST['product_code']); $product_name = mysqli_real_escape_string($conn, $_POST['product_name']); $category = mysqli_real_escape_string($conn, $_POST['category']); $filter = mysqli_real_escape_string($conn, $_POST['filter']); $description = mysqli_real_escape_string($conn, $_POST['description']); $specification = mysqli_real_escape_string($conn, $_POST['specification']); $price = mysqli_real_escape_string($conn, $_POST['price']); $target_dir = "../images/products/"; if (!isset ($_FILES["img1"]["name"])) { $target_file1 = NULL; } else { if (!empty($_FILES["img1"]["name"])) { $target_file1 = $target_dir . basename($_FILES["img1"]["name"]); } else { $target_file1 = NULL; } } if (!isset ($_FILES["img2"]["name"])) { $target_file2 = NULL; } else { if (!empty($_FILES["img2"]["name"])) { $target_file2 = $target_dir . basename($_FILES["img2"]["name"]); } else { $target_file2 = NULL; } } if (!isset ($_FILES["img3"]["name"])) { $target_file3 = NULL; } else { if (!empty($_FILES["img3"]["name"])) { $target_file3 = $target_dir . basename($_FILES["img3"]["name"]); } else { $target_file3 = NULL; } } if (!isset ($_FILES["img4"]["name"])) { $target_file4 = NULL; } else { if (!empty($_FILES["img4"]["name"])) { $target_file4 = $target_dir . basename($_FILES["img4"]["name"]); } else { $target_file4 = NULL; } } $uploadOk = 1; $imageFileType1 = strtolower(pathinfo($target_file1,PATHINFO_EXTENSION)); $imageFileType2= strtolower(pathinfo($target_file2,PATHINFO_EXTENSION)); $imageFileType3 = strtolower(pathinfo($target_file3,PATHINFO_EXTENSION)); $imageFileType4 = strtolower(pathinfo($target_file4,PATHINFO_EXTENSION)); // Check if image file is a actual image or fake image if(isset($_POST["submit"])) { $check1 = getimagesize($_FILES["img1"]["tmp_name"]); $check2 = getimagesize($_FILES["img2"]["tmp_name"]); $check3 = getimagesize($_FILES["img3"]["tmp_name"]); $check4 = getimagesize($_FILES["img4"]["tmp_name"]); if($check1 !== false) { echo "File is an image - " . $check1["mime"] . "."; $uploadOk = 1; } else { echo "File is not an image."; $uploadOk = 0; } if (file_exists($target_file1)) { echo "Sorry, image one already exists."; $uploadOk = 0; } if($imageFileType1 != "jpg" && $imageFileType1 != "png" && $imageFileType1 != "jpeg" && $imageFileType1 != "gif" ) { echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed for img1."; $uploadOk = 0; } if ($uploadOk == 0) { echo "Sorry, your file was not uploaded."; // if everything is ok, try to upload file } else { if (move_uploaded_file($_FILES["img1"]["tmp_name"], $target_file1)) { echo "The file ". htmlspecialchars( basename( $_FILES["img1"]["name"])). " has been uploaded."; } else { echo "Sorry, there was an error uploading image one."; } } echo '<br />'; if($check2 !== false) { echo "File is an image - " . $check2["mime"] . "."; $uploadOk = 1; } else { echo "File is not an image."; $uploadOk = 0; } if (file_exists($target_file2)) { echo "Sorry, image two already exists."; $uploadOk = 0; } if($imageFileType2 != "jpg" && $imageFileType2 != "png" && $imageFileType2 != "jpeg" && $imageFileType2 != "gif" ) { echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed for img2."; $uploadOk = 0; } if (isset ($target_file2)) { if ($uploadOk == 0) { echo "Sorry, your file was not uploaded."; // if everything is ok, try to upload file } else { if (move_uploaded_file($_FILES["img2"]["tmp_name"], $target_file2)) { echo "The file ". htmlspecialchars( basename( $_FILES["img1"]["name"])). " has been uploaded."; } else { echo "Sorry, there was an error uploading image two."; } } } echo '<br />'; if($check3 !== false) { echo "File is an image - " . $check3["mime"] . "."; $uploadOk = 1; } else { echo "File is not an image."; $uploadOk = 0; } if (file_exists($target_file3)) { echo "Sorry, image three already exists."; $uploadOk = 0; } if($imageFileType3 != "jpg" && $imageFileType3 != "png" && $imageFileType3 != "jpeg" && $imageFileType3 != "gif" ) { echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed for img3."; $uploadOk = 0; } if (isset ($target_file3)) { if ($uploadOk == 0) { echo "Sorry, your file was not uploaded."; // if everything is ok, try to upload file } else { if (move_uploaded_file($_FILES["img3"]["tmp_name"], $target_file3)) { echo "The file ". htmlspecialchars( basename( $_FILES["img3"]["name"])). " has been uploaded."; } else { echo "Sorry, there was an error uploading image three."; } } } echo '<br />'; if($check4 !== false) { echo "File is an image - " . $check4["mime"] . "."; $uploadOk = 1; } else { echo "File is not an image."; $uploadOk = 0; } if (file_exists($target_file4)) { echo "Sorry, image four already exists."; $uploadOk = 0; } if($imageFileType4 != "jpg" && $imageFileType4 != "png" && $imageFileType4 != "jpeg" && $imageFileType4 != "gif" ) { echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed for img4."; $uploadOk = 0; } if (isset ($target_file4)) { if ($uploadOk == 0) { echo "Sorry, your file was not uploaded."; // if everything is ok, try to upload file } else { if (move_uploaded_file($_FILES["img4"]["tmp_name"], $target_file4)) { echo "The file ". htmlspecialchars( basename( $_FILES["img4"]["name"])). " has been uploaded."; } else { echo "Sorry, there was an error uploading image four."; } } } } echo '<br />'; $image1 = basename($target_file1); $image2 = basename($target_file2); $image3 = basename($target_file3); $image4 = basename($target_file4); // Create connection $conn = mysqli_connect($servername, $username, $password, $dbname); // Check connection if (!$conn) { die("Connection failed: " . mysqli_connect_error()); } $sql = "INSERT INTO products (product_code, product_name, category, filter, description, specification, img1, img2, img3, img4, price) VALUES('$product_code', '$product_name', '$category', '$filter', '$description', '$specification', '$image1', '$image2', '$image3', '$image4', '$price')"; if (mysqli_query($conn, $sql)) { echo "Product Added successfully, Now on to the Sizes"; } else { echo "Error: " . $sql . "<br>" . mysqli_error($conn); } ?>
Anyone know of a script that will allow you to upload a file and converts it to a specified file format? Folder layout: script/ script/videos/mp4/ } script/videos/ogg/ } folders for converted files from uploaded files script/videos/webm/ } script/videos/swf/ } Video player: Code: [Select] <video width="320" height="240" controls="controls"> <source src="script/videos/mp4/<? echo $movie; ?>.mp4" type="video/mp4" /> <source src="script/videos/ogg/ <? echo $movie; ?> .ogg" type="video/ogg" /> <source src="script/videos/webm/ <? echo $movie; ?> .webm" type="video/webm" /> <object data="script/videos/mp4/ <? echo $movie; ?> .mp4" width="320" height="240"> <embed src="script/videos/swf/ <? echo $movie; ?> .swf" width="320" height="240"> Your browser does not support video </embed> </object> </video> I have searched and searched the web for an answer and cannot find one pleas help? Hi Still very new to PHP but getting some good use out of it with includes. I'm currently using this code to check the file name of the page and then give the corresponding anchor tag a class of active in order to style my main menu. This is all working for most of my pages but my problem is that I now have multiple files called index.php one in the root of my site and some are in folders. Is there any way around this issue? Can PHP check to see if its the index file in the root of the site or is there a better way. I suppose I could create a second variable in the index file in my root ie my home page and then check to say if the current page is called index and has the variable of home but how would I write this? My code Code: [Select] $currentPage = basename($_SERVER['SCRIPT_NAME'], '.php'); <li><a href="/" <?php if ($currentPage == 'index') {echo 'class="active"';} ?>>Home</a></li> Hi, really need some extra brains to help me with this one! I have a form with only 1 text box (input type=text) in this textbox I enter a local path on my computer to a specific folder. in this folder I have few files, each has a set name that I know in advance. what I want to do is to be able to upload all those files in my local folder to the server, without making the user click browes and pick them 1 by 1. I searched and searched but I see it's not as simple as I thought cuz I can't just set the value of the input file.. since my page has a form eitherway I thought of maybe doing something sneaky and hiding the input files and some how passing them the path of each file (the folder path will be taken from the not hidden textbox) and the file name is known to me so I can add those 2 somehow.. I can't find a way to do that, so I wonder if any of you have an idea? maybe it's possible to set the file path after the form is submited? basicly I think it's possible to give the name of the file, but I also need the temp name of the file ($_FILES['docfile1']['tmp_name']), and this I don't know how to set.. this is my code for uploading a file with <input type=file> Code: [Select] if ($_FILES['docfile1']['name']!='') { $target = 'import/'; $target = $target . basename($_FILES['docfile1']['name']); if ($target =="import/myfile.xlsx"){ if (file_exists($target)) unlink($target); if (move_uploaded_file($_FILES['docfile1']['tmp_name'], $target)) { echo 'success'; }else{ echo 'fail'; } }else{ echo 'fail'; } }desperately need help! I am working on making an album however I am not sure where I am going wrong with my codes. I have an upload and thumbs folder in the albums folder but I keep getting this message.... Warning: mkdir() [function.mkdir]: File exists in /home/ebermy5/public_html/albums/album_func.php on line 44 Warning: mkdir() [function.mkdir]: File exists in /home/ebermy5/public_html/albums/album_func.php on line 45 Warning: Cannot modify header information - headers already sent by (output started at /home/ebermy5/public_html/albums/create_album.php:9) in /home/ebermy5/public_html/albums/create_album.php on line 29 Codes: for line 44 and 45 function create_album($album_name, $album_description){ $album_name = mysql_real_escape_string(htmlentities($album_name)); $album_description = mysql_real_escape_string(htmlentities($album_description)); mysql_query("INSERT INTO `albums` VALUES ('', '".$_SESSION['SESS_ID']."', UNIX_TIMESTAMP(), `$album_name`,`$album_description`)"); mkdir('uploads/'.mysql_insert_id(), 0744); mkdir('uploads/thumbs/'.mysql_insert_id(), 0744); } Code: for line 29 if(isset($_POST['album_name'], $_POST['album_description'])){ $album_name = $_POST['album_name']; $album_description = $_POST['album_description']; $errors = ""; if(empty($album_name) || empty($album_description)){ $errors = 'Album name and description required'; }else{ if(strlen($album_name) > 55 || strlen($album_description) > 255){ $errors = 'One or more fields contains too many characters'; } } if(!empty($errors)){ foreach($errors as $error){ echo $errors, '<br />'; } } else { create_album ($album_name, $album_description); header('Location: albums.php'); exit(); } } i am using the fancy upload script for post attachments on my forum. the problem is that when a user starts a new post and adds an attachment the attachment is uploaded before the post is complete. so how would i associate the attachment with the post that they are going to post when i have no post id to go off? i had tried not uploading the files straight away and instead populate an input box with the filenames but i cant figure it out with this script. Anyone got any other options or ideas? ok i added this script in the bottom of my other uploader script.
what i wanted to do was, to upload an imagefile to an folder called uploads
and in the same time add the name of the file to an database called uploads,
together with the next id of another database
i dont get any error msg, the page is just blank.
<?php include 'sqlconnect.php'; $result = mysql_query(" SHOW TABLE STATUS LIKE 'aktiviteter' "); $data = mysql_fetch_assoc($result); $next_increment = $data['Auto_increment']; $sql = sprintf( "INSERT INTO aktiviteter (`title`, `firma`, `beskrivelse`, `information`, `pris`, `varighed`, `antal`, `adresse`, `by`, `postnummer`, `telefon`, `email`, `hjemmeside`) VALUES ('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s')", mysqli_real_escape_string($con, $_POST['title']), mysqli_real_escape_string($con, $_POST['firma']), mysqli_real_escape_string($con, $_POST['beskrivelse']), mysqli_real_escape_string($con, $_POST['information']), mysqli_real_escape_string($con, $_POST['pris']), mysqli_real_escape_string($con, $_POST['varighed']), mysqli_real_escape_string($con, $_POST['antal']), mysqli_real_escape_string($con, $_POST['adresse']), mysqli_real_escape_string($con, $_POST['by']), mysqli_real_escape_string($con, $_POST['postnummer']), mysqli_real_escape_string($con, $_POST['telefon']), mysqli_real_escape_string($con, $_POST['email']), mysqli_real_escape_string($con, $_POST['hjemmeside']) ); if (!mysqli_query($con, $sql)) { die('Error: ' . mysqli_error($con)); } echo "Aktiviteten er uploaded"; if(isset($_POST['upload'])) { $allowed_filetypes = array('.jpg','.jpeg','.png','.gif'); $max_filesize = 10485760; $upload_path = 'uploads/'; $targetId = $next_increment $filename = $_FILES['billede']['name']; $ext = substr($filename, strpos($filename,'.'), strlen($filename)-1); if(!in_array($ext,$allowed_filetypes)) die('The file you attempted to upload is not allowed.'); if(filesize($_FILES['billede']['tmp_name']) > $max_filesize) die('The file you attempted to upload is too large.'); if(!is_writable($upload_path)) die('You cannot upload to the specified directory, please CHMOD it to 777.'); if(move_uploaded_file($_FILES['billede']['tmp_name'],$upload_path . $filename)) { $query = "INSERT INTO uploads (name, target) VALUES ($filename, $targetId)"; mysql_query($query); echo 'Your file upload was successful!'; } else { echo 'There was an error during the file upload. Please try again.'; } } mysqli_close($con); ok im stuck again and need help. I have gotten rid of the attachment system(too many issues) on ASF and decided to replace it with my own. The problem is that the original new post form is sent to php via jQuery. Obv i cannot do this with files so the attachment section needs to be a seperate form. Now i have no issues with sending files to the folder and sending their name to the database but i need to send multiple. so far when the user selects a file it will add the name of it to a hidden input element and each one that is added to that element is seperated with | . then in the php i would use explode on this element to get an array of the file names. but this only helps when sending to the database and not when moving files. I also dont want a page refresh when uploading files. No other file upload systems out there will work because they upload the file as soon as you press submit, but then how do i add the post id to the attachments row in the database? Hi, I have a system that uses PHP to create a Word Doc as information is extracted from a table using this code: Code: [Select] header("Content-type: applicaton/save"); header("Content-Disposition: attachment; filename="FILE NAME".doc"); header("Pragma: no-cache"); header("Expires: 0"); This part of the system I'm trying to implement is working fine. However, what I would ideally like for it to do (and at this point I understand that it sounds a bit pointless) is to save that downloaded file onto a specified folder location on the server directory i.e. to the uploads folder. This will enable all users of the system to then download / view these files as required. I'm not sure whether this is possible or not but and help would be greatly appreciated. Thanks in advance, Ben Me and a friend are working on a nice secure Image Upload Script. The Upload Class <?php class imageUploader { public $image; // [name], [type], [tmp_name], [error], [size] public $maxFileSize; public $imageExtension; public function __construct($image, $max_file_size) { $this->image = $image; $this->maxFileSize = $max_file_size; } public function isValidImage() { $validExts = array("gif" => "image/gif", "jpeg" => "image/jpeg", "png" => "image/png"); if(in_array(strtolower($this->image["type"]), $validExts) == true) { foreach($validExts as $name => $value) { if(strtolower($this->image["type"]) == $value) { $this->imageExtension = $name; break; } } return true; } else { return false; } } public function isValidSize() { if($this->image["size"] > $this->maxFileSize) { return false; } else { return true; } } public function uploadImage() { if($this->image["error"] > 0) { $errors[] = "An error has occurred"; } elseif($this->isValidImage() == false) { $errors[] = "Invalid file type. Only use JPG, GIF or PNG"; } elseif($this->isValidSize() == false) { $errors[] = "Max file size exceeded."; } if(count((array) $errors) == 0) { move_uploaded_file($this->image["tmp_name"], "Images/" . $this->generateName(rand(10, 15)) . time() . "." . $this->imageExtension); } else { echo implode("<br />", $errors); } } public function createThumbnails() { } public function resizeImage($size_y, $size_x) { } public function generateName($length) { $randstr = ""; for ($i = 0; $i < $length; $i++) { $randnum = mt_rand(0, 61); if ($randnum < 10) { $randstr .= chr($randnum + 48); } elseif ($randnum < 36) { $randstr .= chr($randnum + 55); } else { $randstr .= chr($randnum + 61); } } return $randstr; } } ?> The Everyday HTML Code: [Select] <form action="" method="post" enctype="multipart/form-data"> <table> <tr> <td>Image</td> <td><input type="file" name="file" id="file" /></td> <td><input type="submit" name="submit" value="Submit" /></td> </tr> </table> </form> My friend did most of the work, but had to go to sleep. My problem is I have a deadline to finish this in under 3 hours for use on my website. What I need it to do is create thumbnails in a /Thumbnail/ sub-folder, with thumbnails being cropped to 100px x 100px. If the full image is larger than 600px x 600px they would have to be resized down to nothing more than 600px for the longest side. I wouldn't mind if they were 300px x 600px, just nothing larger than 600px. I'm willing to pay for this to be completed, I only have roughly $50 though. I know this isn't a freelance area, but it kind of suits this area too with a freelance option. After the upload script is done, I have to work on a php system to get the images and display them, so that I'm not directly linking images. So anyone got some spare time to help out? ok i have a image uploading script here, it works fine but theres one thing im unhappy with when i first downloaded it it had 1 working one, and the rest examples which you basically have to put together yourself with the sample code (doesen't work without adding missing coding), i have done all that then i took the time to add a random string prefix, im new at php so it took me awhile to work out which strings would work in the right area. now this is what i need help with, when it uploads it has two options, download and remove, these both work fine, but on the file uploader that does work it has "file uploaded to "http://site.com/image.png" the example of course did not work (had loading bar working, and etc but didn't upload or have the feature i just mentioned) and the coder of the script used javascript and inner html for the file uploaded.... etc, because it uploads without refreshing, only thing is i cant seem to get it to work with the new random string i put in, i tried to recreate one with the same type of thing they used for the filename but it didn't work well here is the code, hope you can help. image upload handler Code: [Select] <?php require_once "phpuploader/include_phpuploader.php" ?> <?php $uploader=new PhpUploader(); if(@$_GET["download"]) { $fileguid=$_GET["download"]; $mvcfile=$uploader->GetUploadedFile($fileguid); header("Content-Type: application/oct-stream"); header("Content-Disposition: attachment; filename=\"" . $mvcfile->FileName . "\""); readfile($mvcfile->FilePath); } if(@$_POST["delete"]) { $fileguid=$_POST["delete"]; $mvcfile=$uploader->GetUploadedFile($fileguid); unlink($mvcfile->FilePath); echo("OK"); } if(@$_POST["guidlist"]) { $guidarray=explode("/",$_POST["guidlist"]); //OUTPUT JSON echo("["); $count=0; foreach($guidarray as $fileguid) { $mvcfile=$uploader->GetUploadedFile($fileguid); if(!$mvcfile) continue; //process the file here , move to some where //rename(...) if($count>0) echo(","); echo("{"); echo("FileGuid:'");echo($mvcfile->FileGuid);echo("'"); echo(","); echo("FileSize:'");echo($mvcfile->FileSize);echo("'"); echo(","); echo("FileName:'");echo($mvcfile->FileName);echo("'"); echo("}"); $count++; } echo("]"); } //USER CODE: $rand = substr(md5(microtime()),rand(0,26),10); $targetfilepath= 'savefiles/' . $rand->rand . $mvcfile->FileName; if( is_file ($targetfilepath) ) unlink($targetfilepath); $mvcfile->MoveTo( $targetfilepath ); exit(200); ?> image upload(with form to choose file) Code: [Select] <?php require_once "phpuploader/include_phpuploader.php" ?> <?php session_start(); ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title> Ajax - Build attachments table </title> <link href="demo.css" rel="stylesheet" type="text/css" /> <script type="text/javascript"> var handlerurl='ajax-attachments-handler.php' function CreateAjaxRequest() { var xh; if (window.XMLHttpRequest) xh = new window.XMLHttpRequest(); else xh = new ActiveXObject("Microsoft.XMLHTTP"); xh.open("POST", handlerurl, false, null, null); xh.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8"); return xh; } </script> <script type="text/javascript"> var fileArray=[]; function ShowAttachmentsTable() { var table = document.getElementById("filelist"); while(table.firstChild)table.removeChild(table.firstChild); AppendToFileList(fileArray); } function AppendToFileList(list) { var table = document.getElementById("filelist"); for (var i = 0; i < list.length; i++) { var item = list[i]; var row=table.insertRow(-1); row.setAttribute("fileguid",item.FileGuid); row.setAttribute("filename",item.FileName); var td1=row.insertCell(-1); td1.innerHTML="<img src='phpuploader/resources/circle.png' border='0'/>"; var td2=row.insertCell(-1); td2.innerHTML=item.FileName; var td4=row.insertCell(-1); td4.innerHTML="[<a href='"+handlerurl+"?download="+item.FileGuid+"'>download</a>]"; var td4=row.insertCell(-1); td4.innerHTML="[<a href='javascript:void(0)' onclick='Attachment_Remove(this)'>remove</a>]"; } } function Attachment_FindRow(element) { while(true) { if(element.nodeName=="TR") return element; element=element.parentNode; } } function Attachment_Remove(link) { var row=Attachment_FindRow(link); if(!confirm("Are you sure you want to delete '"+row.getAttribute("filename")+"'?")) return; var guid=row.getAttribute("fileguid"); var xh=CreateAjaxRequest(); xh.send("delete=" + guid); var table = document.getElementById("filelist"); table.deleteRow(row.rowIndex); for(var i=0;i<fileArray.length;i++) { if(fileArray[i].FileGuid==guid) { fileArray.splice(i,1); break; } } } function CuteWebUI_AjaxUploader_OnPostback() { var uploader = document.getElementById("myuploader"); var guidlist = uploader.value; var xh=CreateAjaxRequest(); xh.send("guidlist=" + guidlist); //call uploader to clear the client state uploader.reset(); if (xh.status != 200) { alert("http error " + xh.status); setTimeout(function() { document.write(xh.responseText); }, 10); return; } var list = eval(xh.responseText); //get JSON objects fileArray=fileArray.concat(list); AppendToFileList(list); } function ShowFiles() { var msgs=[]; for(var i=0;i<fileArray.length;i++) { msgs.push(fileArray[i].FileName); } alert(msgs.join("\r\n")); } </script> </head> <body> <div class="demo"> <h2>Building attachment table (AJAX)</h2> <p>This sample demonstrates how to build your own attachment table.</p> <?php $uploader=new PhpUploader(); $uploader->MaxSizeKB=10240; $uploader->Name="myuploader"; $uploader->MultipleFilesUpload=true; $uploader->InsertText="Select multiple files (Max 10M)"; $uploader->AllowedFileExtensions="*.jpg,*.png,*.gif,*.bmp,*.txt,*.zip,*.rar"; $uploader->Render(); ?> <br/><br/> <table id="filelist" style='border-collapse: collapse' class='Grid' border='0' cellspacing='0' cellpadding='2'> </table> <br/><br/> <button onclick="ShowFiles()">Show files</button> </div> <script type='text/javascript'> //this is to show the header.. ShowAttachmentsTable(); </script> <script type='text/javascript'> function CuteWebUI_AjaxUploader_OnTaskComplete(task) { var div=document.createElement("DIV"); var link=document.createElement("A"); link.setAttribute("href","savefiles/"+task.rand); link.innerHTML="You have uploaded file : savefiles/"+task.rand; link.target="_blank"; div.appendChild(link); document.body.appendChild(div); } </script> </body> </html> and here is the phpuploader.php file just in case I am having trouble getting my upload file to work... Form HTML: Code: [Select] <form action="" method="POST"> <input type="file" name="file" /> <input type='"submit" name="upload" value="Upload" /> </form> PHP: Code: [Select] if($_POST["upload_avatar"]){ $upload_path = "images/users/"; $file = $_FILES["file"]["name"]; $extension_types = array("gif","jpg","jpeg","png"); if($file){ $filename = stripslashes($_FILES["file"]["name"]); $extension = getExtension($filename); $extension = strtolower($extension); $size = filesize($_FILES["file"]["tmp_name"]); if(in_array($extension, $extension_types)){ if($size <= $max_file_size){ $file_search = glob($upload_path . strtolower($username) . '*'); array_map("unlink", $file_search); $file_name = $upload_path . strtolower($username) . "." . $extension; $copied = copy($_FILES["file"]["tmp_name"], $file_name); if (!$copied){ $r_error = "Upload has failed"; } } else{$r_error = "File too big";} } else{$r_error = "Unknown file extension";} } else{$r_error = "No file chosen";} } Every time, it gives me the "No File Chosen" error. It doesn't seem to be actually uploading the file... I hope this isn't just some stupid thing I am looking over, can someone help me? Hello I am new to programming, coding, php... and need some help. I have some code that uploads a file and does some basic checks but I also want it to rename the file possibly adding the time stamp. Heres what I have so far. cheers. $tbl_name="guestbook"; // Table name $email = $_REQUEST["email"]; $name = $_REQUEST["name"]; $comment = $_REQUEST["comment"]; $_FILES["file"]["name"]; $_FILES["file"]["type"]; $_FILES["file"]["size"]; $_FILES["file"]["tmp_name"]; $_FILES["file"]["error"]; $datetime = date("dmy"); $uploaddir = "upload/"; $filename = $_FILES["file"]["name"]; $pathinfo = pathinfo($_FILES['userfile1']['name']); mysql_connect("$host", "$username", "$password")or die("cannot connect server "); mysql_select_db("$db_name")or die("cannot select DB"); $sql="INSERT INTO $tbl_name(name, email, comment, datetime)VALUES('$name', '$email', '$comment', '$datetime')"; $result=mysql_query($sql); if($result){ echo "Successful added update to the Melody Bear Bulletin Board"; echo "<BR>"; echo "<a href='ViewBulletinBoard.php'>View Bulletin Board</a>"; } else { echo "ERROR"; } 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 />"; if (file_exists("upload/" . $_FILES["file"]["name"])) { echo $_FILES["file"]["name"] . " already exists. "; } else { move_uploaded_file($_FILES["file"]["tmp_name"], "upload/" . $_FILES["file"]["name"]); echo "Stored in: " . "upload/" . $_FILES["file"]["name"]. "<br>"; } } } else { echo "Invalid file"; } mysql_close(); ?> please just deleting this post I think i figured it out Hi All Please can someone help me. I have a CSV file with over 3000 lines. Each one contains the following information Country Insurance Name Mandatory or Optional Description and Coverage Group SIPP Cost Per Day Cost Per Week Cost Per Month Deductable I have written the following script to read line by line, compare the country and insurance with the previous and if it is the same, tag certain parts of each line onto the end of the previous. However, I am getting no output from this, and I keep getting an error saying I am using too much memory or my computer hangs. I am fairly new to php so any pointers would be good. Firstly, does my script look like it should do what I want it to do? If so, any clues how to get around the momory issue. If not, what have I done wrong? Cheers guys <?php //open file paths $handle=fopen("insurances.csv","r"); $handle_out=fopen("insuranceoutput.csv","a"); //writes the first line of the csv file into an array to act as a comparrison if($handle){ $line=fgets($handle); $line_array=explode(",",$line); $full_array=$line_array; fclose($handle); } } if($handle) { while (!feof($handle)) { // read one line into array $line=fgets($handle); $line_array=explode(",",$line); fclose($handle); //test to see if country matches previous while ($line_array[0] == $full_array[0]) { //test to see if insurance matches previous while ($line_array[1] == $full_array[1]) { //write array values 4 - 9 to main array $full_array[]=array("$line_array[4]","$line_array[5]","$line_array[6]","$line_array[7]","$line_array[8]","$line_array[9]"); } } //write to new file when new insurance is found foreach($full_array as $output) { fwrite($handle_out, "$output,"); } fwrite($handle_out,"\n"); fclose($handle_out); } // write to new file if new country is found. foreach($full_array as $output) { fwrite($handle_out, "$output,"); } fwrite($handle_out,"\n"); fclose($handle_out); } } ?> Sorry for posting this here, but for some reason the "create new topic" in linux subforum doesnt exist. anyways i made a small php script that enables me to retrieve data between two dates. now am stuck on how i should copy it or u0pload it into linux. system tells me i need to upload to /usr/bin/libexec , i am there now but i dont have the slightest idea on how to do that. help is much appreciated. Thanks I don't know why this image upload code isn't uploading the image file to the uploads/ folder.
Any help will be appreciated.
$allowedExts = array("gif", "jpeg", "jpg", "png"); $temp = explode(".", $_FILES["file"]["name"]); $extension = strtolower( end($temp) ); if ( $_FILES["file"]["size"] < 2000000 && in_array($extension, $allowedExts) ) { if ($_FILES["file"]["error"]!= 0) { echo "Return Code: " . $_FILES["file"]["error"] . "<br>"; } else { $length = 20; $randomString = substr(str_shuffle(md5(time())),0,$length); $newfilename = $randomString . "." . $extension; move_uploaded_file($_FILES["file"]["tmp_name"], "upload/" . $newfilename ); $file_location = '<a href="http://www.--.com/upload/' . $newfilename . '">http://www.--.com/upload/' . $newfilename . '</a>'; } } else { echo "Invalid upload file"; } <form enctype="multipart/form-data" action="uploader.php"> <input type="file" name="file" id="file"> <input type="submit" name="submitted" value="Submit"> </form> I have created a page for users to upload files, but for some reason end users can't access the files. we are getting an access denied page and every time files get uploaded i have to ftp to the site and change the permissions. is there something i am missing? Thank you in advance. kindly check the following code i am trying to make such an script that'll allow you to upload images on facebook from your site i am running this script locally but getting different errors like Facebook.php is being downloaded from facebook api's (Kindly provide any other working example that would be fine with me too i just need the functionality) Warning: Missing argument 2 for Facebook::__construct(), called in C:\Users\Administrator\Desktop\face\abc.php on line 16 and defined in C:\Users\Administrator\Desktop\face\library\facebook.php on line 64 Notice: Undefined variable: secret in C:\Users\Administrator\Desktop\face\library\facebook.php on line 66 Notice: Undefined variable: secret in C:\Users\Administrator\Desktop\face\library\facebook.php on line 68 Fatal error: Call to undefined method Facebook::api() in C:\Users\Administrator\Desktop\face\abc.php on line 31 Code: [Select] <html> <head> <title> Upload images to Facebook</title> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> </head> <body> <?php $app_id = 332267477347; $app_secret = "989b7e58b48f17b3463ee54ea9c4f88d"; require_once 'library/facebook.php'; $facebook = new Facebook(array( 'appId' => $app_id, 'secret' => $app_secret, 'fileUpload' => true )); //It can be found at https://developers.facebook.com/tools/access_token/ $access_token = 'I pout here the key of my profile'; $params = array('access_token' => $access_token); //The id of the fanpage $fanpage = '194458563914948'; //The id of the album $album_id ='406221796071956'; //Replace arvind07 with your Facebook ID $accounts = $facebook->api('/faizan.gemeni/accounts', 'GET', $params); foreach($accounts['data'] as $account) { if( $account['id'] == $fanpage || $account['name'] == $fanpage ){ $fanpage_token = $account['access_token']; } } $valid_files = array('image/jpeg', 'image/png', 'image/gif'); if(isset($_FILES) && !empty($_FILES)){ if( !in_array($_FILES['pic']['type'], $valid_files ) ){ echo 'Only jpg, png and gif image types are supported!'; }else{ #Upload photo here $img = realpath($_FILES["pic"]["tmp_name"]); $args = array( 'message' => 'This photo was uploaded via WebSpeaks.in', 'image' => '@' . $img, 'aid' => $album_id, 'no_story' => 1, 'access_token' => $fanpage_token ); $photo = $facebook->api($album_id . '/photos', 'post', $args); if( is_array( $photo ) && !empty( $photo['id'] ) ){ echo '<p><a target="_blank" href="http://www.facebook.com/photo.php?fbid='.$photo['id'].'">Click here to watch this photo on Facebook.</a></p>'; } } } ?> <!-- Form for uploading the photo --> <div > <p>Select a photo to upload on Facebook Fan Page</p> <form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" enctype="multipart/form-data"> <p>Select the image: <input type="file" name="pic" /></p> <p><input class="post_but" type="submit" value="Upload to my album" /></p> </form> </div> </body> </html> |