Display die('message') problem - php

How do i display the die() message in if($allowed) at the same place as move_uploaded_file result?
<?php
$destination_path = $_SERVER['DOCUMENT_ROOT'].'/uploads/';
$allowed[] = 'image/gif';
$allowed[] = 'image/jpeg';
$allowed[] = 'image/pjpeg';
$allowed[] = 'image/png';
if (!in_array($_FILES['myfile']['type'], $allowed)) {
die('Wrong file type!');
}
$result = 0;
$now = time();
$ext = end(explode(".", $_FILES['myfile']["name"]));
$filename = ( $_FILES['myfile'][0].$now.".".$ext);
if(#move_uploaded_file($_FILES['myfile']['tmp_name'], $destination_path .$filename)) {
$result = 1;
}
sleep(1);
?>
<script language="javascript" type="text/javascript"> window.top.window.stopUpload('<? php echo $result; ?>', '<?php echo $filename; ?>');</script>
Javascript to display move_uploaded_file result:
function stopUpload(success,filename){
var result = '';
if (success == 1){
result = '<span class="msg">Great!<\/span><br/><br/>';
}
else {
result = '<span class="emsg">Not so great.<\/span><br/><br/>';
}

do you mean in the same condition?
if (in_array($_FILES['myfile']['type'], $allowed) && #move_uploaded_file($_FILES['myfile']['tmp_name'], $destination_path .$filename)) {
$result = 1;
} else {
die("Error while uploding file");
}

Add a third $result condition (-1, for example), then instead of die(message);, do $result = -1; exit(0);. Change the JavaScript so else if (success == -1) { result = 'Wrong file type!' }

Related

Upload file in PHP?

When I upload an image file to the host, why the file repeat filename extension again ? I check the filename in the host is like test.jpg.jpg
Here is the code:
$uploadPath = "../../upload/Image/";
$handle = new Upload($_FILES['pic'], 'zh_TW');
if($handle->uploaded){
$pic=$_FILES['pic']['name'];
if($pic != ''){
$filename = $pic;
}
else{
$microSecond = microtime();
$filename = substr($microSecond, 11, 20).substr($microSecond, 2, 8);
}
$handle->file_new_name_body = $filename;
$handle->image_resize = true;
$handle->image_ratio_y = true;
$handle->image_x = 212;
$handle->image_ratio_fill = true;
$handle->allowed = array('image/*');
$handle->file_overwrite = true;
$handle->process($uploadPath);
if($handle->processed){
$handle->file_dst_name = $filename;
}
else{
echo "<script>";
echo "alert('$handle->error');";
echo "history.back();";
echo "</script>";
die;
}
}
else{
$filename = $_POST['currentPic'];
}
Base on your conditions. you can just get the name onle part by explode function.
if($handle->uploaded){
$pic=$_FILES['pic']['name'];
if($pic != ''){
//$filename = $pic;
$filename = explode(".",$pic)[0];
}
else{
$microSecond = microtime();
$filename = substr($microSecond, 11, 20).substr($microSecond, 2, 8);
}
This is so you dont need to modify your class, also if you modify your class you will get trouble on the "ELSE" side of your condition that will cause additional spending time where to get the extension.

Pass $_FILE data to $.getJSON

I want to pass the $_FILES array to .getJSON.
Here is my jquery:
$.getJSON(link+'api/images/upload.php',{action:'image.upload',id:id,img:img}, function (response){
var url = this.url;
var result = response.message;
if(response.status == 200){
var data = response.data;
console.log(data);
try_print('Data',data,try_dbg);
}
else{
alert(response.message);
}
});
Here is my api:
switch($_REQUEST['action']){
case 'image.upload':
$id = $_REQUEST['id'];
$img = $_FILES['img']['name']; //echo $img;
$temp = explode(".", $_FILES["img"]["name"]);
$extension = end($temp);
$error = $_FILES["img"]["error"];
if(!empty($id)){
if(!empty($img)){
if(is_writable($original)){
if(in_array($extension, $allowedExts)){
if($error == 0){
$filename = $_FILES["img"]["tmp_name"];
list($width, $height) = getimagesize($filename);
$a = apiPicture($original, $id, $_FILES["img"]);
$return['status'] = 'success';
$return['url'] = $original.$_FILES["img"]["name"];
$return['width'] = $width;
$return['height'] = $height;
$return['status'] = 200;
$return['message'] = 'Success.';
}
else{
$return['status'] = 400;
$return['message'] = 'Error: '.$error;
}
.... the rest of the error codes
break;
default:
$return['message'] = 'Unknown Request';
}
Is there a solution for this, can I pass an image through .getJSON?

jQuery/PHP File Upload Times Out Before Loading Next Page

So I am developing the following image upload script, based off an existing open-source script. It's currently viewable live here: http://images.oneightynyc.com/
Now if you take any series of regular sized images (under 5mb) and proceed to upload them, the upload process goes just fine. Uploads the files, and brings you to a page that displays the link codes to those files. However let's say you upload a few large images, like the following:
http://imaging.nikon.com/lineup/dslr/d90/img/sample/pic_005b.jpg
http://imaging.nikon.com/lineup/dslr/d90/img/sample/pic_003b.jpg
The uploads happen in the process, however the script never brings you to the uploaded page. The only way I am aware that the upload has actually taken place is if I browse to the Gallery page and see that the files are listed there.
Here is the uploader.php file which handles the upload:
<?
//ob_start();
session_start();
$auth_id=$_SESSION['userid'];
if (!$auth_id || empty($auth_id) || $auth_id==""){
$auth_id = 0;
}
require_once("config.php");
require_once("limits.php");
require_once("ftp.class.php");
require_once("func.php");
$link = mysql_connect($db_server, $db_user, $db_password) or die("Could not connect to the database.");
mysql_select_db($db_name) or die("Could not select the database.");
if ($config[Uploads] == 0) {
$msg= "<center><b><br><br><br>Uploads are temporarily disabled by the site admin</center></b>";
}
else if ($config[Uploads] == 1 && !$auth_id) {
$msg= "<center><b><br><br><br>You have to Register before you will be able to upload photos.</center></b>";
}
$query = "select count(*) as total from ftp where status=1";
$result = mysql_query($query) or die("Query failed.");
while ($row = mysql_fetch_array($result))
{
$total=$row[total];
}
if($total<=0)
{
$no_server="1";
$ftpid=0;
$url=$server_url."/images/";
}
else
{
$query = "select * from ftp where status=1 ORDER BY RAND() limit 1";
$result = mysql_query($query) or die("Query failed.");
while ($row = mysql_fetch_array($result))
{
$no_server="0";
$ftpid=$row['ftpid'];
$path=$row['name'];
$url=$row['dir'];
$host=$row['host'];
$user=$row['user'];
$pass=$row['ftppass'];
}
}
// get variables for fields on upload screen
$tos = $_POST['tos'];
$prv = $_POST['prv'];
if($prv!="1")
$prv=0;
$uploaderip = $_SERVER['REMOTE_ADDR'];
$messages="";
$msg="";
$newID="";
$FileName="";
$FileFile="";
$FileUrl="";
$FileUrlLink="";
$FiletnUrl="";
// check for blocked ip address
if ($uploaderip != "") {
$query = "select ip from blocked where ip = '$uploaderip'";
$result = mysql_query($query) or die("Query failed.");
$num_rows = mysql_num_rows($result);
if ($num_rows > 0) {
$msg= "Your IP address (".$uploaderip.") has been blocked from using this service.";
}
}
if ($config[AcceptTerms]=="1"){
if ($tos=="")
{
$msg= "You must check the box stating you agree to our terms.";
echo "<script language='javascript'>parent.upload('".$msg."','".$newID."','".$messages."','".$FileName."','".$FileFile."','".$FileUrl."','".$FileUrlLink."','".$FiletnUrl."','".$page_url."','".$server_url."','".$site_name."','".$HotLink."');</script>";
}
}
if($msg=="")
{
// check for a file
for($i=0;$i<=14;$i++)
{
$err="0";
$thefile = $_FILES['thefile'.$i];
if ($thefile['name']!="")
{
// check for valid file extension
$path_parts = pathinfo($thefile['name']);
$file_ext = strtolower($path_parts['extension']);
if ($err == "0")
{
// check for valid file type
if (!in_array_nocase($file_ext, $valid_file_ext))
{
$messages.= "|<em>".$thefile['name']."</em> is not in a valid format (".$valid_mime_types_display.")";
$err="1";
}
}
if ($err == "0") {
// check for valid image file
$imageinfo = getimagesize($_FILES['thefile0']['tmp_name']);
if(!eregi('image',$imageinfo['mime'])) {
$messages.="|". "Sorry, This is not a valid image file!";
$err="1"; } }
if ($err == "0")
{
// check for valid file size
if ($thefile['size'] > ($max_file_size_b))
{
$filesizemb =($thefile['size']/1048576);
$filesizemb = number_format($filesizemb, 3);
$messages.="Sorry but this image size is ".$filesizemb." MB which is bigger than the max allowed file size of ".$max_file_size_mb." MB.";
$err="1";
}
}
// save the file, if no error messages
if ($err == "0")
{
// replace special chars with spaces
$thefile['name'] = eregi_replace("[^a-z0-9.]", " ", $thefile['name']);
// Replace multiple spaces with one space
$thefile['name'] = ereg_replace(' +', ' ', $thefile['name']);
// Replace spaces with underscore
$thefile['name'] = str_replace(' ', '_', $thefile['name']);
// Replace hyphens with underscore
$thefile['name'] = str_replace('-', '_', $thefile['name']);
// Replace multiple underscores with one underscore
$thefile['name'] = ereg_replace('_+', '_', $thefile['name']);
$path_parts = pathinfo($thefile['name']);
// if php < 5.2
if(!isset($path_parts['filename'])){
$path_parts['filename'] = substr($path_parts['basename'], 0,strpos($path_parts['basename'],'.'));
}
$thefile['name'] = strpos($path_parts['filename'], '.');
$thefile['name'] = substr($path_parts['filename'], 0, 22); // limit file name length to 22 chars from the beginning
$thefile['name'] = $thefile['name'] . "." . strtolower($path_parts['extension']);
// Generate prefix to add to file name
$prefix = rand(99,999);
// Add prefix to file name
$newFileName = $prefix . $thefile['name'];
// SAVE THE PICTURE
$FileName.="|". newImageName($thefile['name']);
$FileFile.="|". $server_dir . $newFileName;
$newFile = $server_dir . $newFileName;
$newFileUrl = $url . $newFileName;
$FileUrl.="|". $url . $newFileName;
$newFileUrlLink = $server_save_directory . $newFileName;
$FileUrlLink.="|". $newFileName;
if (in_array_nocase($file_ext, $valid_file_ext))
{
$lx = 3;
if ($file_ext == "jpeg") {
$lx = 4; }
$tnFileName = substr($newFileName, 0, strlen($newFileName) - $lx) . "jpg";
$tnFileName = str_replace('.', '_tn.', $tnFileName);
$tnFile = $server_dir . $tnFileName;
$FiletnUrl.="|". $url . $tnFileName;
$tnFileUrl = $url . $tnFileName;
}
else
{
$tnFileName = "";
$tnFile = "";
$tnFileUrl = "";
}
$filesize = $thefile['size'];
$newID = "";
if (!#copy($thefile['tmp_name'], $newFile))
{
$messages.="|". "Please check site settings in admin panel and set proper value for server local path.<br><br>Also please make sure the images folder is chmodded to 0777";
}
else
{
// add to database
if($auth_id)
$uid=$auth_id;
else $uid=0;
//ftpupload($host,$user,$pass,$path."/".$dir."/".$newFileName,$newFileUrl);
//ftpupload
if($no_server=="0")
{
$ftp =& new FTP();
if ($ftp->connect($host)) {
if ($ftp->login($user,$pass)) {
$ftp->chdir($path);
$ftp->put($newFileName,$newFile);
}
}
// unlink($newFile);
}
//ftpupload
$date_add=time();
$query = "INSERT INTO images (prv,ftpid,userid,filename, tn_filename, filepath, ip, filesize,added) VALUES ($prv,$ftpid,$uid,'$newFileName', '$tnFileName', '$url', '$uploaderip', $filesize,$date_add)";
mysql_query($query) or die("Database entry failed.");
$newID.="|". mysql_insert_id();
}
if ($file_ext == "jpeg" ||$file_ext == "jpg" || $file_ext == "png" || $file_ext == "gif" || $file_ext == "bmp")
{
if ($file_ext == "jpg")
{
$source_id = imagecreatefromjpeg($newFile);
}
if ($file_ext == "jpeg")
{
$source_id = imagecreatefromjpeg($newFile);
}
elseif ($file_ext == "png")
{
$source_id = imagecreatefrompng($newFile);
}
elseif ($file_ext == "gif")
{
$source_id = imagecreatefromgif($newFile);
}
elseif ($file_ext == "bmp")
{
$source_id = ImageCreateFromBMP($newFile);
}
$true_width = imagesx($source_id);
$true_height = imagesy($source_id);
}
}
}
}
mysql_close($link);
// create URL links to display to user
$showURL1 = false; // image on hosted page - image only
$showURL2 = false; // direct link to file - all
$showURL3 = false; // HTML for img - image only
$showURL4 = false; // [img][/img] tags - image only
$showURL5 = false; // thumbnail pic - image only
// determine flags
$showURL2 = true;
if ($file_ext == "jpg" || $file_ext == "jpeg"|| $file_ext == "gif" || $file_ext == "png" || $file_ext == "bmp") {
$showURL1 = true;
$showURL3 = true;
$showURL4 = true;
}
if ($file_ext == "jpg" || $file_ext == "gif" || $file_ext == "png"|| $file_ext == "jpeg" || $file_ext == "bmp") {
$showURL5 = true;
}
echo "<script language='javascript'>parent.upload('".$msg."','".$newID."','".$messages."','".$FileName."','".$FileFile."','".$FileUrl."','".$FileUrlLink."','".$FiletnUrl."','".$page_url."','".$server_url."','".$site_name."','".$HotLink."');</script>";
}
else
{
echo "<script language='javascript'>parent.uploaderror('".$msg."');</script>";
exit;
}
function newImageName($fname) {
$timestamp = time();
$new_image_file_ext = substr($fname, strlen($fname) - 3, strlen($fname));
if ($new_image_file_ext == "peg") {
$ext = ".jpg";
} else {
$ext = "." . $new_image_file_ext;
}
$newfilename = randString() . substr($timestamp, strlen(timestamp) - 4, strlen(timestamp)) . $ext;
return $newfilename;
}
function randString() {
$newstring="";
while(strlen($newstring) < 3) {
$randnum = mt_rand(0,61);
if ($randnum < 10) {
$newstring .= chr($randnum + 48);
} elseif ($randnum < 36) {
$newstring .= chr($randnum + 55);
} else {
$newstring .= chr($randnum + 61);
}
}
return $newstring;
}
function in_array_nocase($item, $array) {
$item = &strtoupper($item);
foreach($array as $element) {
if ($item == strtoupper($element)) {
return true;
}
}
return false;
}
?>
And the upload.js script which takes care of producing the uploaded page:
var cp = new cpaint();
cp.set_transfer_mode('get');
cp.set_response_type('xml');
cp.set_debug(1);
function uploaderror(msg)
{
alert(msg);
}
function showfile()
{
var countfld=1;
countfld=document.getElementById("countfld").value+countfld;
fld=countfld.length;
if(fld>14)
{
alert("Sorry, i can upload max 15 files at once.");
return false;
}
else
{
document.getElementById("f"+fld).style.display="block";
document.getElementById("countfld").value=countfld;
}
var file=document.getElementById("f"+fld).value;
if(file=="")
{
msg="Please fill this field.";
alert(msg);
document.getElementById("f"+fld).focus();
return false;
}
}
function showfileux()
{
var countfld=1;
countfld=document.getElementById("countfldu").value+countfld;
fld=countfld.length;
if(fld>14)
{
alert("Sorry, i can upload max 15 files at once.");
return false;
}
else
{
document.getElementById("u"+fld).style.display="block";
document.getElementById("countfldu").value=countfld;
}
}
function showfileu()
{
var countfld=1;
countfld=document.getElementById("countfldu").value+countfld;
fld=countfld.length;
fldx=fld-1;
fldxx=fld.value;
if(fldxx=="")
{
msg="Email Address cannot be left empty.";
alert(msg);
document.getElementById("u"+fldxx).select();
document.getElementById("u"+fldxx).focus();
return false;
}
if(fld>14)
{
alert("Sorry, i can upload max 15 files at once.");
return false;
}
else
{
document.getElementById("u"+fld).style.display="block";
document.getElementById("countfldu").value=countfld;
}
}
function uploadfile(id)
{
if(document.getElementById(id).value==1)
{
document.getElementById("showurl").style.display="none";
document.getElementById("showfl").style.display="block";
return true;
}
if(document.getElementById(id).value==2)
{
document.getElementById("showfl").style.display="none";
document.getElementById("showurl").style.display="block";
return true;
}
document.getElementById("countfldu").value="0";
document.getElementById("countfld").value="0";
}
function show_loading()
{
document.getElementById('loading').style.display = "block";
document.getElementById('newupload').submit;
document.getElementById('submit').disabled = true;
// return true;
}
function show_loading1()
{
document.getElementById('loading1').style.display = "block";
document.getElementById('newupload1').submit;
document.getElementById('submit').disabled = true;
}
function upload(msg,newID,messages,FileName,FileFile,FileUrl,FileUrlLink,FiletnUrl,page_url,server_url,site_name,HotLink)
{
var html='<div id="wrapper"><div style="width:760px;"><center><FONT SIZE="4" COLOR="#00A4B7">Photo Links</FONT></h4><br></center><span class="body"><form name="uploadresults" action="uploademail.php" method="post">';
if(newID)
{
html=html+'<input type="hidden" name="idx[]" value="'+newID+'">';
}
if(msg)
{
var getmsg = msg.split("|");
for(i=0;i<getmsg.length;i++)
{
if(getmsg[i] && getmsg[i]!="on")
html=html+'<span style="font-weight: bold; color: red;">'+getmsg[i]+'</span><br>';
}
}
html=html+'<br><center>';
if(messages)
{
var getmessages = messages.split("|");
for(i=0;i<getmessages.length;i++)
{
if(getmessages[i] && getmessages[i]!="on")
html=html+'<span style="font-weight: bold; color: red;">'+getmessages[i]+'</span>';
}
html=html+'</center>';
}
if(FileName)
{
var getFileName = FileName.split("|");
var getFileFile = FileFile.split("|");
var getFileUrl = FileUrl.split("|");
var getFileUrlLink = FileUrlLink.split("|");
var getFiletnUrl = FiletnUrl.split("|");
var getHotLink = HotLink.split("|");
for(i=0;i<getFileName.length;i++)
{
if(getFileName[i] && getFileName[i]!="on") {
html=html+'<center><br><img src="'+getFileUrl[i]+'" style="max-width: 550px;"" /><br><br>';
html=html+'<strong>Link to add tags and delete the photo <br><div align="center"><textarea name="url1[]" cols="80" rows="1" READONLY onfocus="javascript: this.select()">'+server_url+'/view2.php?filename='+getFileUrlLink[i]+'
Let me know what you think is causing this error, as this is the final step I need to fix.
I've had similar issue with creating excel files from large data bases. What it boils down to is that the PHP script exceeds the servers set time limit. There are multiple ways to delay/extend this from built in PHP functions, some or all may be used. I personally had use a combination of the ability with AJAX to allow it run in the backgroun and then redirect that page.
Here is the documentation on how to delay/extend it:
http://php.net/manual/en/function.set-time-limit.php
Here is the documentation on how check for a time out as well:
http://php.net/manual/en/function.connection-timeout.php
If you end up going the AJAX route as I did, I highly recommend going the jQuery route instead of vanilla JS.

Issues with PHP image upload

I've been creating a HTML5 Drag & Drop image up-loader. All is good with the Javascript side of things however the PHP is driving me crazy!
I've been able to create a script that successfully places a image in a folder upon the drop of an image, however once it tries to create a thumb nail for the image and place the image link into the users db table it all goes to pot. I've sat here for hours on end, trying and trying to no avail, so i believe as it is now just about 3am GMT i should admit defeat and ask for a little help.
The JavaScript:
$(function(){
var dropbox = $('#dropbox'),
message = $('.message', dropbox);
dropbox.filedrop({
paramname:'pic',
maxfiles: 5,
maxfilesize: 200,
url: 'uploadCore.php',
uploadFinished:function(i,file,response){
$.data(file).addClass('done');
},
error: function(err, file) {
switch(err) {
case 'BrowserNotSupported':
showMessage('Your browser does not support HTML5 file uploads!');
break;
case 'TooManyFiles':
alert('Too many files!');
break;
case 'FileTooLarge':
alert(file.name+' is too large! Please upload files up to 200mb.');
break;
default:
break;
}
},
beforeEach: function(file){
if(!file.type.match(/^image\//)){
alert('Only images are allowed!');
return false;
}
},
uploadStarted:function(i, file, len){
createImage(file);
},
progressUpdated: function(i, file, progress) {
$.data(file).find('.progress').width(progress);
}
});
var template = '<div class="preview">'+
'<span class="imageHolder">'+
'<img />'+
'<span class="uploaded"></span>'+
'</span>'+
'<div class="progressHolder">'+
'<div class="progress"></div>'+
'</div>'+
'</div>';
function createImage(file){
var preview = $(template),
image = $('img', preview);
var reader = new FileReader();
image.width = 100;
image.height = 100;
reader.onload = function(e){
image.attr('src',e.target.result);
};
reader.readAsDataURL(file);
message.hide();
preview.appendTo(dropbox);
$.data(file,preview);
}
function showMessage(msg){
message.html(msg);
}
});
Now for the PHP:
<?php
// db connection
include("db-info.php");
$link = mysql_connect($server, $user, $pass);
if(!mysql_select_db($database)) die(mysql_error());
include("loadsettings.inc.php");
//$upload_dir = 'pictures/';
$allowed_ext = array('jpg','jpeg','png','gif');
if(strtolower($_SERVER['REQUEST_METHOD']) != 'post'){
exit_status('Error! Wrong HTTP method!');
}
if(array_key_exists('pic',$_FILES) && $_FILES['pic']['error'] == 0 ){
if (isset($_SESSION["imagehost-user"]))
{
$session = true;
$username = $_SESSION["imagehost-user"];
$password = $_SESSION["imagehost-pass"];
$q = "SELECT id FROM `members` WHERE (username = '$username') and (password = '$password')";
if(!($result_set = mysql_query($q))) die(mysql_error());
$number = mysql_num_rows($result_set);
if (!$number) {
session_destroy();
$session = false;
}else {
$row = mysql_fetch_row($result_set);
$loggedId = $row[0];
}
}
$date = date("d-m-y");
$lastaccess = date("y-m-d");
$ip = $_SERVER['REMOTE_ADDR'];
$type = "public";
$pic = $_FILES['pic'];
$n = $pic;
$rndName = md5($n . date("d-m-y") . time()) . "." . get_extension($pic['name']);
$upload_dir = "pictures/" . $rndName;
move_uploaded_file($pic['tmp_name'], $upload_dir.$pic['name']);
// issues starts here
$imagePath = $upload_dir;
$img = imagecreatefromunknown($imagePath);
$mainWidth = imagesx($img);
$mainHeight = imagesy($img);
$a = ($mainWidth >= $mainHeight) ? $mainWidth : $mainHeight;
$div = $a / 150;
$thumbWidth = intval($mainWidth / $div);
$thumbHeight = intval($mainHeight / $div);
$myThumb = imagecreatetruecolor($thumbWidth, $thumbHeight);
imagecopyresampled($myThumb, $img, 0, 0, 0, 0, $thumbWidth, $thumbHeight, $mainWidth, $mainHeight);
$thumbPath = "thumbnails/" . basename($imagePath);
imagejpeg($myThumb, $thumbPath);
$details = intval(filesize($imagePath) / 1024) . " kb (" . $mainWidth . " x " . $mainHeight . ")" ;
$id = md5($thumbPath . date("d-m-y") . time());
$q = "INSERT INTO `images`(id, userid, image, thumb, tags, details, date, access, type, ip)
VALUES('$id', '$loggedId', '$imagePath', '$thumbPath', '$tags', '$details', '$date', '$lastaccess', 'member-{$type}', '$ip')";
if(!($result_set = mysql_query($q))) die(mysql_error());*/
exit_status('File was uploaded successfuly!');
// to here
$result = mysql_query("SELECT id FROM `blockedip` WHERE ip = '$ip'");
$number = mysql_num_rows($result);
if ($number) die(""); // blocked IP message
function imagecreatefromunknown($path) {
$exten = get_extension($path);
switch ($exten) {
case "jpg":
$img = imagecreatefromjpeg($path);
break;
case "gif":
$img = imagecreatefromgif($path);
break;
case "png":
$img = imagecreatefrompng($path);
break;
}
return $img;
}
}
exit_status('Something went wrong with your upload!');
// Helper functions
function exit_status($str){
echo json_encode(array('status'=>$str));
exit;
}
function get_extension($file_name){
$ext = explode('.', $file_name);
$ext = array_pop($ext);
return strtolower($ext);
}
?>
It seems you pass wrong path to the imagecreatefromunknown() function. You pass $imagePath that equals $upload_dir, but your image destination is $upload_dir.$pic['name']

How to modify this script to get only the mp4 file version from youtube knowing the youtube id?

How to mofify this to get only the url of the mp4 file version?
<?php
//$debug = true;
if(empty($debug))
$debug = false;
if(empty($_GET['id']))
die('no id');
if(!preg_match('/^[A-Z0-9-_]+$/i', $_GET['id']))
die('invalid character in id');
else
$id = $_GET['id'];
if(empty($_GET['type']))
$type = 'mp4';
else
if(!preg_match('/^[A-Z]+$/i', $_GET['type']))
die('invalid character in type');
else
$type = strtolower($_GET['type']);
$url = 'http://youtube.com/get_video_info?video_id=';
$key = 'url_encoded_fmt_stream_map';
$content = file_get_contents($url.$id);
parse_str($content, $result);
if($debug)
{
echo $url.$id.'<br/>';
echo $key.'<br/>';
echo $type.'<br/>';
echo '<pre>';
print_r($result);
echo '</pre>';
}
else
{
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="videofile.'.$type.'"');
}
$type = 'type=video/'.$type;
$files = explode(',url=', $result[$key]);
$files[0] = substr($files[0], 4);
for($i=0; $i<count($files); $i++)
{
$file = urldecode($files[$i]);
$found = strpos($file, $type) > -1;
if ($debug)
{
if ($found)
echo '[THIS]';
echo ''.$file.'<br/><br/>';
}
else
{
if ($found)
{
$file = explode('; codecs=', $file);
#readfile($file[0]);
break;
}
}
}
?>
Those 3 links are all the mp4 links with different ID tages (at the end).
Itags are different HD/Normal formats for the screen resolution, Google them up.
However, if you want to land now, keep this:
<?php
$debug = true;
if(empty($debug))
$debug = false;
if(empty($_GET['id']))
die('no id');
if(!preg_match('/^[A-Z0-9-_]+$/i', $_GET['id']))
die('invalid character in id');
else
$id = $_GET['id'];
if(empty($_GET['type']))
$type = 'mp4';
else
if(!preg_match('/^[A-Z]+$/i', $_GET['type']))
die('invalid character in type');
else
$type = strtolower($_GET['type']);
$url = 'http://youtube.com/get_video_info?video_id=';
$key = 'url_encoded_fmt_stream_map';
$content = file_get_contents($url.$id);
parse_str($content, $result);
/*if($debug)
{
echo $url.$id.'<br/>';
echo $key.'<br/>';
echo $type.'<br/>';
echo '<pre>';
print_r($result);
echo '</pre>';
}
else
{
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="videofile.'.$type.'"');
}
*/
$type = 'type=video/'.$type;
$files = explode(',url=', $result[$key]);
$files[0] = substr($files[0], 4);
for($i=0; $i<count($files); $i++)
{
$file = urldecode($files[$i]);
$found = strpos($file, $type) > -1;
$itag = strpos($file, "itag=18") > -1;
if ($found & $itag){
echo ''.$file.'<br/><br/>';
}
}
?>
<?php
$debug = true;
if(empty($debug))
$debug = false;
if(empty($_GET['id']))
die('no id');
if(!preg_match('/^[A-Z0-9-_]+$/i', $_GET['id']))
die('invalid character in id');
else
$id = $_GET['id'];
if(empty($_GET['type']))
$type = 'mp4';
else
if(!preg_match('/^[A-Z]+$/i', $_GET['type']))
die('invalid character in type');
else
$type = strtolower($_GET['type']);
$url = 'http://youtube.com/get_video_info?video_id=';
$key = 'url_encoded_fmt_stream_map';
$content = file_get_contents($url.$id);
parse_str($content, $result);
/*if($debug)
{
echo $url.$id.'<br/>';
echo $key.'<br/>';
echo $type.'<br/>';
echo '<pre>';
print_r($result);
echo '</pre>';
}
else
{
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="videofile.'.$type.'"');
}
*/
$type = 'type=video/'.$type;
$files = explode(',url=', $result[$key]);
$files[0] = substr($files[0], 4);
for($i=0; $i<count($files); $i++)
{
$file = urldecode($files[$i]);
$found = strpos($file, $type) > -1;
if ($found){
echo ''.$file.'<br/><br/>';
}
}
?>

Categories