Upload file with different md5 and expire at the end - javascript
I have a script for uploading files, this script works with PHP without data base, I can upload regular file types including
$valid_exts = array("JPEG","jpeg","jpg","gif","png","PNG","bmp","svg","doc","docx","ppt","pdf","pptx","html","xml","zip","rar","mp3","mp4","mkv","exe");
but I have many link with this format. There is md5 and expire at the end
for example:
https://dl.vipdl.pro/Dl/Movies/2019/November/I.Still.Hide.to.Smoke.2016.DVDRip.SkyFilm.mkv?md5=kgTWFtHIOTmt0szuHMArQg&expires=1582385143
I want to upload these files but I can't/this parameters is different for every link and expire after 3 days is there any other way?
I write all function codes here.
function yawar_DUP($getfileurl='',$urltype='',$vid='', $conn="", $d=""){
ini_set('max_execution_time', 550);
$line = $getfileurl;
$file = fopen($line,"rb");
if(!empty($d)){
$directory = "upload/" . $d . "/";
}else{
$directory = "upload/";
}
$valid_exts = array("JPEG","jpeg","jpg","gif","png","PNG","bmp","svg","doc","docx","ppt","pdf","pptx","html","xml","zip","rar","mp3","mp4","mkv","exe");
$ext = end(explode(".",strtolower(basename($line))));
if(in_array($ext,$valid_exts)||$urltype=='youtube')
{
switch ($urltype) {
case 'youtube':
$name = 'youtubeVideo'.date("Ymdhis").'.mp4';
break;
case 'aparat':
$name = 'AparatVideo_'.$vid.'.mp4';
break;
default:
$name = basename($line);
break;
}
$prefix = 'DUP'.date("Ymdhis")."_www.website.com".'_';
$filename = $prefix.$name;
//$sanitized_filename = remove_accents( $filename ); // Convert to ASCII
// Standard replacements
$invalid = array(' '=> '-', '%20' => '-', '_' => '-',);
$filename = str_replace( array_keys( $invalid ), array_values( $invalid ), $filename );
$newfile = fopen($directory . $filename, "wb");
if($newfile)
{
while(!feof($file))
{
fwrite($newfile,fread($file,1024 * 800),1024 * 160000);
}
$finalmsg= 'File '.$filename.' uploaded successfully .';
}
else
{
$finalmsg= 'File does not exists';
}
}
else{$finalmsg= 'Invalid URL';}
return $finalmsg;
}
function yawar_DUP_ftp($fileurl='',$urltype='',$vid='',$conn=''){
ini_set('max_execution_time', 550);
$file = fopen($fileurl,"r");
$directory = "upload/";
$valid_exts = array("JPEG","jpeg","jpg","gif","png","PNG","bmp","svg","doc","docx","ppt","pdf","pptx","html","xml","zip","rar","mp3","mp4","mkv","exe");
$ext = end(explode(".",strtolower(basename($fileurl))));
if(in_array($ext,$valid_exts)||$urltype=='youtube')
{
switch ($urltype) {
case 'youtube':
$name = 'youtubeVideo'.date("Ymdhis").'.mp4';
break;
case 'aparat':
$name = 'AparatVideo_'.$vid.'.mp4';
break;
default:
$name = basename($fileurl);
break;
}
$prefix = 'DUP'.date("ymd").'_';
$filename = $prefix.$name;
$invalid = array(' '=> '-', '%20' => '-', '_' => '-',);
$filename = str_replace( array_keys( $invalid ), array_values( $invalid ), $filename );
$godup=ftp_upload_data_files($conn,$fileurl,$filename);
if (is_array($godup)) {
$finalmsg= 'File '.$godup['name'].' uploaded successfully .';
}
else
{
$finalmsg= 'Error : FTP connection not stablished!';
}
/*
$newfile = fopen($directory . $filename, "wb");
if($newfile)
{
while(!feof($file))
{
fwrite($newfile,fread($file,1024 * 800),1024 * 160000);
}
$finalmsg= 'File '.$filename.' uploaded successfully .';
}
else
{
$finalmsg= 'File does not exists';
}
*/
}
else{$finalmsg= 'Invalid URL';}
return $finalmsg;
}
function ftp_upload_data_files($conn='',$desfile,$filename)
{
$ftphost= $conn["host"];
if(substr($ftphost , 0, 4) === "ftp.") {$ftphost=substr($ftphost , 4);}
$ftp_server = 'ftp://'.$ftphost.'/public_html/'.$conn["dir"];//(FTP_CONNECTION_TYPE == "test") ? FTP_CONNECTION_FTP_SERVER_TEST : FTP_CONNECTION_FTP_SERVER_LIVE;
$http_server= 'http://'.$ftphost.'/'.$conn["dir"];
$FTP_CONNECTION_PORT= $conn["port"];
$FTP_CONNECTION_USERNAME= $conn["user"];
$FTP_CONNECTION_PASS= $conn["pass"];
$ch = curl_init();
$fp = fopen($desfile, 'rb');
//curl_setopt($curl, CURLOPT_HTTPHEADER, array('Expect:'));
curl_setopt($ch, CURLOPT_URL, $ftp_server.$filename);
curl_setopt($ch, CURLOPT_USERPWD, $FTP_CONNECTION_USERNAME.":".$FTP_CONNECTION_PASS);
curl_setopt($ch, CURLOPT_UPLOAD, 1);
curl_setopt($ch, CURLOPT_INFILE, $fp);
curl_setopt($ch, CURLOPT_INFILESIZE, filesize($desfile));
curl_exec ($ch);
$error_no = curl_errno($ch);
curl_close ($ch);
if ($error_no == 0 || $error_no == 18) {
$callback = array('link'=>$http_server.$filename , 'name'=> $filename);
} else {
$callback = $error_no;
}
return $callback;
}
function yawarDUP_getFileSize($fileurl){
//URL of the remote file that you want to get
//the file size of.
$remoteFile = $fileurl;
//Create a cURL handle with the URL of
//the remote file.
$curl = curl_init($remoteFile);
//Set CURLOPT_FOLLOWLOCATION to TRUE so that our
//cURL request follows any redirects.
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
//We want curl_exec to return the output as a string.
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
//Set CURLOPT_HEADER to TRUE so that cURL returns
//the header information.
curl_setopt($curl, CURLOPT_HEADER, true);
//Set CURLOPT_NOBODY to TRUE to send a HEAD request.
//This stops cURL from downloading the entire body
//of the content.
curl_setopt($curl, CURLOPT_NOBODY, true);
//Execute the request.
curl_exec($curl);
//Retrieve the size of the remote file in bytes.
$fileSize = curl_getinfo($curl, CURLINFO_CONTENT_LENGTH_DOWNLOAD);
//Convert it into KB
$fileSizeMB = round(round($fileSize / 1024) / 1024);
return $fileSizeMB;
}
function ftp_get_file_names()
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "ftp://$ftp_server/");
curl_setopt($ch, CURLOPT_PORT, $FTP_CONNECTION_PORT);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERPWD, $FTP_CONNECTION_USERNAME.":".$FTP_CONNECTION_PASS);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_DIRLISTONLY, TRUE);
$files_list = curl_exec($ch);
curl_close($ch);
// The list of all files names on folder
$file_names_array= explode("\n", $files_list);
// Filter and exclude array elements not valid
foreach ($file_names_array as $file_name)
{
if (preg_match('#^'.FILES_PREFIX.'#', $file_name) === 1) {
$file_names[] = $file_name;
}
}
return $file_names;
}
function yawar_get_aparat_videos($aparatkey,$keytype='',$vnumber='') {
if(!is_array($aparatkey)){
$aparatkey= (strpos($aparatkey, 'https://www.aparat.com/') !== false) ? after_last('/', $aparatkey ) : $aparatkey;
}
if ($keytype==='channel'||empty($keytype)) {
$aurl = 'https://www.aparat.com/etc/api/videoByUser/username/'.$aparatkey.'/perpage/'.$vnumber;
$chvid= yawar_get_json_data($aurl);
$loopvids= $chvid->videobyuser;
$fetchtype= (!empty($loopvids)) ? 'videobyuser' : 'videobytag' ;
}
if ($keytype==='MULTIVIDEO'){
foreach ($aparatkey as $key => $videokey) {
$msvids[$key]= array('uid' => $videokey);
}
$loopvids = $msvids;
$loopvids = array_map(function($loopvids){return (object)$loopvids;}, $loopvids);
}
if ($fetchtype=='videobytag') {
$aurl='https://www.aparat.com/etc/api/videobytag/text/'.$aparatkey;
$chvid= yawar_get_json_data($aurl);
$loopvids= $chvid->videobytag;
}
if ($keytype==='singlevideo'||empty($loopvids)) {
$loopvids = array(array('uid'=>$aparatkey));
$loopvids = array_map(function($loopvids){return (object)$loopvids;}, $loopvids);
}
foreach ($loopvids as $item) {
//https://www.aparat.com//video/video/config/videohash/$aparatkey/watchtype/site
//https://www.aparat.com/etc/api/video/videohash/$aparatkey
$svdata= yawar_get_json_data('https://www.aparat.com//video/video/config/videohash/'.$item->uid.'/watchtype/site');
$svxml = (simplexml_load_file("https://www.aparat.com//video/video/config/videohash/".$item->uid."/watchtype/site","SimpleXMLElement", LIBXML_NOERROR | LIBXML_ERR_NONE)) ? simplexml_load_file("https://www.aparat.com//video/video/config/videohash/".$item->uid."/watchtype/site") : "";
if(empty($svxml)){echo '<p class="ltr text-left f-nim grey-text text-center"><i class="fas fa-exclamation-triangle pr-1 align-text-top amber-text"></i>Aparat Error: failed to fetch this video id: '.$item->uid.', So im ignored it</p>' ; continue;}
$vurl = before_last('__', $svxml->file );
$viQuality = between_last('-','p', $vurl);
if (!empty($viQuality)) {
switch ($viQuality) { //increase video Quality.
case '720':
$avaiqu= array('720p','480p','360p');
break;
case '480':
$avaiqu= array('720p','480p','360p');
break;
case '360':
$avaiqu= array('480p','360p','240p');
break;
case '270':
$avaiqu= array('360p','270p','240p');
break;
case '240':
$avaiqu= array('360p','270p','240p');
break;
case '144':
$avaiqu= array('240p','144p');
break;
default:
$avaiqu= array($viQuality.'p');
break;
}
$x=0;
foreach ($avaiqu as $value) {
$thisvurl= before_last('-', $vurl).'-'.$value.'.mp4';
$file_headers = #get_headers($thisvurl);
if (strpos($file_headers[0], '200') !== false) {
$Avurl[$x]=$thisvurl;
$x++;
}
}
}else{$Avurl[0]=$vurl.'.mp4';}
$Avfile=$Avurl;
$Avposter= $svdata->video->big_poster;
$Avtitle= $svdata->video->title;
$Avdescription= $svdata->video->description;
$Avuid= $item->uid;
$Avuserid= $svdata->video->username;
$Avusername= $svdata->video->sender_name;
$Avuserpage= 'https://www.aparat.com/'.$Avuserid;
$Avlink= 'https://www.aparat.com/v/'.$Avuid;
$Avuserlogo= $svdata->video->profilePhoto;
$Avvisits= 0+$svdata->video->visit_cnt;
$Avlikes= 0+$svdata->video->like_cnt;
$Avcat= $svdata->video->cat_name;
$Avtags= $svdata->video->tags; foreach ($Avtags as $key => $tag) {$Avtags[$key] = $tag->name;}
$Avdate= $svdata->video->create_date;
$Aisofficial= $svdata->video->official;
$videodata[]=array('data'=> array('from'=>'aparat', 'vid'=>$Avuid, 'title'=>$Avtitle, 'description'=>$Avdescription, 'video'=>$Avfile, 'poster'=>$Avposter,'alink'=>$Avlink, 'userid'=>$Avuserid, 'username'=>$Avusername, 'userlink'=>$Avuserpage, 'userlogo'=> $Avuserlogo, 'official'=> $Aisofficial, 'adate'=>$Avdate,'tags'=> $Avtags, 'cat'=>$Avcat , 'likes'=>$Avlikes, 'views'=>$Avvisits, 'quality'=>$avaiqu));
$c++; if ($c==$vnumber) {break;}
} //end foreach.
return $videodata;
}//end func.
/**
* Youtube Fetch System.
**/
function yawar_get_youtubevideos($youtubeurl){
$youtubekey= (strpos($youtubeurl, 'https://www.youtube.com/') !== false) ? after_last('/watch?v=', $youtubeurl ) : $youtubeurl;
$videosrc= yawar_get_youtubevideo_info($youtubekey);
return $videosrc;
}
function yawar_get_youtubevideo_info($video_id) {
$vinfo = 'https://www.youtube.com/get_video_info?video_id='.$video_id;
$video_data= file_get_contents($vinfo);
$wm_string = iconv("windows-1251", "utf-8", $video_data);
parse_str(urldecode($wm_string), $result);
$json = json_encode($result);
$end= json_decode($json,true);
$video= after('url=',$end['url_encoded_fmt_stream_map']);
return $video;
/*echo '<div class="col-10 mx-auto position-relative">
<div class="video p-1">
<video class="video-fluid w-100" poster="" controls>
<source src="'.$video.'" type="video/mp4">
Your browser does not support the video tag.
</video>
</div>
<hr>';
echo '</div>'; */
}
function yawar_get_json_data($jsonURL){
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, $jsonURL);
$result = curl_exec($ch);
curl_close($ch);
$pdata= json_decode($result);
return $pdata;
}
function after ($thisvar, $inthat)
{
if (!is_bool(strpos($inthat, $thisvar)))
return substr($inthat, strpos($inthat,$thisvar)+strlen($thisvar));
};
function after_last ($thisvar, $inthat)
{
if (!is_bool(strrevpos($inthat, $thisvar)))
return substr($inthat, strrevpos($inthat, $thisvar)+strlen($thisvar));
};
function before ($thisvar, $inthat)
{
return substr($inthat, 0, strpos($inthat, $thisvar));
};
function before_last ($thisvar, $inthat)
{
return substr($inthat, 0, strrevpos($inthat, $thisvar));
};
function between ($thisvar, $that, $inthat)
{
return before ($that, after($thisvar, $inthat));
};
function between_last ($thisvar, $that, $inthat)
{
return after_last($thisvar, before_last($that, $inthat));
};
// use strrevpos function in case your php version does not include it
function strrevpos($instr, $needle)
{
$rev_pos = strpos (strrev($instr), strrev($needle));
if ($rev_pos===false) return false;
else return strlen($instr) - $rev_pos - strlen($needle);
};
?> ``
Related
How to use drag and drop with knockoutJs and php?
I'm trying for several hours, to understand the js file of knockout-binding. Can you please help me using php to upload it to my sql server? The following picture shows the layout of drag and drop. This one shows the php code when the submit button is pressed to upload photos: <?php function resizeImage($resourceType,$image_width,$image_height,$resizeWidth,$resizeHeight) { // $resizeWidth = 100; // $resizeHeight = 100; $imageLayer = imagecreatetruecolor($resizeWidth,$resizeHeight); imagecopyresampled($imageLayer,$resourceType,0,0,0,0,$resizeWidth,$resizeHeight, $image_width,$image_height); return $imageLayer; } session_start(); // *** Include the class if (isset($_POST['submit'])) { $newFileName = $_POST['filename']; if (empty($_POST['filename'])) { $newFileName = "gallery"; }else { $newFileName = strtolower(str_replace(" ", "-", $newFileName)); } $imageTitle = $_POST['filetitle']; $imageDesc = $_POST['filedesc']; $file = $_FILES['file']; $fileName = $file["name"]; $fileType = $file["type"]; $fileTempName = $file["tmp_name"]; $fileError = $file["error"]; $fileSize = $file["size"]; $fileExt = explode(".", $fileName); $fileActualExt = strtolower(end($fileExt)); $allowed = array("jpg", "jpeg", "png"); if (in_array($fileActualExt, $allowed)){ if ($fileError === 0) { if ($fileSize < 2000000) { $imageFullName = $newFileName . "." . uniqid("", true) . "." . $fileActualExt; $fileDestination = "../img/gallery/" . $imageFullName; include_once "db_connection.php"; $sql = "SELECT * FROM users;"; $stmt = mysqli_stmt_init($conn); if (!mysqli_stmt_prepare($stmt, $sql)) { echo "SQL statement failed"; }else{ mysqli_stmt_execute($stmt); $result = mysqli_stmt_get_result($stmt); $rowCount = mysqli_num_rows($result); $setImageOrder = $rowCount + 1; $sql = "UPDATE users SET imgFullName =?, orderGallery=? WHERE userId =?;"; if (!mysqli_stmt_prepare($stmt, $sql)) { echo "SQL statement failed"; } else{ // Image editing $new_width = 800; $new_height = 600; $sourceProperties = getimagesize($fileTempName); $uploadImageType = $sourceProperties[2]; $sourceImageWidth = $sourceProperties[0]; $sourceImageHeight = $sourceProperties[1]; $session_id = $_SESSION['userId']; echo $fileDestination; mysqli_stmt_bind_param($stmt, 'sii', $imageFullName, $setImageOrder, $session_id); mysqli_stmt_execute($stmt); echo $fileDestination . "file destination"; echo $fileTempName . "file temp name"; switch ($uploadImageType) { case IMAGETYPE_JPEG: $resourceType = imagecreatefromjpeg($fileTempName); $imageLayer = resizeImage($resourceType,$sourceImageWidth,$sourceImageHeight,$new_width,$new_height); imagejpeg($imageLayer,$fileDestination); break; case IMAGETYPE_GIF: $resourceType = imagecreatefromgif($fileTempName); $imageLayer = resizeImage($resourceType,$sourceImageWidth,$sourceImageHeight,$new_width,$new_height); imagegif($imageLayer,$fileDestination); break; case IMAGETYPE_PNG: $resourceType = imagecreatefrompng($fileTempName); $imageLayer = resizeImage($resourceType,$sourceImageWidth,$sourceImageHeight,$new_width,$new_height); imagepng($imageLayer,$fileDestination); break; default: $imageProcess = 0; break; } if ($stmt->error) { echo "Failure!!! " . $stmt->error; } else { // move_uploaded_file($fileTempName, $fileDestination); } header("Location: ../putaria.php?upload=success"); } } }else { echo "File size is too big!"; exit(); } }else { echo "You had an error!"; exit(); } }else { echo "You need to upload a proper file type!"; exit(); } } For that code, only works when I press the submit button to upload the pictures. But in this case, I drop and drag them to the web site, and I want to know how to do it.
Unpack Javascript with PHP
I need a way to unpack JavaScript with PHP the changing code is on my domain here http://beastfeeds.com/ty9.php the full code is in page source view-source:http://beastfeeds.com/ty9.php for some odd reason the webpage only displays part of the code but the full one is there! I just need it to run and decrypt the code so it displays the decrypted code so i can grab the m3u8 from the output as it changes on every page load. Here is what i am trying to run to achieve it which works fine with Javascript Eval (U.n.p.a.c.k.e.d) but not with this format <?php class JavaScriptUnpacker { private $unbaser; private $payload; private $symtab; private $radix; private $count; function Detect($source) { $source = preg_replace("/ /","",$source); preg_match("/eval\(function\(p,a,c,k,e,[r|d]?/", $source, $res); Debug::Write($res,"detection result"); return (count($res) > 0); } function Unpack($source) { preg_match_all("/}\('(.*)', *(\d+), *(\d+), *'(.*?)'\.split\('\|'\)/",$source,$out); Debug::Write($out,"DOTALL", false); // Payload $this->payload = $out[1][0]; Debug::Write($this->payload,"payload"); // Words $this->symtab = preg_split("/\|/",$out[4][0]); Debug::Write($this->symtab,"symtab"); // Radix $this->radix = (int)$out[2][0]; Debug::Write($this->radix,"radix"); // Words Count $this->count = (int)$out[3][0]; Debug::Write($this->count,"count"); if( $this->count != count($this->symtab)) return; // Malformed p.a.c.k.e.r symtab ! //ToDo: Try catch $this->unbaser = new Unbaser($this->radix); $result = preg_replace_callback( '/\b\w+\b/', array($this, 'Lookup') , $this->payload ); $result = str_replace('\\', '', $result); Debug::Write($result); $this->ReplaceStrings($result); return $result; } function Lookup($matches) { $word = $matches[0]; $ub = $this->symtab[$this->unbaser->Unbase($word)]; $ret = !empty($ub) ? $ub : $word; return $ret; } function ReplaceStrings($source) { preg_match_all("/var *(_\w+)\=\[\"(.*?)\"\];/",$source,$out); Debug::Write($out); } } class Unbaser { private $base; private $dict; private $selector = 52; private $ALPHABET = array( 52 => '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOP', 54 => '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQR', 62 => '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ', 95 => ' !"#$%&\'()*+,-./0123456789:;<=>?#ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~' ); function __construct($base) { $this->base = $base; if($this->base > 62) $this->selector = 95; else if($this->base > 54) $this->selector = 62; else if($this->base > 52) $this->selector = 54; } function Unbase($val) { if( 2 <= $this->base && $this->base <= 36) { return intval($val,$this->base); }else{ if(!isset($this->dict)){ $this->dict = array_flip(str_split($this->ALPHABET[$this->selector])); } $ret = 0; $valArray = array_reverse(str_split($val)); for($i = 0; $i < count($valArray) ; $i++) { $cipher = $valArray[$i]; $ret += pow($this->base, $i) * $this->dict[$cipher]; } return $ret; // UnbaseExtended($x, $base) } } } class Debug { public static $debug = false; public static function Write($data, $header = "", $mDebug = true) { if(!self::$debug || !$mDebug) return; if(!empty($header)) echo "<h4>".$header."</h4>"; echo "<pre>"; print_r($data); echo "</pre>"; } } // FOLLOW ALL REDIRECTS: // This makes multiple requests, following each redirect until it reaches the // final destination. function get_redirect_final_target($url) { $ch = curl_init($url); curl_setopt($ch, CURLOPT_NOBODY, 1); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); // follow redirects curl_setopt($ch, CURLOPT_AUTOREFERER, 1); // set referer on redirect curl_exec($ch); $target = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL); curl_close($ch); if ($target) return $target; return false; } function getURL($u){ $ops = array( 'http'=>array( 'method'=>"GET", 'header'=>"Accept: text/html\r\n" . "User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:47.0) Gecko/20100101 Firefox/47.0\r\n" ) ); $co = stream_context_create($ops); $r = file_get_contents('http://' . $u, false, $co); return $r != false ? $r : ""; } function GetStringBetween($string, $start, $finish){ $string = " ".$string; $position = strpos($string, $start); if ($position == 0) return ""; $position += strlen($start); $length = strpos($string, $finish, $position) - $position; return substr($string, $position, $length); } $grab = file_get_contents("http://beastfeeds.com/ty9.php"); $streama = GetStringBetween($grab, 'var', '</script>'); $unpacker = new JavaScriptUnpacker(); $unpacked = $unpacker->Unpack($grab); preg_match_all('/\b(?:(?:https?|ftp|file):\/\/|www\.|ftp\.)[-A-Z0-9+&##\/%=~_|$?!:,.]*[A-Z0-9+&##\/%=~_|$]/i', $unpacked, $result, PREG_PATTERN_ORDER); $result = $result[0]; $stream = GetStringBetween($unpacked, "src:'", "'"); ?> <?= trim($unpacked, "\r\n\t ")?> I reallllllly need this!!!! any help is greatly appreciated i have been trying to do this for a week now.
remote login with php curl to coinbase
I am trying to create a script to login remotely to coinbase.com, but i get javascript is not enabled on submit if user/pass combination is valid. Else i get the correct response that user or pass is invalid. Is there anyway to bypass the javascript error? Any help would be much appreciated. Here is the code : <?php session_cache_limiter('nocache'); ini_set('memory_limit','-1'); error_reporting(0); $user=$_POST['email']; $pass=$_POST['password']; $random=rand(1, 100000); $cookie=$random . ".txt"; $agent="Mozilla/5.0 (Windows NT 6.3; Win64; x64; rv:56.0) Gecko/20100101 Firefox/56.0"; function doRequest($method, $url, $referer, $agent, $cookie, $vars) { $ch=curl_init(); curl_setopt($ch, CURLOPT_URL, $url); if($referer != "") { curl_setopt($ch, CURLOPT_REFERER, $referer); } curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, FALSE); curl_setopt($ch, CURLOPT_USERAGENT, $agent); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 0); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie); curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie); if ($method == 'POST') { curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $vars); } if (substr($url, 0, 5) == "https") { curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2); } $data = curl_exec($ch); curl_close($ch); if ($data) { return $data; } else { return curl_error($ch); } } function get($url, $referer, $agent, $cookie) { return doRequest('GET', $url, $referer, $agent, $cookie, 'NULL'); } function post($url, $referer, $agent, $cookie, $vars) { return doRequest('POST', $url, $referer, $agent, $cookie, $vars); } function between1($src,$start,$end){ $txt=explode($start,$src); $txt2=explode($end,$txt[1]); return trim($txt2[0]); } $url = "https://www.coinbase.com/signin"; $referer = ""; $result=get($url,'',$agent,$cookie); $token=between1($result, 'name="authenticity_token" value="', '"'); $utf=between1($result, 'name="utf8" type="hidden" value="', '"'); $token=urlencode($token); $utf=urlencode($utf); $url="https://ws.coinbase.com/app/d7be708e7945ebab11a34c530cb4dc?protocol=7&client=js&version=2.2.3&flash=false"; $result=get($url,'',$agent,$cookie); $url="https://www.coinbase.com/sessions"; $referer="https://www.coinbase.com/signin"; $vars="utf8=".$utf."&authenticity_token=".$token."&email=".urlencode($user)."&password=".urlencode($pass)."&commit=Sign+In: undefined"; $result=post($url,$referer,$agent,$cookie,$vars); echo $result; ?>
How to return json string from php array
I am doing something i don't understand how. written a php code in O.O.P and the value gotten from it are objects. but i want to convert this O.O.P object to JSON data to be used in by javascript. so I converted my converted my objects to array on the php end. the try to use the json_encode function on it the script just keep returning errors. so i tried using a function i scope out, it worked but the js keeps on rejecting the data. Below is the JS file var ajax = new XMLHttpRequest(); ajax.open('GET','user.php',true); ajax.setRequestHeader("Content-type","application/json"); ajax.onreadystatechange = function(){ if(ajax.readyState == 4 && ajax.status ==200){ var data = JSON.parse(ajax.responseText.trim()); console.log(data); console.log(data[username]); } } ajax.send(); it will return this error "SyntaxError: JSON.parse: bad control character in string literal at line 1 column 129 of the JSON data" without the JSON.parse it return undefind fro the data.username console log. Below is the PHP SCRIPT //header("Content-type: application/json"); require_once 'core/init.php'; function array2json($arr) { /*if (function_exists('json_encode')) { echo "string"; return json_encode($arr); }*/ $pars = array(); $is_list = false; $keys = array_keys($arr); $max_length = count($arr) - 1; if (($keys[0] == 0) and($keys[$max_length] == $max_length)) { $is_list = true; for ($i = 0; $i < count($keys); $i++) { if ($i != $keys[$i]) { $is_list = false; break; } } } foreach($arr as $key => $value) { if (is_array($value)) { if ($is_list) $parts[] = array2json($value); else $part[] = '"'.$key. ':'.array2json($value); } else { $str = ''; if (!$is_list) $str = '"'.$key. '"'. ':'; if (is_numeric($value)) $str. = $value; elseif($value === false) $str. = 'false'; elseif($value === true) $str. = 'true'; else $str. = '"'.addslashes($value). '"'; $parts[] = $str; } } $json = implode(',', $parts); if ($is_list) return '['.$json. ']'; return '{'.$json. '}'; } $user = new User(); $json = array(); if (!$user - > is_LOggedIn()) { echo "false"; } else { foreach($user - > data() as $key => $value) { $json[$key] = $value; //$json =json_encode($json,JSON_FORCE_OBJECT); //echo $json; } /*$details = '{"'.implode('", "', array_keys($json)).'"'; $data = '"'.implode('" "', $json).'"}'; die($details.' / '.$data);*/ $json = array2json($json); print $json; } PLEASE HELP ME OUT TO SORT THIS ERROR THANK YOU.
You need to set the response headers, and ensure you are not violating CORS: /* * Construct Data Structure */ $response = [ 'value1', 'value2' ]; /* * Format Data */ $jsonResponse = json_encode ( $response, JSON_PRETTY_PRINT ); /* * Prepare Response */ header('content-type: application/json; charset=UTF-8'); /* * ONLY if you want/need any domain to be able to access it. */ header('Access-Control-Allow-Origin: *'); /* * Send Response */ print_r ( $jsonResponse ); /* * Return with intended destruction */ die;
Just use the json functions json_encode and json_decode to convert arrays into json string or vice versa: $myArray = array("value1", "value2"); echo json_encode($myArray);
If websocket handshake completes successfully should I see an onopen event in my client?
First if you could tell me if there is something here that is wrong : client: var ws = new WebSocket('ws://localhost:9090/websocket_server.php');// ws://echo.websocket.org/echo console.log(ws); ws.onopen = function(e) { console.log("Connection open...", e); ws.send("Hello WebSocket!"); }; ws.onmessage = function(e) { if(typeof e.data === "string"){ console.log("String message received", e, e.data); } else { console.log("Other message received", e, e.data); } }; ws.onerror = function(e) { console.log("WebSocket Error: " , e); }; ws.onclose = function(e) { console.log("Connection closed", e); }; server: <?php defined('KEY_SUFFIX') ? null : define('KEY_SUFFIX', "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"); error_reporting(E_ALL); set_time_limit(0); ob_implicit_flush(); $sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); socket_bind($sock, 'localhost', 9090); socket_listen($sock); while (true) { $client = socket_accept($sock) or die('socket_accept returned false');; //$buf = socket_read($client, 1024); $buf = null;$key=null; while ( $line = socket_read($client, 2048, PHP_NORMAL_READ) ) { $buf .= $line; if ( strpos($line, 'Sec-WebSocket-Key')!== false ) { $key = substr($line, 19); } else if ( strpos($line, 'User-Agent')!== false ) { break; } } //echo $buf; $sha1 = SHA1($key.KEY_SUFFIX, true); $accept = base64_encode($sha1); $write = "HTTP/1.1 101 Switching Protocols\n"; $write .= "Upgrade: websocket\n"; $write .= "connection: Upgrade\n"; $write .= "Sec-Websocket-Accept: $accept\n"; //$write .= "Sec-Websocket-Extensions: extension\n"; socket_write( $client, $write, strlen($write) ); } socket_close($sock); ?> I run the php script in this way: F:\xampp\php\php -q D:\websocket_server.php Question: Suppose if It's all correct, I keep looking at chrome debugger network section and It's pending and I expected that after this process I should see an onopen event in js console, what is going on? Am I expecting wrong? Should the connection between sever and client go from 0 state to 1 state after this process or It needs more work to establish an open state?
I found the problems: mistakes: 1: reading the last character in the line of the sec-websocket-key which made the calculation of the sec-websocket-accpet wrong on line 18 2: Didn't know 2 things about response header : one is that you need to put \r\n at the end of each line not just \n and seccond is that you need to put two \r\n\r\n after the last line of header, it just doesn't work if it's not two. (lines: 30-33) Now it initiates an onopen event in client. <?php defined('KEY_SUFFIX') ? null : define('KEY_SUFFIX', "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"); error_reporting(E_ALL); set_time_limit(0); ob_implicit_flush(); $sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); socket_bind($sock, 'localhost', 9090); socket_listen($sock); while (true) { $client = socket_accept($sock) or die('socket_accept returned false');; //$buf = socket_read($client, 1024); $buf = null;$key=null; while ( $line = socket_read($client, 2048, PHP_NORMAL_READ) ) { $buf .= $line; if ( strpos($line, 'Sec-WebSocket-Key')!== false ) { $key = substr($line, 19, 24); // <== mistake num 1 here } else if ( strpos($line, 'User-Agent')!== false ) { break; } } //echo $buf; $sha1 = SHA1($key.KEY_SUFFIX, true); $accept = base64_encode($sha1); //mistake num 2 here $write = "HTTP/1.1 101 Switching Protocols\r\n"; $write .= "Upgrade: websocket\r\n"; $write .= "connection: Upgrade\r\n"; $write .= "Sec-Websocket-Accept: $accept\r\n\r\n"; socket_write( $client, $write, strlen($write) ); } socket_close($sock); ?>