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);
};
?> ``
So basically I have to work on this loan calculator loancalc.000webhostapp.com
I have looked at other pages on this site "how to submit form without page reload?" but this isn't completely relevant to what i'm working on. So far i've added this into the jquery part of the page...
jQuery('qis-register').on('submit', 'input', function(){
event.preventDefault();
var name = $("input#yourname").val();
var email = $("input#youremail").val();
if (name == ""){
$("input#yourname").focus;
return false;
}
else{
}
if (email == ""){
$("input#youremail").focus;
return false;
}
});
But i'm told there is also two other scripts that I need to work with, I'm not really too experienced with php so not sure what's going on, the two php scripts I have to work with are called quick-interest-slider.php and register.php,
//qis_verify_application in register.php
function qis_verify_application(&$values, &$errors) {
$application = qis_get_stored_application();
$register = qis_get_stored_application_messages();
$arr = array_map('array_shift', $application);
foreach ($arr as $key => $value) {
if ($application[$key]['type'] == 'multi') {
$d = explode(",",$application[$key]['options']);
foreach ($d as $item) {
$values[$key] .= $values[$key.$item];
}
}
if ($application[$key]['required'] == 'checked' && $register['use'.$application[$key]['section']] && (empty($values[$key]) || $values[$key] == 'Select...'))
$errors[$key] = 'error';
}
$filenames = array('identityproof','addressproof');
foreach($filenames as $item) {
$tmp_name = $_FILES[$item]['tmp_name'];
$name = $_FILES[$item]['name'];
$size = $_FILES[$item]['size'];
if (file_exists($tmp_name)) {
if ($size > $register['attach_size']) $errors['attach'.$item] = $register['attach_error_size'];
$ext = strtolower(substr(strrchr($name,'.'),1));
if (strpos($register['attach_type'],$ext) === false) $errors['attach'.$item] = $register['attach_error_type'];
}
}
return (count($errors) == 0);
}
//qis_process_application in register.php
function qis_process_application($values) {
global $post;
$content='';
$register = qis_get_stored_register ('default');
$applicationmessages = qis_get_stored_application_messages();
$settings = qis_get_stored_settings();
$auto = qis_get_stored_autoresponder();
$application = qis_get_stored_application();
$message = get_option('qis_messages');
$arr = array_map('array_shift', $application);
if ($message) {
$count = count($message);
for($i = 0; $i <= $count; $i++) {
if ($message[$i]['reference'] == $values['reference']) {
$values['complete'] = 'Completed';
$message[$i] = $values;
update_option('qis_messages',$message);
}
}
}
$filenames = array('identityproof','addressproof');
$attachments = array();
if ( ! function_exists( 'wp_handle_upload' ) ) {
require_once( ABSPATH . 'wp-admin/includes/file.php' );
}
add_filter( 'upload_dir', 'qis_upload_dir' );
$dir = (realpath(WP_CONTENT_DIR . '/uploads/qis/') ? '/uploads/qis/' : '/uploads/');
foreach($filenames as $item) {
$filename = $_FILES[$item]['tmp_name'];
if (file_exists($filename)) {
$name = $values['reference'].'-'.$_FILES[$item]['name'];
$name = trim(preg_replace('/[^A-Za-z0-9. ]/', '', $name));
$name = str_replace(' ','-',$name);
$_FILES[$item]['name'] = $name;
$uploadedfile = $_FILES[$item];
$upload_overrides = array( 'test_form' => false );
$movefile = wp_handle_upload( $uploadedfile, $upload_overrides );
array_push($attachments , WP_CONTENT_DIR .$dir.$name);
}
}
remove_filter( 'upload_dir', 'qis_upload_dir' );
$content = qis_build_complete_message($values,$application,$arr,$register);
qis_send_full_notification ($register,$values,$content,true,$attachments);
qis_send_full_confirmation ($auto,$values,$content,$register);
}
function qis_loop in quick-interest-slider.php
function qis_loop($atts) {
$qppkey = get_option('qpp_key');
if (!$qppkey['authorised']) {
$atts['formheader'] = $atts['loanlabel'] = $atts['termlabel'] = $atts['application'] = $atts['applynow'] = $atts['interestslider'] = $atts['intereselector']= $atts['usecurrencies'] = $atts['usefx'] = $atts['usedownpayment'] = false;
if ($atts['interesttype'] == 'amortization' || $atts['interesttype'] == 'amortisation') $atts['interesttype'] = 'compound';
}
global $post;
// Apply Now Button
if (!empty($_POST['qisapply'])) {
$settings = qis_get_stored_settings();
$formvalues = $_POST;
$url = $settings['applynowaction'];
if ($settings['applynowquery']) $url = $url.'?amount='.$_POST['loan-amount'].'&period='.$_POST['loan-period'];
echo "<p>".__('Redirecting....','quick-interest-slider')."</p><meta http-equiv='refresh' content='0;url=$url' />";
die();
// Application Form
} elseif (!empty($_POST['qissubmit'])) {
$formvalues = $_POST;
$formerrors = array();
if (!qis_verify_form($formvalues, $formerrors)) {
return qis_display($atts,$formvalues, $formerrors,null);
} else {
qis_process_form($formvalues);
$apply = qis_get_stored_application_messages();
if ($apply['enable'] || $atts['parttwo']) return qis_display_application($formvalues,array(),'checked');
else return qis_display($atts,$formvalues, array(),'checked');
}
// Part 2 Application
} elseif (!empty($_POST['part2submit'])) {
$formvalues = $_POST;
$formerrors = array();
if (!qis_verify_application($formvalues, $formerrors)) {
return qis_display_application($formvalues, $formerrors,null);
} else {
qis_process_application($formvalues);
return qis_display_result($formvalues);
}
// Default Display
} else {
$formname = $atts['formname'] == 'alternate' ? 'alternate' : '';
$settings = qis_get_stored_settings();
$values = qis_get_stored_register($formname);
$values['formname'] = $formname;
$arr = explode(",",$settings['interestdropdownvalues']);
$values['interestdropdown'] = $arr[0];
$digit1 = mt_rand(1,10);
$digit2 = mt_rand(1,10);
if( $digit2 >= $digit1 ) {
$values['thesum'] = "$digit1 + $digit2";
$values['answer'] = $digit1 + $digit2;
} else {
$values['thesum'] = "$digit1 - $digit2";
$values['answer'] = $digit1 - $digit2;
}
return qis_display($atts,$values ,array(),null);
}
}
Do I have to edit any of the php and I also don't know what I have to write considering the php.
You can use what is called Ajax to submit the data to the server via POST.
Create a button and give it a class of qis-register, then give each of your input fields a class that matches it's name. Then just add that field to the data object that I have following the format within it.
jQuery(document).on('click', '.qis-register', function(){
var name = $("input#yourname").val();
var email = $("input#youremail").val();
if (name == ""){
$("input#yourname").focus;
}
else if (email == ""){
$("input#youremail").focus;
}
else{
jQuery.ajax({
type: "POST",
url: "your_php_here.php",
data: {
name:name,
email:email,
qissubmit:$(".qissubmit").val(),
qisapply:$(".qisapply").val(),
part2submit:$(".part2submit").val(),
},
done: function(msg){
console.log(msg);
}
});
}
});
Im using PHP socket and im trying to connect it using js .
my JS code is :
var socket = new WebSocket("ws://localhost:9090/");
setTimeout(
socket.onopen = function()
{
try {
socket.send('\n');
}catch (e){
alert(e);
}
try {
socket.send('{"link":"1"}');
}catch (e){
alert(e);
}
alert("Connected");
// Web Socket is connected, send data using send()
}
, 5000);
And PHP code is :
$host = '127.0.0.1';
$port = '9090';
$null = NULL;
include_once ("TransmissionRPC.php");
$rpc = new TransmissionRPC();
$rpc->return_as_array = true;
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
socket_set_option($socket, SOL_SOCKET, SO_REUSEADDR, 1);
socket_bind($socket, 0, $port);
socket_listen($socket);
socket_set_block($socket);
$clients = array($socket);
while(true){
$changed = $clients;
socket_select($changed, $null, $null, 0, 10);
if (in_array($socket, $changed)){
$socket_new = socket_accept($socket);
$clients[] = $socket_new;
print_r($clients);
$header = socket_read($socket_new, 1024);
perform_handshaking($header, $socket_new, $host, $port);
socket_getpeername($socket_new, $ip);
//make room for new socket
$found_socket = array_search($socket, $changed);
unset($changed[$found_socket]);
}
foreach($changed as $changed_socket){
while($input = socket_read($changed_socket, 1024)){
print_r($input);
$received_text = trim($input);
$recived = json_decode($received_text);
if (array_key_exists('session', $recived)){
$session_id = $recived->{'session'};
$info = $rpc->get($session_id, array());
send_message(json_encode($info), 1);
} else if(array_key_exists('link', $recived)) {
$link = $recived->{'link'};
$result = $rpc->sstats();
$test_torrent = "http://www.slackware.com/torrents/slackware64-13.1-install-dvd.torrent";
$result = $rpc->add( $test_torrent, '/home/ftpacc/domains/ali.com/public_html/' );
send_message(json_encode($result), 1);
}
break 2;
}
$buf = #socket_read($changed_socket, 1024, PHP_NORMAL_READ);
if ($buf === false) {
$found_socket = array_search($changed_socket, $clients);
socket_getpeername($changed_socket, $ip);
unset($clients[$found_socket]);
$response = mask(json_encode(array('type' => 'system', 'message' => $ip . ' disconnected \n')));
echo "DC";
}
}
}
function perform_handshaking($receved_header, $client_conn, $host, $port)
{
$headers = array();
$lines = preg_split("/\r\n/", $receved_header);
foreach ($lines as $line){
$line = chop($line);
if (preg_match('/\A(\S+): (.*)\z/', $line, $matches)) {
$headers[$matches[1]] = $matches[2];
}
}
}
function mask($text)
{
$b1 = 0x80 | (0x1 & 0x0f);
$length = strlen($text);
if ($length <= 125)
$header = pack('CC', $b1, $length);
elseif ($length > 125 && $length < 65536)
$header = pack('CCn', $b1, 126, $length);
elseif ($length >= 65536)
$header = pack('CCNN', $b1, 127, $length);
return $header . $text;
}
function send_message($msg, $reciver_id)
{
global $clients;
#socket_send($clients[$reciver_id] , $msg , strlen($msg) , 0);
var_dump($clients);
return true;
}
When im using socket.send('{"link":"1"}'); not working .
Its give me this error :
InvalidStateError: An attempt was made to use an object that is not, or is no longer, usable
How can i fix this problem ?
Notice : Its working when im connecting to socket via TELNET .
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);
In my project I have a PHP function that parses an HTML page and retrieves meta tags correctly. When I run my function for an aspx page this fails and doesn't create return data even though the aspx page in question has correctly set the meta tags.
The function is:
function getUrlData($url)
{
$result = false;
$contents = getUrlContents($url);
if (isset($contents) && is_string($contents))
{
$title = null;
$metaTags = null;
preg_match('/<title>([^>]*)<\/title>/si', $contents, $match );
if (isset($match) && is_array($match) && count($match) > 0)
{
$title = strip_tags($match[1]);
}
preg_match_all('/<[\s]*meta[\s]*name="?' . '([^>"]*)"?[\s]*' . 'content="? ([^>"]*)"?[\s]*[\/]?[\s]*>/si', $contents, $match);
if (isset($match) && is_array($match) && count($match) == 3)
{
$originals = $match[0];
$names = $match[1];
$values = $match[2];
if (count($originals) == count($names) && count($names) == count($values))
{
$metaTags = array();
for ($i=0, $limiti=count($names); $i < $limiti; $i++)
{
$metaTags[$names[$i]] = array (
'html' => htmlentities($originals[$i]),
'value' => $values[$i]
);
}
}
}
$result = array (
'title' => $title,
'metaTags' => $metaTags
);
}
return $result;
}
function getUrlContents($url, $maximumRedirections = null, $currentRedirection = 0)
{
$result = false;
$contents = #file_get_contents($url);
// Check if we need to go somewhere else
if (isset($contents) && is_string($contents))
{
preg_match_all('/<[\s]*meta[\s]*http-equiv="?REFRESH"?' . '[\s]*content="?[0-9]*;[\s]*URL[\s]*=[\s]*([^>"]*)"?' . '[\s]*[\/]?[\s]*>/si', $contents, $match);
if (isset($match) && is_array($match) && count($match) == 2 && count($match[1]) == 1)
{
if (!isset($maximumRedirections) || $currentRedirection < $maximumRedirections)
{
return getUrlContents($match[1][0], $maximumRedirections, ++$currentRedirection);
}
$result = false;
}
else
{
$result = $contents;
}
}
return $contents;
}
How is it possible to read meta tags from aspx pages?
Thanks in advance
AM
There might be a easier way to do this using get_meta_tags
e.g.
<?php
// Load
$tags = get_meta_tags('http://www.example.com/');
// Debug
echo "<pre>";
print_r($tags);
echo "</pre>";
?>